Add x prefix to v850e case for handling --with-cpu=v850e.
[official-gcc.git] / gcc / ada / gnat_ug.texi
blobfa370e18a2b4611db16fe1378f50bb56b3ee8d5e
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  GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com).    o
24 @c                                                                            o
25 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
27 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
29 @c                           GNAT_UG Style Guide
31 @c  1. Always put a @noindent on the line before the first paragraph
32 @c     after any of these commands:
34 @c          @chapter
35 @c          @section
36 @c          @subsection
37 @c          @subsubsection
38 @c          @subsubsubsection
40 @c          @end smallexample
41 @c          @end itemize
42 @c          @end enumerate
44 @c  2. DO NOT use @example. Use @smallexample instead.
46 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
47 @c     command must be preceded by two empty lines
49 @c  4. The @item command must be on a line of its own if it is in an
50 @c     @itemize or @enumerate command.
52 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
53 @c     or "ali".
55 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
57 @ifset vms
58 @setfilename gnat_ug_vms.info
59 @settitle GNAT User's Guide for OpenVMS Alpha
60 @end ifset
62 @ifset wnt
63 @setfilename gnat_ug_wnt.info
64 @settitle GNAT User's Guide for Windows NT
65 @end ifset
67 @ifset unx
68 @setfilename gnat_ug_unx.info
69 @settitle GNAT User's Guide for Unix Platforms
70 @end ifset
72 @ifset vxworks
73 @setfilename gnat_ug_vxw.info
74 @settitle GNAT User's Guide for Cross Platforms
75 @end ifset
77 @include gcc-common.texi
79 @setchapternewpage odd
80 @syncodeindex fn cp
81 @c %**end of header
83 @titlepage
85 @ifset vms
86 @title GNAT User's Guide
87 @center @titlefont{for OpenVMS Alpha}
88 @end ifset
90 @ifset wnt
91 @title GNAT User's Guide
92 @center @titlefont{for Windows NT}
93 @end ifset
95 @ifset unx
96 @title GNAT User's Guide
97 @center @titlefont{for Unix Platforms}
98 @end ifset
100 @ifset vxworks
101 @title GNAT User's Guide
102 @center @titlefont{for Cross Platforms}
103 @end ifset
105 @subtitle GNAT, The GNU Ada 95 Compiler
106 @subtitle GNAT Version for GCC @value{version-GCC}
108 @author Ada Core Technologies, Inc.
110 @page
111 @vskip 0pt plus 1filll
113 Copyright @copyright{} 1995-2002, Free Software Foundation
115 Permission is granted to copy, distribute and/or modify this document
116 under the terms of the GNU Free Documentation License, Version 1.1
117 or any later version published by the Free Software Foundation;
118 with the Invariant Sections being ``GNU Free Documentation License'', with the
119 Front-Cover Texts being
120 @ifset vms
121 ``GNAT User's Guide for OpenVMS Alpha'',
122 @end ifset
123 @ifset wnt
124 ``GNAT User's Guide for Windows NT'',
125 @end ifset
126 @ifset unx
127 ``GNAT User's Guide for Unix Platforms'',
128 @end ifset
129 @ifset vxworks
130 ``GNAT User's Guide for Cross Platforms'',
131 @end ifset
132 and with no Back-Cover Texts.
133 A copy of the license is included in the section entitled ``GNU
134 Free Documentation License''.
136 @end titlepage
138 @ifnottex
139 @node Top, About This Guide, (dir), (dir)
140 @top GNAT User's Guide
142 @ifset vms
143 GNAT User's Guide for OpenVMS Alpha
144 @end ifset
146 @ifset wnt
147 GNAT User's Guide for Windows NT
148 @end ifset
150 @ifset unx
151 GNAT User's Guide for Unix Platforms
152 @end ifset
154 @ifset vxworks
155 GNAT User's Guide for Cross Platforms
156 @end ifset
158 GNAT, The GNU Ada 95 Compiler
160 GNAT Version for GCC @value{version-GCC}
162 Ada Core Technologies, Inc.
164 Copyright @copyright{} 1995-2002, Free Software Foundation
166 Permission is granted to copy, distribute and/or modify this document
167 under the terms of the GNU Free Documentation License, Version 1.1
168 or any later version published by the Free Software Foundation;
169 with the Invariant Sections being ``GNU Free Documentation License'', with the
170 Front-Cover Texts being
171 @ifset vms
172 ``GNAT User's Guide for OpenVMS Alpha'',
173 @end ifset
174 @ifset wnt
175 ``GNAT User's Guide for Windows NT'',
176 @end ifset
177 @ifset unx
178 ``GNAT User's Guide for Unix Platforms'',
179 @end ifset
180 @ifset vxworks
181 ``GNAT User's Guide for Cross Platforms'',
182 @end ifset
183 and with no Back-Cover Texts.
184 A copy of the license is included in the section entitled ``GNU
185 Free Documentation License''.
187 @menu
188 * About This Guide::
189 @ifset vxworks
190 * Preliminary Note for Cross Platform Users::
191 @end ifset
192 * Getting Started with GNAT::
193 * The GNAT Compilation Model::
194 * Compiling Using gcc::
195 * Binding Using gnatbind::
196 * Linking Using gnatlink::
197 * The GNAT Make Program gnatmake::
198 * Renaming Files Using gnatchop::
199 * Configuration Pragmas::
200 * Handling Arbitrary File Naming Conventions Using gnatname::
201 * GNAT Project Manager::
202 * Elaboration Order Handling in GNAT::
203 * The Cross-Referencing Tools gnatxref and gnatfind::
204 * File Name Krunching Using gnatkr::
205 * Preprocessing Using gnatprep::
206 @ifset vms
207 * The GNAT Run-Time Library Builder gnatlbr::
208 @end ifset
209 * The GNAT Library Browser gnatls::
210 @ifclear vms
211 * GNAT and Libraries::
212 * Using the GNU make Utility::
213 @ifclear vxworks
214 * Finding Memory Problems with gnatmem::
215 @end ifclear
216 @end ifclear
217 * Finding Memory Problems with GNAT Debug Pool::
218 * Creating Sample Bodies Using gnatstub::
219 * Reducing the Size of Ada Executables with gnatelim::
220 * Other Utility Programs::
221 @ifset vms
222 * Compatibility with DEC Ada::
223 @end ifset
224 * Running and Debugging Ada Programs::
225 * Inline Assembler::
226 @ifset wnt
227 * Microsoft Windows Topics::
228 @end ifset
229 @ifset vxworks
230 * VxWorks Topics::
231 * LynxOS Topics::
232 @end ifset
233 * Performance Considerations::
234 * GNU Free Documentation License::
235 * Index::
237  --- The Detailed Node Listing ---
239 About This Guide
241 * What This Guide Contains::
242 * What You Should Know before Reading This Guide::
243 * Related Information::
244 * Conventions::
246 @ifset vxworks
247 Preliminary Note for Cross Platform Users::
248 @end ifset
250 Getting Started with GNAT
252 * Running GNAT::
253 @ifclear vxworks
254 * Running a Simple Ada Program::
255 @end ifclear
256 @ifset vxworks
257 * Building a Simple Ada Program::
258 * Executing a Program on VxWorks::
259 @end ifset
260 * Running a Program with Multiple Units::
261 * Using the gnatmake Utility::
262 @ifset vms
263 * Editing with Emacs::
264 @end ifset
266 The GNAT Compilation Model
268 * Source Representation::
269 * Foreign Language Representation::
270 * File Naming Rules::
271 * Using Other File Names::
272 * Alternative File Naming Schemes::
273 * Generating Object Files::
274 * Source Dependencies::
275 * The Ada Library Information Files::
276 * Binding an Ada Program::
277 * Mixed Language Programming::
278 * Building Mixed Ada & C++ Programs::
279 * Comparison between GNAT and C/C++ Compilation Models::
280 * Comparison between GNAT and Conventional Ada Library Models::
282 Foreign Language Representation
284 * Latin-1::
285 * Other 8-Bit Codes::
286 * Wide Character Encodings::
288 Compiling Ada Programs With gcc
290 * Compiling Programs::
291 * Switches for gcc::
292 * Search Paths and the Run-Time Library (RTL)::
293 * Order of Compilation Issues::
294 * Examples::
296 Switches for gcc
298 * Output and Error Message Control::
299 * Debugging and Assertion Control::
300 * Run-Time Checks::
301 * Stack Overflow Checking::
302 * Run-Time Control::
303 * Validity Checking::
304 * Style Checking::
305 * Using gcc for Syntax Checking::
306 * Using gcc for Semantic Checking::
307 * Compiling Ada 83 Programs::
308 * Character Set Control::
309 * File Naming Control::
310 * Subprogram Inlining Control::
311 * Auxiliary Output Control::
312 * Debugging Control::
313 * Units to Sources Mapping Files::
315 Binding Ada Programs With gnatbind
317 * Running gnatbind::
318 * Generating the Binder Program in C::
319 * Consistency-Checking Modes::
320 * Binder Error Message Control::
321 * Elaboration Control::
322 * Output Control::
323 * Binding with Non-Ada Main Programs::
324 * Binding Programs with No Main Subprogram::
325 * Summary of Binder Switches::
326 * Command-Line Access::
327 * Search Paths for gnatbind::
328 * Examples of gnatbind Usage::
330 Linking Using gnatlink
332 * Running gnatlink::
333 * Switches for gnatlink::
334 * Setting Stack Size from gnatlink::
335 * Setting Heap Size from gnatlink::
337 The GNAT Make Program gnatmake
339 * Running gnatmake::
340 * Switches for gnatmake::
341 * Mode Switches for gnatmake::
342 * Notes on the Command Line::
343 * How gnatmake Works::
344 * Examples of gnatmake Usage::
346 Renaming Files Using gnatchop
348 * Handling Files with Multiple Units::
349 * Operating gnatchop in Compilation Mode::
350 * Command Line for gnatchop::
351 * Switches for gnatchop::
352 * Examples of gnatchop Usage::
354 Configuration Pragmas
356 * Handling of Configuration Pragmas::
357 * The Configuration Pragmas Files::
359 Handling Arbitrary File Naming Conventions Using gnatname
361 * Arbitrary File Naming Conventions::
362 * Running gnatname::
363 * Switches for gnatname::
364 * Examples of gnatname Usage::
366 GNAT Project Manager
368 * Introduction::
369 * Examples of Project Files::
370 * Project File Syntax::
371 * Objects and Sources in Project Files::
372 * Importing Projects::
373 * Project Extension::
374 * External References in Project Files::
375 * Packages in Project Files::
376 * Variables from Imported Projects::
377 * Naming Schemes::
378 * Library Projects::
379 * Switches Related to Project Files::
380 * Tools Supporting Project Files::
381 * An Extended Example::
382 * Project File Complete Syntax::
384 Elaboration Order Handling in GNAT
386 * Elaboration Code in Ada 95::
387 * Checking the Elaboration Order in Ada 95::
388 * Controlling the Elaboration Order in Ada 95::
389 * Controlling Elaboration in GNAT - Internal Calls::
390 * Controlling Elaboration in GNAT - External Calls::
391 * Default Behavior in GNAT - Ensuring Safety::
392 * Elaboration Issues for Library Tasks::
393 * Mixing Elaboration Models::
394 * What to Do If the Default Elaboration Behavior Fails::
395 * Elaboration for Access-to-Subprogram Values::
396 * Summary of Procedures for Elaboration Control::
397 * Other Elaboration Order Considerations::
399 The Cross-Referencing Tools gnatxref and gnatfind
401 * gnatxref Switches::
402 * gnatfind Switches::
403 * Project Files for gnatxref and gnatfind::
404 * Regular Expressions in gnatfind and gnatxref::
405 * Examples of gnatxref Usage::
406 * Examples of gnatfind Usage::
408 File Name Krunching Using gnatkr
410 * About gnatkr::
411 * Using gnatkr::
412 * Krunching Method::
413 * Examples of gnatkr Usage::
415 Preprocessing Using gnatprep
417 * Using gnatprep::
418 * Switches for gnatprep::
419 * Form of Definitions File::
420 * Form of Input Text for gnatprep::
422 @ifset vms
423 The GNAT Run-Time Library Builder gnatlbr
425 * Running gnatlbr::
426 * Switches for gnatlbr::
427 * Examples of gnatlbr Usage::
428 @end ifset
430 The GNAT Library Browser gnatls
432 * Running gnatls::
433 * Switches for gnatls::
434 * Examples of gnatls Usage::
436 @ifclear vms
438 GNAT and Libraries
440 * Creating an Ada Library::
441 * Installing an Ada Library::
442 * Using an Ada Library::
443 * Creating an Ada Library to be Used in a Non-Ada Context::
444 * Rebuilding the GNAT Run-Time Library::
446 Using the GNU make Utility
448 * Using gnatmake in a Makefile::
449 * Automatically Creating a List of Directories::
450 * Generating the Command Line Switches::
451 * Overcoming Command Line Length Limits::
453 @ifclear vxworks
454 Finding Memory Problems with gnatmem
456 * Running gnatmem (GDB Mode)::
457 * Running gnatmem (GMEM Mode)::
458 * Switches for gnatmem::
459 * Examples of gnatmem Usage::
460 * GDB and GMEM Modes::
461 * Implementation Note::
463 @end ifclear
464 @end ifclear
466 Finding Memory Problems with GNAT Debug Pool
468 Creating Sample Bodies Using gnatstub
470 * Running gnatstub::
471 * Switches for gnatstub::
473 Reducing the Size of Ada Executables with gnatelim
475 * About gnatelim::
476 * Eliminate Pragma::
477 * Tree Files::
478 * Preparing Tree and Bind Files for gnatelim::
479 * Running gnatelim::
480 * Correcting the List of Eliminate Pragmas::
481 * Making Your Executables Smaller::
482 * Summary of the gnatelim Usage Cycle::
484 Other Utility Programs
486 * Using Other Utility Programs with GNAT::
487 * The gnatpsta Utility Program::
488 * The External Symbol Naming Scheme of GNAT::
489 * Ada Mode for Glide::
490 * Converting Ada Files to html with gnathtml::
491 @ifset vms
492 * LSE::
493 @end ifset
495 @ifset vms
496 Compatibility with DEC Ada
498 * Ada 95 Compatibility::
499 * Differences in the Definition of Package System::
500 * Language-Related Features::
501 * The Package STANDARD::
502 * The Package SYSTEM::
503 * Tasking and Task-Related Features::
504 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
505 * Pragmas and Pragma-Related Features::
506 * Library of Predefined Units::
507 * Bindings::
508 * Main Program Definition::
509 * Implementation-Defined Attributes::
510 * Compiler and Run-Time Interfacing::
511 * Program Compilation and Library Management::
512 * Input-Output::
513 * Implementation Limits::
514 * Tools::
516 Language-Related Features
518 * Integer Types and Representations::
519 * Floating-Point Types and Representations::
520 * Pragmas Float_Representation and Long_Float::
521 * Fixed-Point Types and Representations::
522 * Record and Array Component Alignment::
523 * Address Clauses::
524 * Other Representation Clauses::
526 Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
528 * Assigning Task IDs::
529 * Task IDs and Delays::
530 * Task-Related Pragmas::
531 * Scheduling and Task Priority::
532 * The Task Stack::
533 * External Interrupts::
535 Pragmas and Pragma-Related Features
537 * Restrictions on the Pragma INLINE::
538 * Restrictions on the Pragma INTERFACE::
539 * Restrictions on the Pragma SYSTEM_NAME::
541 Library of Predefined Units
543 * Changes to DECLIB::
545 Bindings
547 * Shared Libraries and Options Files::
548 * Interfaces to C::
549 @end ifset
551 Running and Debugging Ada Programs
553 * The GNAT Debugger GDB::
554 * Running GDB::
555 * Introduction to GDB Commands::
556 * Using Ada Expressions::
557 * Calling User-Defined Subprograms::
558 * Using the Next Command in a Function::
559 * Ada Exceptions::
560 * Ada Tasks::
561 * Debugging Generic Units::
562 * GNAT Abnormal Termination or Failure to Terminate::
563 * Naming Conventions for GNAT Source Files::
564 * Getting Internal Debugging Information::
565 * Stack Traceback::
567 Inline Assembler
569 * Basic Assembler Syntax::
570 * A Simple Example of Inline Assembler::
571 * Output Variables in Inline Assembler::
572 * Input Variables in Inline Assembler::
573 * Inlining Inline Assembler Code::
574 * Other Asm Functionality::
575 * A Complete Example::
577 @ifset wnt
578 Microsoft Windows Topics
580 * Using GNAT on Windows::
581 * GNAT Setup Tool::
582 * CONSOLE and WINDOWS subsystems::
583 * Temporary Files::
584 * Mixed-Language Programming on Windows::
585 * Windows Calling Conventions::
586 * Introduction to Dynamic Link Libraries (DLLs)::
587 * Using DLLs with GNAT::
588 * Building DLLs with GNAT::
589 * GNAT and Windows Resources::
590 * GNAT and COM/DCOM Objects::
591 @end ifset
593 @ifset vxworks
594 VxWorks Topics
596 * Kernel Configuration for VxWorks::
597 * Kernel Compilation Issues for VxWorks::
598 * Handling Relocation Issues for PowerPc Targets::
599 * Support for Software Floating Point on PowerPC Processors::
600 * Interrupt Handling for VxWorks::
601 * Simulating Command Line Arguments for VxWorks::
602 * Debugging Issues for VxWorks::
603 * Using GNAT from the Tornado 2 Project Facility::
604 * Frequently Asked Questions for VxWorks::
606 LynxOS Topics
608 * Getting Started with GNAT on LynxOS::
609 * Kernel Configuration for LynxOS::
610 * Patch Level Issues for LynxOS::
611 * Debugging Issues for LynxOS::
612 * An Example Debugging Session for LynxOS::
613 @end ifset
615 Performance Considerations
617 * Controlling Run-Time Checks::
618 * Optimization Levels::
619 * Debugging Optimized Code::
620 * Inlining of Subprograms::
621 @ifset vms
622 * Coverage Analysis::
623 @end ifset
625 * Index::
626 @end menu
627 @end ifnottex
629 @node About This Guide
630 @unnumbered About This Guide
632 @noindent
633 @ifset vms
634 This guide describes the use of of GNAT, a full language compiler for the Ada
635 95 programming language, implemented on DIGITAL OpenVMS Alpha Systems.
636 @end ifset
637 @ifclear vms
638 This guide describes the use of GNAT, a compiler and software development
639 toolset for the full Ada 95 programming language.
640 @end ifclear
641 It describes the features of the compiler and tools, and details
642 how to use them to build Ada 95 applications.
644 @menu
645 * What This Guide Contains::
646 * What You Should Know before Reading This Guide::
647 * Related Information::
648 * Conventions::
649 @end menu
651 @node What This Guide Contains
652 @unnumberedsec What This Guide Contains
654 @noindent
655 This guide contains the following chapters:
656 @itemize @bullet
657 @ifset vxworks
658 @item
659 @ref{Preliminary Note for Cross Platform Users}, describes the basic
660 differences between the cross and native versions of GNAT.
661 @end ifset
662 @item
663 @ref{Getting Started with GNAT}, describes how to get started compiling
664 and running Ada programs with the GNAT Ada programming environment.
665 @item
666 @ref{The GNAT Compilation Model}, describes the compilation model used
667 by GNAT.
668 @item
669 @ref{Compiling Using gcc}, describes how to compile
670 Ada programs with @code{gcc}, the Ada compiler.
671 @item
672 @ref{Binding Using gnatbind}, describes how to
673 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
674 utility.
675 @item
676 @ref{Linking Using gnatlink},
677 describes @code{gnatlink}, a
678 program that provides for linking using the GNAT run-time library to
679 construct a program. @code{gnatlink} can also incorporate foreign language
680 object units into the executable.
681 @item
682 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
683 utility that automatically determines the set of sources
684 needed by an Ada compilation unit, and executes the necessary compilations
685 binding and link.
686 @item
687 @ref{Renaming Files Using gnatchop}, describes
688 @code{gnatchop}, a utility that allows you to preprocess a file that
689 contains Ada source code, and split it into one or more new files, one
690 for each compilation unit.
691 @item
692 @ref{Configuration Pragmas}, describes the configuration pragmas handled by GNAT.
693 @item
694 @ref{Handling Arbitrary File Naming Conventions Using gnatname}, shows how to override
695 the default GNAT file naming conventions, either for an individual unit or globally.
696 @item
697 @ref{GNAT Project Manager}, describes how to use project files to organize large projects.
698 @item
699 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps you deal with
700 elaboration order issues.
701 @item
702 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
703 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
704 way to navigate through sources.
705 @item
706 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
707 file name krunching utility, used to handle shortened
708 file names on operating systems with a limit on the length of names.
709 @item
710 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
711 preprocessor utility that allows a single source file to be used to
712 generate multiple or parameterized source files, by means of macro
713 substitution.
714 @item
715 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
716 utility that displays information about compiled units, including dependences
717 on the corresponding sources files, and consistency of compilations.
718 @ifclear vms
719 @item
720 @ref{GNAT and Libraries}, describes the process of creating and using
721 Libraries with GNAT. It also describes how to recompile the GNAT run-time
722 library.
724 @item
725 @ref{Using the GNU make Utility}, describes some techniques for using
726 the GNAT toolset in Makefiles.
728 @ifclear vxworks
729 @item
730 @ref{Finding Memory Problems with gnatmem}, describes @code{gnatmem}, a
731 utility that monitors dynamic allocation and deallocation activity in a
732 program, and displays information about incorrect deallocations and sources
733 of possible memory leaks.
734 @end ifclear
735 @end ifclear
736 @item
737 @ref{Finding Memory Problems with GNAT Debug Pool}, describes how to
738 use the GNAT-specific Debug Pool in order to detect as early as possible
739 the use of incorrect memory references.
741 @item
742 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
743 a utility that generates empty but compilable bodies for library units.
745 @item
746 @ref{Reducing the Size of Ada Executables with gnatelim}, describes
747 @code{gnatelim}, a tool which detects unused subprograms and helps
748 the compiler to create a smaller executable for the program.
750 @item
751 @ref{Other Utility Programs}, discusses several other GNAT utilities,
752 including @code{gnatpsta}.
754 @item
755 @ref{Running and Debugging Ada Programs}, describes how to run and debug
756 Ada programs.
758 @item
759 @ref{Inline Assembler}, shows how to use the inline assembly facility in an Ada program.
761 @ifset vxworks
762 @item
763 @ref{VxWorks Topics}, presents information relevant to the VxWorks target for cross-compilation
764 configurations.
766 @item
767 @ref{LynxOS Topics}, presents information relevant to the LynxOS target for cross-compilation
768 configurations.
769 @end ifset
771 @item
772 @ref{Performance Considerations}, reviews the trade offs between using
773 defaults or options in program development.
774 @ifset vms
775 @item
776 @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
777 DEC Ada 83 for OpenVMS Alpha.
778 @end ifset
779 @end itemize
781 @node What You Should Know before Reading This Guide
782 @unnumberedsec What You Should Know before Reading This Guide
784 @cindex Ada 95 Language Reference Manual
785 @noindent
786 This user's guide assumes that you are familiar with Ada 95 language, as
787 described in the International Standard ANSI/ISO/IEC-8652:1995, Jan
788 1995.
790 @node Related Information
791 @unnumberedsec Related Information
793 @noindent
794 For further information about related tools, refer to the following
795 documents:
797 @itemize @bullet
798 @item
799 @cite{GNAT Reference Manual}, which contains all reference
800 material for the GNAT implementation of Ada 95.
802 @item
803 @cite{Ada 95 Language Reference Manual}, which contains all reference
804 material for the Ada 95 programming language.
806 @item
807 @cite{Debugging with GDB}
808 @ifset vms
809 , located in the GNU:[DOCS] directory,
810 @end ifset
811 contains all details on the use of the GNU source-level debugger.
813 @item
814 @cite{GNU Emacs Manual}
815 @ifset vms
816 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
817 @end ifset
818 contains full information on the extensible editor and programming
819 environment Emacs.
821 @end itemize
823 @node Conventions
824 @unnumberedsec Conventions
825 @cindex Conventions
826 @cindex Typographical conventions
828 @noindent
829 Following are examples of the typographical and graphic conventions used
830 in this guide:
832 @itemize @bullet
833 @item
834 @code{Functions}, @code{utility program names}, @code{standard names},
835 and @code{classes}.
837 @item
838 @samp{Option flags}
840 @item
841 @file{File Names}, @file{button names}, and @file{field names}.
843 @item
844 @var{Variables}.
846 @item
847 @emph{Emphasis}.
849 @item
850 [optional information or parameters]
852 @item
853 Examples are described by text
854 @smallexample
855 and then shown this way.
856 @end smallexample
857 @end itemize
859 @noindent
860 Commands that are entered by the user are preceded in this manual by the
861 characters @w{"@code{$ }"} (dollar sign followed by space). If your system
862 uses this sequence as a prompt, then the commands will appear exactly as
863 you see them in the manual. If your system uses some other prompt, then
864 the command will appear with the @code{$} replaced by whatever prompt
865 character you are using.
867 @ifset vxworks
868 @node Preliminary Note for Cross Platform Users
869 @chapter Preliminary Note for Cross Platform Users
871 @noindent
872 The use of GNAT in a cross environment is very similar to its use in a
873 native environment. Most of the tools described in this manual have
874 similar functions and options in both modes. The major
875 difference is that the name of the cross tools includes the target for
876 which the cross compiler is configured. For instance, the cross @command{gnatmake}
877 tool is called @command{@i{target}-gnatmake} where @code{@i{target}} stands for the name of
878 the cross target. Thus, in an environment configured for the
879 target @code{powerpc-wrs-vxworks}, the @command{gnatmake} command is
880 @code{powerpc-wrs-vxworks-gnatmake}. This convention allows the
881 installation of a native and one or several cross development
882 environments at the same location.
884 The tools that are most relevant in a cross environment are:
885 @code{@i{target}-gcc}, @code{@i{target}-gnatmake},
886 @code{@i{target}-gnatbind}, @code{@i{target}-gnatlink} to build cross
887 applications and @code{@i{target}-gnatls} for cross library
888 browsing. @code{@i{target}-gdb} is also usually available for cross
889 debugging in text mode. The graphical debugger interface
890 @code{gvd} is always a native tool but it can be configured to drive
891 the above mentioned cross debugger, thus allowing graphical cross debugging
892 sessions. Some other tools such as  @code{@i{target}-gnatchop},
893 @code{@i{target}-gnatkr}, @code{@i{target}-gnatprep},
894 @code{@i{target}-gnatpsta}, @code{@i{target}-gnatxref}, @code{@i{target}-gnatfind}
895 and @code{@i{target}-gnatname} are also provided for completeness
896 even though they do not differ greatly from their native counterpart.
898 In the rest of this manual, the tools are sometimes designated with
899 their full cross name, and sometimes with their simplified native
900 name.
902 @end ifset
904 @node Getting Started with GNAT
905 @chapter Getting Started with GNAT
907 @ifclear vxworks
908 @noindent
909 This chapter describes some simple ways of using GNAT to build
910 executable Ada programs.
911 @end ifclear
912 @ifset vxworks
913 @noindent
914 This introduction is a starting point for using GNAT to develop
915 and execute Ada 95 programs in a cross environment.
916 It provides some specifics
917 about the GNAT toolchain targeted to the Wind River Sytems' VxWorks/Tornado platform;
918 for other targets please refer to the corresponding chapter later in this manual.
920 Basic familiarity with use of GNAT in a native environment is
921 presumed. For the VxWorks specific part, a knowledge of how to start
922 Tornado's @code{windsh} tool is also presumed.
923 @end ifset
925 @menu
926 * Running GNAT::
927 @ifclear vxworks
928 * Running a Simple Ada Program::
929 @end ifclear
930 @ifset vxworks
931 * Building a Simple Ada Program::
932 * Executing a Program on VxWorks::
933 @end ifset
935 * Running a Program with Multiple Units::
937 * Using the gnatmake Utility::
938 @ifset vms
939 * Editing with Emacs::
940 @end ifset
941 @ifclear vms
942 * Introduction to Glide and GVD::
943 @end ifclear
944 @end menu
946 @node Running GNAT
947 @section Running GNAT
949 @noindent
950 Three steps are needed to create an executable file from an Ada source
951 file:
953 @enumerate
954 @item
955 The source file(s) must be compiled.
956 @item
957 The file(s) must be bound using the GNAT binder.
958 @item
959 @ifclear vxworks
960 All appropriate object files must be linked to produce an executable.
961 @end ifclear
962 @ifset vxworks
963 All appropriate object files must be linked to produce a loadable module.
964 @end ifset
965 @end enumerate
967 @noindent
968 All three steps are most commonly handled by using the @code{gnatmake}
969 utility program that, given the name of the main program, automatically
970 performs the necessary compilation, binding and linking steps.
972 @ifclear vxworks
973 @node Running a Simple Ada Program
974 @section Running a Simple Ada Program
975 @end ifclear
976 @ifset vxworks
977 @node Building a Simple Ada Program
978 @section Building a Simple Ada Program
979 @end ifset
981 @noindent
982 Any text editor may be used to prepare an Ada program. If @code{Glide} is
983 used, the optional Ada mode may be helpful in laying out the program. The
984 program text is a normal text file. We will suppose in our initial
985 example that you have used your editor to prepare the following
986 standard format text file:
988 @smallexample
989 @group
990 @cartouche
991 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
992 @b{procedure} Hello @b{is}
993 @b{begin}
994    Put_Line ("Hello WORLD!");
995 @b{end} Hello;
996 @end cartouche
997 @end group
998 @end smallexample
1000 @noindent
1001 This file should be named @file{hello.adb}.
1002 With the normal default file naming conventions, GNAT requires
1003 that each file
1004 contain a single compilation unit whose file name is the
1005 unit name,
1006 with periods replaced by hyphens; the
1007 extension is @file{ads} for a
1008 spec and @file{adb} for a body.
1009 You can override this default file naming convention by use of the
1010 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1011 Alternatively, if you want to rename your files according to this default
1012 convention, which is probably more convenient if you will be using GNAT
1013 for all your compilations, then the @code{gnatchop} utility
1014 can be used to generate correctly-named source files
1015 (@pxref{Renaming Files Using gnatchop}).
1017 You can compile the program using the following command (@code{$} is used
1018 as the command prompt in the examples in this document):
1020 @ifclear vxworks
1021 @smallexample
1022 $ gcc -c hello.adb
1023 @end smallexample
1024 @end ifclear
1026 @ifset vxworks
1027 @smallexample
1028 $ @i{target}-gcc -c hello.adb
1029 @end smallexample
1030 @end ifset
1032 @noindent
1033 @code{gcc} is the command used to run the compiler. This compiler is
1034 capable of compiling programs in several languages, including Ada 95 and
1035 C. It assumes that you have given it an Ada program if the file extension is
1036 either @file{.ads} or @file{.adb}, and it will then call the GNAT compiler to compile
1037 the specified file.
1039 @ifclear vms
1040 The @option{-c} switch is required. It tells @command{gcc} to only do a
1041 compilation. (For C programs, @command{gcc} can also do linking, but this
1042 capability is not used directly for Ada programs, so the @option{-c}
1043 switch must always be present.)
1044 @end ifclear
1046 This compile command generates a file
1047 @file{hello.o}, which is the object
1048 file corresponding to your Ada program. It also generates an "Ada Library Information" file
1049 @file{hello.ali},
1050 which contains additional information used to check
1051 that an Ada program is consistent.
1052 @ifclear vxworks
1053 To build an executable file,
1054 @end ifclear
1055 @ifset vxworks
1056 To build a downloadable module,
1057 @end ifset
1058 use @code{gnatbind} to bind the program
1059 and @code{gnatlink} to link it. The
1060 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1061 @file{ali} file, but the default extension of @file{.ali} can
1062 be omitted. This means that in the most common case, the argument
1063 is simply the name of the main program:
1065 @ifclear vxworks
1066 @smallexample
1067 $ gnatbind hello
1068 $ gnatlink hello
1069 @end smallexample
1070 @end ifclear
1072 @ifset vxworks
1073 @smallexample
1074 $ @i{target}-gnatbind hello
1075 $ @i{target}-gnatlink hello
1076 @end smallexample
1077 @end ifset
1079 @noindent
1080 A simpler method of carrying out these steps is to use
1081 @command{gnatmake},
1082 a master program that invokes all the required
1083 compilation, binding and linking tools in the correct order. In particular,
1084 @command{gnatmake} automatically recompiles any sources that have been modified
1085 since they were last compiled, or sources that depend
1086 on such modified sources, so that "version skew" is avoided.
1087 @cindex Version skew (avoided by @command{gnatmake})
1089 @ifclear vxworks
1090 @smallexample
1091 $ gnatmake hello.adb
1092 @end smallexample
1093 @end ifclear
1095 @ifset vxworks
1096 @smallexample
1097 $ @i{target}-gnatmake hello.adb
1098 @end smallexample
1099 @end ifset
1101 @ifclear vxworks
1102 @noindent
1103 The result is an executable program called @file{hello}, which can be
1104 run by entering:
1106 @c The following should be removed (BMB 2001-01-23)
1107 @c @smallexample
1108 @c $ ^./hello^$ RUN HELLO^
1109 @c @end smallexample
1111 @smallexample
1112 $ hello
1113 @end smallexample
1115 @noindent
1116 assuming that the current directory is on the search path for executable programs.
1118 @noindent
1119 and, if all has gone well, you will see
1121 @smallexample
1122 Hello WORLD!
1123 @end smallexample
1125 @noindent
1126 appear in response to this command.
1128 @end ifclear
1130 @ifset vxworks
1131 @noindent
1132 The result is a relocatable object called @file{hello}.
1134 @emph{Technical note:} the result of the linking stage is a
1135 relocatable partially-linked object containing all the relevant GNAT
1136 run-time units, in contrast with the executable-format object file found in
1137 native environments.
1140 @node Executing a Program on VxWorks
1141 @section Executing a Program on VxWorks
1143 @noindent
1144 Getting a program to execute involves loading it onto the target, running it, and then (if re-execution is needed) unloading it.
1146 @menu
1147 * Loading and Running the Program::
1148 * Unloading the Program::
1149 @end menu
1151 @node Loading and Running the Program
1152 @subsection Loading and Running the Program
1154 @noindent
1155 An Ada program is loaded and run in the same way as a C program.
1156 Details may be found in the @cite{Tornado User's Guide}.
1158 In order to load and run our simple "Hello World" example, we assume that
1159 the target has access to the disk of the host containing this object and
1160 that its working directory has been set to the directory containing this
1161 object. The commands are typed in Tornado's Windshell. The @code{windsh} prompt
1162 is the @code{->} sequence.
1164 @smallexample
1165 -> vf0=open("/vio/0",2,0)
1166 new symbol "vf0" added to symbol table.
1167 vf0 = 0x2cab48: value = 12 = 0xc
1168 -> ioGlobalStdSet(1,vf0)
1169 value = 1 = 0x1
1170 -> ld < hello
1171 value = 665408 = 0xa2740
1172 -> hello
1173 Hello World
1174 value = 0 = 0x0
1176 @end smallexample
1178 @noindent
1179 The first two commands redirect output to the shell window.
1180 They are only needed if the target server was started without the
1181 @code{-C} option.  The third command loads the module, which is the file
1182 @file{hello} created previously by the @code{@i{target}-gnatmake} command.
1183 Note that for Tornado AE, the @command{ml} command replaces @command{ld}."
1185 The "Hello World" program comprises a procedure named @code{hello}, and this
1186 is the name entered for the procedure in the target server's symbol table
1187 when the module is loaded.  To execute the procedure, type the symbol name @code{hello}
1188 into @code{windsh} as shown in the last command above.
1190 Note that by default the entry point of an Ada program is the name of the main
1191 Ada subprogram in a VxWorks environment. It is possible to use an alternative
1192 name; see the description of @code{gnatbind} options for details.
1194 @node Unloading the Program
1195 @subsection Unloading the Program
1197 @noindent
1198 It is important to remember that
1199 you must unload a program once you have run it. You
1200 cannot load it once and run it several times. If you don't follow
1201 this rule, your program's behavior can be unpredictable, and will most
1202 probably crash.
1204 This effect is due to the implementation of Ada 95's @emph{elaboration} semantics.
1205 The unit elaboration phase comprises a @emph{static} elaboration and a
1206 @emph{dynamic} elaboration. On a native platform they both take place
1207 when the program is run. Thus rerunning the program will repeat the complete
1208 elaboration phase, and the program will run correctly.
1210 On VxWorks, the process is a bit different.
1211 The static elaboration phase is handled by
1212 the loader (typically when you type @code{ld < program_name} in
1213 @code{windsh}). The dynamic phase takes place when the program is run. If the
1214 program is run twice and has not been unloaded and then reloaded, the
1215 second time it is run, the static elaboration phase is skipped.
1216 Variables initialized during the static elaboration phase
1217 may have been modified during the first execution of the program. Thus the
1218 second execution isn't performed on a completely initialized environment.
1220 Note that in C programs, elaboration isn't systematic. Multiple runs without reload
1221 might work, but, even with C programs, if there is an elaboration
1222 phase, you will have to unload your program before re-running it.
1223 @end ifset
1226 @node Running a Program with Multiple Units
1227 @section Running a Program with Multiple Units
1229 @noindent
1230 Consider a slightly more complicated example that has three files: a
1231 main program, and the spec and body of a package:
1233 @smallexample
1234 @cartouche
1235 @group
1236 @b{package} Greetings @b{is}
1237    @b{procedure} Hello;
1238    @b{procedure} Goodbye;
1239 @b{end} Greetings;
1241 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
1242 @b{package} @b{body} Greetings @b{is}
1243    @b{procedure} Hello @b{is}
1244    @b{begin}
1245       Put_Line ("Hello WORLD!");
1246    @b{end} Hello;
1248    @b{procedure} Goodbye @b{is}
1249    @b{begin}
1250       Put_Line ("Goodbye WORLD!");
1251    @b{end} Goodbye;
1252 @b{end} Greetings;
1253 @end group
1255 @group
1256 @b{with} Greetings;
1257 @b{procedure} Gmain @b{is}
1258 @b{begin}
1259    Greetings.Hello;
1260    Greetings.Goodbye;
1261 @b{end} Gmain;
1262 @end group
1263 @end cartouche
1264 @end smallexample
1266 @noindent
1267 Following the one-unit-per-file rule, place this program in the
1268 following three separate files:
1270 @table @file
1271 @item greetings.ads
1272 spec of package @code{Greetings}
1274 @item greetings.adb
1275 body of package @code{Greetings}
1277 @item gmain.adb
1278 body of main program
1279 @end table
1281 @noindent
1282 To build an executable version of
1283 this program, we could use four separate steps to compile, bind, and link
1284 the program, as follows:
1286 @ifclear vxworks
1287 @smallexample
1288 $ gcc -c gmain.adb
1289 $ gcc -c greetings.adb
1290 $ gnatbind gmain
1291 $ gnatlink gmain
1292 @end smallexample
1293 @end ifclear
1295 @ifset vxworks
1296 @smallexample
1297 $ @i{target}-gcc -c gmain.adb
1298 $ @i{target}-gcc -c greetings.adb
1299 $ @i{target}-gnatbind gmain
1300 $ @i{target}-gnatlink gmain
1301 @end smallexample
1302 @end ifset
1304 @noindent
1305 Note that there is no required order of compilation when using GNAT.
1306 In particular it is perfectly fine to compile the main program first.
1307 Also, it is not necessary to compile package specs in the case where
1308 there is an accompanying body; you only need to compile the body. If you want
1309 to submit these files to the compiler for semantic checking and not code generation,
1310 then use the
1311 @option{-gnatc} switch:
1313 @ifclear vxworks
1314 @smallexample
1315    $ gcc -c greetings.ads -gnatc
1316 @end smallexample
1317 @end ifclear
1319 @ifset vxworks
1320 @smallexample
1321 $ @i{target}-gcc -c greetings.ads -gnatc
1322 @end smallexample
1323 @end ifset
1325 @noindent
1326 Although the compilation can be done in separate steps as in the
1327 above example, in practice it is almost always more convenient
1328 to use the @code{gnatmake} tool. All you need to know in this case
1329 is the name of the main program's source file. The effect of the above four
1330 commands can be achieved with a single one:
1332 @ifclear vxworks
1333 @smallexample
1334 $ gnatmake gmain.adb
1335 @end smallexample
1336 @end ifclear
1338 @ifset vxworks
1339 @smallexample
1340 $ @i{target}-gnatmake gmain.adb
1341 @end smallexample
1342 @end ifset
1344 @noindent
1345 In the next section we discuss the advantages of using @code{gnatmake} in
1346 more detail.
1348 @node Using the gnatmake Utility
1349 @section Using the @command{gnatmake} Utility
1351 @noindent
1352 If you work on a program by compiling single components at a time using
1353 @code{gcc}, you typically keep track of the units you modify. In order to
1354 build a consistent system, you compile not only these units, but also any
1355 units that depend on the units you have modified.
1356 For example, in the preceding case,
1357 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1358 you edit @file{greetings.ads}, you must recompile both
1359 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1360 units that depend on @file{greetings.ads}.
1362 @code{gnatbind} will warn you if you forget one of these compilation
1363 steps, so that it is impossible to generate an inconsistent program as a
1364 result of forgetting to do a compilation. Nevertheless it is tedious and
1365 error-prone to keep track of dependencies among units.
1366 One approach to handle the dependency-bookkeeping is to use a
1367 makefile. However, makefiles present maintenance problems of their own:
1368 if the dependencies change as you change the program, you must make
1369 sure that the makefile is kept up-to-date manually, which is also an
1370 error-prone process.
1372 The @code{gnatmake} utility takes care of these details automatically.
1373 Invoke it using either one of the following forms:
1375 @ifclear vxworks
1376 @smallexample
1377 $ gnatmake gmain.adb
1378 $ gnatmake ^gmain^GMAIN^
1379 @end smallexample
1380 @end ifclear
1382 @ifset vxworks
1383 @smallexample
1384 $ @i{target}-gnatmake gmain.adb
1385 $ @i{target}-gnatmake gmain
1386 @end smallexample
1387 @end ifset
1389 @noindent
1390 The argument is the name of the file containing the main program;
1391 you may omit the extension. @code{gnatmake}
1392 examines the environment, automatically recompiles any files that need
1393 recompiling, and binds and links the resulting set of object files,
1394 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1395 In a large program, it
1396 can be extremely helpful to use @code{gnatmake}, because working out by hand
1397 what needs to be recompiled can be difficult.
1399 Note that @code{gnatmake}
1400 takes into account all the Ada 95 rules that
1401 establish dependencies among units. These include dependencies that result
1402 from inlining subprogram bodies, and from
1403 generic instantiation. Unlike some other
1404 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1405 found by the compiler on a previous compilation, which may possibly
1406 be wrong when sources change. @code{gnatmake} determines the exact set of
1407 dependencies from scratch each time it is run.
1409 @ifset vms
1410 @node Editing with Emacs
1411 @section Editing with Emacs
1412 @cindex Emacs
1414 @noindent
1415 Emacs is an extensible self-documenting text editor that is available in a
1416 separate VMSINSTAL kit.
1418 Invoke Emacs by typing "Emacs" at the command prompt. To get started,
1419 click on the Emacs Help menu and run the Emacs Tutorial.
1420 In a character cell terminal, Emacs help is invoked with "Ctrl-h" (also written
1421 as "C-h"), and the tutorial by "C-h t".
1423 Documentation on Emacs and other tools is available in Emacs under the
1424 pull-down menu button: Help - Info. After selecting Info, use the middle
1425 mouse button to select a topic (e.g. Emacs).
1427 In a character cell terminal, do "C-h i" to invoke info, and then "m"
1428 (stands for menu) followed by the menu item desired, as in "m Emacs", to get
1429 to the Emacs manual.
1430 Help on Emacs is also available by typing "HELP EMACS" at the DCL command
1431 prompt.
1433 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1434 which is sufficiently extensible to provide for a complete programming
1435 environment and shell for the sophisticated user.
1436 @end ifset
1438 @ifclear vms
1439 @node Introduction to Glide and GVD
1440 @section Introduction to Glide and GVD
1441 @cindex Glide
1442 @cindex GVD
1443 @noindent
1444 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.
1446 @menu
1447 * Building a New Program with Glide::
1448 * Simple Debugging with GVD::
1449 * Other Glide Features::
1450 @end menu
1452 @node Building a New Program with Glide
1453 @subsection Building a New Program with Glide
1454 @noindent
1455 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:
1457 @smallexample
1458 $ glide&
1459 @end smallexample
1461 @noindent
1462 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
1463 @itemize @bullet
1464 @item @code{Buffers}
1465 @item @code{Files}
1466 @item @code{Tools}
1467 @item @code{Edit}
1468 @item @code{Search}
1469 @item @code{Mule}
1470 @item @code{Glide}
1471 @item @code{Help}
1472 @end itemize
1474 @noindent
1475 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.
1477 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.
1479 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:
1480 @smallexample
1481 with Ada.Text_IO; use Ada.Text_IO;
1482 procedure Hello is
1483 begin
1484 @end smallexample
1486 @noindent
1487 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.
1489 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.
1491 Next enter the statement (with an intentional error, a missing semicolon) that will form the body of the loop:
1492 @smallexample
1493 Put_Line("Hello, World" & Integer'Image(I))
1494 @end smallexample
1496 @noindent
1497 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.
1499 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.
1501 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.
1503 To execute the program, choose @code{Ada} and then @code{Run}.  You should see the program's output displayed in the bottom window:
1505 @smallexample
1506 Hello, world 1
1507 Hello, world 2
1508 Hello, world 3
1509 Hello, world 4
1510 Hello, world 5
1511 @end smallexample
1513 @node Simple Debugging with GVD
1514 @subsection Simple Debugging with GVD
1516 @noindent
1517 This section describes how to set breakpoints, examine/modify variables, and step through execution.
1519 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:
1521 @smallexample
1522 $ gvd hello
1523 @end smallexample
1525 @noindent
1526 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}.
1528 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.
1530 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.
1532 For this example, set a breakpoint at the statement where @code{Put_Line} is invoked.
1534 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.
1536 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.
1538 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.
1540 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}.
1542 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.
1545 @node Other Glide Features
1546 @subsection Other Glide Features
1548 @noindent
1549 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...}.
1551 To abort a Glide command, type @key{Ctrl-g}.
1553 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:
1555 @smallexample
1556 $ glide hello.adb&
1557 @end smallexample
1559 @noindent
1560 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.
1562 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}.
1564 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:
1565 @itemize @bullet
1566 @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)
1567 @item With the focus in one of the windows, select the desired buffer from the @code{Buffers} menu
1568 @end itemize
1570 @noindent
1571 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1572 @end ifclear
1574 @node The GNAT Compilation Model
1575 @chapter The GNAT Compilation Model
1576 @cindex GNAT compilation model
1577 @cindex Compilation model
1579 @menu
1580 * Source Representation::
1581 * Foreign Language Representation::
1582 * File Naming Rules::
1583 * Using Other File Names::
1584 * Alternative File Naming Schemes::
1585 * Generating Object Files::
1586 * Source Dependencies::
1587 * The Ada Library Information Files::
1588 * Binding an Ada Program::
1589 * Mixed Language Programming::
1590 * Building Mixed Ada & C++ Programs::
1591 * Comparison between GNAT and C/C++ Compilation Models::
1592 * Comparison between GNAT and Conventional Ada Library Models::
1593 @end menu
1595 @noindent
1596 This chapter describes the compilation model used by GNAT. Although
1597 similar to that used by other languages, such as C and C++, this model
1598 is substantially different from the traditional Ada compilation models,
1599 which are based on a library. The model is initially described without
1600 reference to the library-based model. If you have not previously used an
1601 Ada compiler, you need only read the first part of this chapter. The
1602 last section describes and discusses the differences between the GNAT
1603 model and the traditional Ada compiler models. If you have used other
1604 Ada compilers, this section will help you to understand those
1605 differences, and the advantages of the GNAT model.
1607 @node Source Representation
1608 @section Source Representation
1609 @cindex Latin-1
1611 @noindent
1612 Ada source programs are represented in standard text files, using
1613 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1614 7-bit ASCII set, plus additional characters used for
1615 representing foreign languages (@pxref{Foreign Language Representation}
1616 for support of non-USA character sets). The format effector characters
1617 are represented using their standard ASCII encodings, as follows:
1619 @table @code
1620 @item VT
1621 @findex VT
1622 Vertical tab, @code{16#0B#}
1624 @item HT
1625 @findex HT
1626 Horizontal tab, @code{16#09#}
1628 @item CR
1629 @findex CR
1630 Carriage return, @code{16#0D#}
1632 @item LF
1633 @findex LF
1634 Line feed, @code{16#0A#}
1636 @item FF
1637 @findex FF
1638 Form feed, @code{16#0C#}
1639 @end table
1641 @noindent
1642 Source files are in standard text file format. In addition, GNAT will
1643 recognize a wide variety of stream formats, in which the end of physical
1644 physical lines is marked by any of the following sequences:
1645 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1646 in accommodating files that are imported from other operating systems.
1648 @cindex End of source file
1649 @cindex Source file, end
1650 @findex SUB
1651 The end of a source file is normally represented by the physical end of
1652 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1653 recognized as signalling the end of the source file. Again, this is
1654 provided for compatibility with other operating systems where this
1655 code is used to represent the end of file.
1657 Each file contains a single Ada compilation unit, including any pragmas
1658 associated with the unit. For example, this means you must place a
1659 package declaration (a package @dfn{spec}) and the corresponding body in
1660 separate files. An Ada @dfn{compilation} (which is a sequence of
1661 compilation units) is represented using a sequence of files. Similarly,
1662 you will place each subunit or child unit in a separate file.
1664 @node Foreign Language Representation
1665 @section Foreign Language Representation
1667 @noindent
1668 GNAT supports the standard character sets defined in Ada 95 as well as
1669 several other non-standard character sets for use in localized versions
1670 of the compiler (@pxref{Character Set Control}).
1671 @menu
1672 * Latin-1::
1673 * Other 8-Bit Codes::
1674 * Wide Character Encodings::
1675 @end menu
1677 @node Latin-1
1678 @subsection Latin-1
1679 @cindex Latin-1
1681 @noindent
1682 The basic character set is Latin-1. This character set is defined by ISO
1683 standard 8859, part 1. The lower half (character codes @code{16#00#}
1684 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half is
1685 used to represent additional characters. These include extended letters
1686 used by European languages, such as French accents, the vowels with umlauts
1687 used in German, and the extra letter A-ring used in Swedish.
1689 @findex Ada.Characters.Latin_1
1690 For a complete list of Latin-1 codes and their encodings, see the source
1691 file of library unit @code{Ada.Characters.Latin_1} in file
1692 @file{a-chlat1.ads}.
1693 You may use any of these extended characters freely in character or
1694 string literals. In addition, the extended characters that represent
1695 letters can be used in identifiers.
1697 @node Other 8-Bit Codes
1698 @subsection Other 8-Bit Codes
1700 @noindent
1701 GNAT also supports several other 8-bit coding schemes:
1703 @table @asis
1704 @cindex Latin-2
1705 @item Latin-2
1706 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1707 equivalence.
1709 @item Latin-3
1710 @cindex Latin-3
1711 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1712 equivalence.
1714 @item Latin-4
1715 @cindex Latin-4
1716 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1717 equivalence.
1719 @item Latin-5
1720 @cindex Latin-5
1721 @cindex Cyrillic
1722 Latin-4 letters (Cyrillic) allowed in identifiers, with uppercase and lowercase
1723 equivalence.
1725 @item IBM PC (code page 437)
1726 @cindex code page 437
1727 This code page is the normal default for PCs in the U.S. It corresponds
1728 to the original IBM PC character set. This set has some, but not all, of
1729 the extended Latin-1 letters, but these letters do not have the same
1730 encoding as Latin-1. In this mode, these letters are allowed in
1731 identifiers with uppercase and lowercase equivalence.
1733 @item IBM PC (code page 850)
1734 @cindex code page 850
1735 This code page is a modification of 437 extended to include all the
1736 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1737 mode, all these letters are allowed in identifiers with uppercase and
1738 lowercase equivalence.
1740 @item Full Upper 8-bit
1741 Any character in the range 80-FF allowed in identifiers, and all are
1742 considered distinct. In other words, there are no uppercase and lowercase
1743 equivalences in this range. This is useful in conjunction with
1744 certain encoding schemes used for some foreign character sets (e.g.
1745 the typical method of representing Chinese characters on the PC).
1747 @item No Upper-Half
1748 No upper-half characters in the range 80-FF are allowed in identifiers.
1749 This gives Ada 83 compatibility for identifier names.
1750 @end table
1752 @noindent
1753 For precise data on the encodings permitted, and the uppercase and lowercase
1754 equivalences that are recognized, see the file @file{csets.adb} in
1755 the GNAT compiler sources. You will need to obtain a full source release
1756 of GNAT to obtain this file.
1758 @node Wide Character Encodings
1759 @subsection Wide Character Encodings
1761 @noindent
1762 GNAT allows wide character codes to appear in character and string
1763 literals, and also optionally in identifiers, by means of the following
1764 possible encoding schemes:
1766 @table @asis
1768 @item Hex Coding
1769 In this encoding, a wide character is represented by the following five
1770 character sequence:
1772 @smallexample
1773 ESC a b c d
1774 @end smallexample
1776 @noindent
1777 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1778 characters (using uppercase letters) of the wide character code. For
1779 example, ESC A345 is used to represent the wide character with code
1780 @code{16#A345#}.
1781 This scheme is compatible with use of the full Wide_Character set.
1783 @item Upper-Half Coding
1784 @cindex Upper-Half Coding
1785 The wide character with encoding @code{16#abcd#} where the upper bit is on (in
1786 other words, "a" is in the range 8-F) is represented as two bytes,
1787 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1788 character, but is not required to be in the upper half. This method can
1789 be also used for shift-JIS or EUC, where the internal coding matches the
1790 external coding.
1792 @item Shift JIS Coding
1793 @cindex Shift JIS Coding
1794 A wide character is represented by a two-character sequence,
1795 @code{16#ab#} and
1796 @code{16#cd#}, with the restrictions described for upper-half encoding as
1797 described above. The internal character code is the corresponding JIS
1798 character according to the standard algorithm for Shift-JIS
1799 conversion. Only characters defined in the JIS code set table can be
1800 used with this encoding method.
1802 @item EUC Coding
1803 @cindex EUC Coding
1804 A wide character is represented by a two-character sequence
1805 @code{16#ab#} and
1806 @code{16#cd#}, with both characters being in the upper half. The internal
1807 character code is the corresponding JIS character according to the EUC
1808 encoding algorithm. Only characters defined in the JIS code set table
1809 can be used with this encoding method.
1811 @item UTF-8 Coding
1812 A wide character is represented using
1813 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1814 10646-1/Am.2. Depending on the character value, the representation
1815 is a one, two, or three byte sequence:
1816 @smallexample
1817 @iftex
1818 @leftskip=.7cm
1819 @end iftex
1820 16#0000#-16#007f#: 2#0xxxxxxx#
1821 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1822 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1824 @end smallexample
1826 @noindent
1827 where the xxx bits correspond to the left-padded bits of the
1828 16-bit character value. Note that all lower half ASCII characters
1829 are represented as ASCII bytes and all upper half characters and
1830 other wide characters are represented as sequences of upper-half
1831 (The full UTF-8 scheme allows for encoding 31-bit characters as
1832 6-byte sequences, but in this implementation, all UTF-8 sequences
1833 of four or more bytes length will be treated as illegal).
1834 @item Brackets Coding
1835 In this encoding, a wide character is represented by the following eight
1836 character sequence:
1838 @smallexample
1839 [ " a b c d " ]
1840 @end smallexample
1842 @noindent
1843 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1844 characters (using uppercase letters) of the wide character code. For
1845 example, ["A345"] is used to represent the wide character with code
1846 @code{16#A345#}. It is also possible (though not required) to use the
1847 Brackets coding for upper half characters. For example, the code
1848 @code{16#A3#} can be represented as @code{["A3"]}.
1850 This scheme is compatible with use of the full Wide_Character set,
1851 and is also the method used for wide character encoding in the standard
1852 ACVC (Ada Compiler Validation Capability) test suite distributions.
1854 @end table
1856 @noindent
1857 Note: Some of these coding schemes do not permit the full use of the
1858 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
1859 use of the upper half of the Latin-1 set.
1861 @node File Naming Rules
1862 @section File Naming Rules
1864 @noindent
1865 The default file name is determined by the name of the unit that the
1866 file contains. The name is formed by taking the full expanded name of
1867 the unit and replacing the separating dots with hyphens and using
1868 ^lowercase^uppercase^ for all letters.
1870 An exception arises if the file name generated by the above rules starts
1871 with one of the characters
1872 @ifset vms
1873 A,G,I, or S,
1874 @end ifset
1875 @ifclear vms
1876 a,g,i, or s,
1877 @end ifclear
1878 and the second character is a
1879 minus. In this case, the character ^tilde^dollar sign^ is used in place
1880 of the minus. The reason for this special rule is to avoid clashes with
1881 the standard names for child units of the packages System, Ada,
1882 Interfaces, and GNAT, which use the prefixes
1883 @ifset vms
1884 S- A- I- and G-
1885 @end ifset
1886 @ifclear vms
1887 s- a- i- and g-
1888 @end ifclear
1889 respectively.
1891 The file extension is @file{.ads} for a spec and
1892 @file{.adb} for a body. The following list shows some
1893 examples of these rules.
1895 @table @file
1896 @item main.ads
1897 Main (spec)
1898 @item main.adb
1899 Main (body)
1900 @item arith_functions.ads
1901 Arith_Functions (package spec)
1902 @item arith_functions.adb
1903 Arith_Functions (package body)
1904 @item func-spec.ads
1905 Func.Spec (child package spec)
1906 @item func-spec.adb
1907 Func.Spec (child package body)
1908 @item main-sub.adb
1909 Sub (subunit of Main)
1910 @item ^a~bad.adb^A$BAD.ADB^
1911 A.Bad (child package body)
1912 @end table
1914 @noindent
1915 Following these rules can result in excessively long
1916 file names if corresponding
1917 unit names are long (for example, if child units or subunits are
1918 heavily nested). An option is available to shorten such long file names
1919 (called file name "krunching"). This may be particularly useful when
1920 programs being developed with GNAT are to be used on operating systems
1921 with limited file name lengths. @xref{Using gnatkr}.
1923 Of course, no file shortening algorithm can guarantee uniqueness over
1924 all possible unit names; if file name krunching is used, it is your
1925 responsibility to ensure no name clashes occur. Alternatively you
1926 can specify the exact file names that you want used, as described
1927 in the next section. Finally, if your Ada programs are migrating from a
1928 compiler with a different naming convention, you can use the gnatchop
1929 utility to produce source files that follow the GNAT naming conventions.
1930 (For details @pxref{Renaming Files Using gnatchop}.)
1932 @node Using Other File Names
1933 @section Using Other File Names
1934 @cindex File names
1936 @noindent
1937 In the previous section, we have described the default rules used by
1938 GNAT to determine the file name in which a given unit resides. It is
1939 often convenient to follow these default rules, and if you follow them,
1940 the compiler knows without being explicitly told where to find all
1941 the files it needs.
1943 However, in some cases, particularly when a program is imported from
1944 another Ada compiler environment, it may be more convenient for the
1945 programmer to specify which file names contain which units. GNAT allows
1946 arbitrary file names to be used by means of the Source_File_Name pragma.
1947 The form of this pragma is as shown in the following examples:
1948 @cindex Source_File_Name pragma
1950 @smallexample
1951 @group
1952 @cartouche
1953 @b{pragma} Source_File_Name (My_Utilities.Stacks,
1954   Spec_File_Name => "myutilst_a.ada");
1955 @b{pragma} Source_File_name (My_Utilities.Stacks,
1956   Body_File_Name => "myutilst.ada");
1957 @end cartouche
1958 @end group
1959 @end smallexample
1961 @noindent
1962 As shown in this example, the first argument for the pragma is the unit
1963 name (in this example a child unit). The second argument has the form
1964 of a named association. The identifier
1965 indicates whether the file name is for a spec or a body;
1966 the file name itself is given by a string literal.
1968 The source file name pragma is a configuration pragma, which means that
1969 normally it will be placed in the @file{gnat.adc}
1970 file used to hold configuration
1971 pragmas that apply to a complete compilation environment.
1972 For more details on how the @file{gnat.adc} file is created and used
1973 @pxref{Handling of Configuration Pragmas}
1974 @cindex @file{gnat.adc}
1976 @ifclear vms
1977 GNAT allows completely arbitrary file names to be specified using the
1978 source file name pragma. However, if the file name specified has an
1979 extension other than @file{.ads} or @file{.adb} it is necessary to use a special
1980 syntax when compiling the file. The name in this case must be preceded
1981 by the special sequence @code{-x} followed by a space and the name of the
1982 language, here @code{ada}, as in:
1984 @smallexample
1985 $ gcc -c -x ada peculiar_file_name.sim
1986 @end smallexample
1987 @end ifclear
1989 @noindent
1990 @code{gnatmake} handles non-standard file names in the usual manner (the
1991 non-standard file name for the main program is simply used as the
1992 argument to gnatmake). Note that if the extension is also non-standard,
1993 then it must be included in the gnatmake command, it may not be omitted.
1995 @node Alternative File Naming Schemes
1996 @section Alternative File Naming Schemes
1997 @cindex File naming schemes, alternative
1998 @cindex File names
2000 In the previous section, we described the use of the @code{Source_File_Name}
2001 pragma to allow arbitrary names to be assigned to individual source files.
2002 However, this approach requires one pragma for each file, and especially in
2003 large systems can result in very long @file{gnat.adc} files, and also create
2004 a maintenance problem.
2006 GNAT also provides a facility for specifying systematic file naming schemes
2007 other than the standard default naming scheme previously described. An
2008 alternative scheme for naming is specified by the use of
2009 @code{Source_File_Name} pragmas having the following format:
2010 @cindex Source_File_Name pragma
2012 @smallexample
2013 pragma Source_File_Name (
2014    Spec_File_Name  => FILE_NAME_PATTERN
2015  [,Casing          => CASING_SPEC]
2016  [,Dot_Replacement => STRING_LITERAL]);
2018 pragma Source_File_Name (
2019    Body_File_Name  => FILE_NAME_PATTERN
2020  [,Casing          => CASING_SPEC]
2021  [,Dot_Replacement => STRING_LITERAL]);
2023 pragma Source_File_Name (
2024    Subunit_File_Name  => FILE_NAME_PATTERN
2025  [,Casing             => CASING_SPEC]
2026  [,Dot_Replacement    => STRING_LITERAL]);
2028 FILE_NAME_PATTERN ::= STRING_LITERAL
2029 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2031 @end smallexample
2033 @noindent
2034 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2035 It contains a single asterisk character, and the unit name is substituted
2036 systematically for this asterisk. The optional parameter
2037 @code{Casing} indicates
2038 whether the unit name is to be all upper-case letters, all lower-case letters,
2039 or mixed-case. If no
2040 @code{Casing} parameter is used, then the default is all
2041 ^lower-case^upper-case^.
2043 The optional @code{Dot_Replacement} string is used to replace any periods
2044 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2045 argument is used then separating dots appear unchanged in the resulting
2046 file name.
2047 Although the above syntax indicates that the
2048 @code{Casing} argument must appear
2049 before the @code{Dot_Replacement} argument, but it
2050 is also permissible to write these arguments in the opposite order.
2052 As indicated, it is possible to specify different naming schemes for
2053 bodies, specs, and subunits. Quite often the rule for subunits is the
2054 same as the rule for bodies, in which case, there is no need to give
2055 a separate @code{Subunit_File_Name} rule, and in this case the
2056 @code{Body_File_name} rule is used for subunits as well.
2058 The separate rule for subunits can also be used to implement the rather
2059 unusual case of a compilation environment (e.g. a single directory) which
2060 contains a subunit and a child unit with the same unit name. Although
2061 both units cannot appear in the same partition, the Ada Reference Manual
2062 allows (but does not require) the possibility of the two units coexisting
2063 in the same environment.
2065 The file name translation works in the following steps:
2067 @itemize @bullet
2069 @item
2070 If there is a specific @code{Source_File_Name} pragma for the given unit,
2071 then this is always used, and any general pattern rules are ignored.
2073 @item
2074 If there is a pattern type @code{Source_File_Name} pragma that applies to
2075 the unit, then the resulting file name will be used if the file exists. If
2076 more than one pattern matches, the latest one will be tried first, and the
2077 first attempt resulting in a reference to a file that exists will be used.
2079 @item
2080 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2081 for which the corresponding file exists, then the standard GNAT default
2082 naming rules are used.
2084 @end itemize
2086 @noindent
2087 As an example of the use of this mechanism, consider a commonly used scheme
2088 in which file names are all lower case, with separating periods copied
2089 unchanged to the resulting file name, and specs end with ".1.ada", and
2090 bodies end with ".2.ada". GNAT will follow this scheme if the following
2091 two pragmas appear:
2093 @smallexample
2094 pragma Source_File_Name
2095   (Spec_File_Name => "*.1.ada");
2096 pragma Source_File_Name
2097   (Body_File_Name => "*.2.ada");
2098 @end smallexample
2100 @noindent
2101 The default GNAT scheme is actually implemented by providing the following
2102 default pragmas internally:
2104 @smallexample
2105 pragma Source_File_Name
2106   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2107 pragma Source_File_Name
2108   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2109 @end smallexample
2111 @noindent
2112 Our final example implements a scheme typically used with one of the
2113 Ada 83 compilers, where the separator character for subunits was "__"
2114 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2115 by adding @file{.ADA}, and subunits by
2116 adding @file{.SEP}. All file names were
2117 upper case. Child units were not present of course since this was an
2118 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2119 the same double underscore separator for child units.
2121 @smallexample
2122 pragma Source_File_Name
2123   (Spec_File_Name => "*_.ADA",
2124    Dot_Replacement => "__",
2125    Casing = Uppercase);
2126 pragma Source_File_Name
2127   (Body_File_Name => "*.ADA",
2128    Dot_Replacement => "__",
2129    Casing = Uppercase);
2130 pragma Source_File_Name
2131   (Subunit_File_Name => "*.SEP",
2132    Dot_Replacement => "__",
2133    Casing = Uppercase);
2134 @end smallexample
2136 @node Generating Object Files
2137 @section Generating Object Files
2139 @noindent
2140 An Ada program consists of a set of source files, and the first step in
2141 compiling the program is to generate the corresponding object files.
2142 These are generated by compiling a subset of these source files.
2143 The files you need to compile are the following:
2145 @itemize @bullet
2146 @item
2147 If a package spec has no body, compile the package spec to produce the
2148 object file for the package.
2150 @item
2151 If a package has both a spec and a body, compile the body to produce the
2152 object file for the package. The source file for the package spec need
2153 not be compiled in this case because there is only one object file, which
2154 contains the code for both the spec and body of the package.
2156 @item
2157 For a subprogram, compile the subprogram body to produce the object file
2158 for the subprogram. The spec, if one is present, is as usual in a
2159 separate file, and need not be compiled.
2161 @item
2162 @cindex Subunits
2163 In the case of subunits, only compile the parent unit. A single object
2164 file is generated for the entire subunit tree, which includes all the
2165 subunits.
2167 @item
2168 Compile child units independently of their parent units
2169 (though, of course, the spec of all the ancestor unit must be present in order
2170 to compile a child unit).
2172 @item
2173 @cindex Generics
2174 Compile generic units in the same manner as any other units. The object
2175 files in this case are small dummy files that contain at most the
2176 flag used for elaboration checking. This is because GNAT always handles generic
2177 instantiation by means of macro expansion. However, it is still necessary to
2178 compile generic units, for dependency checking and elaboration purposes.
2179 @end itemize
2181 @noindent
2182 The preceding rules describe the set of files that must be compiled to
2183 generate the object files for a program. Each object file has the same
2184 name as the corresponding source file, except that the extension is
2185 @file{.o} as usual.
2187 You may wish to compile other files for the purpose of checking their
2188 syntactic and semantic correctness. For example, in the case where a
2189 package has a separate spec and body, you would not normally compile the
2190 spec. However, it is convenient in practice to compile the spec to make
2191 sure it is error-free before compiling clients of this spec, because such
2192 compilations will fail if there is an error in the spec.
2194 GNAT provides an option for compiling such files purely for the
2195 purposes of checking correctness; such compilations are not required as
2196 part of the process of building a program. To compile a file in this
2197 checking mode, use the @option{-gnatc} switch.
2199 @node Source Dependencies
2200 @section Source Dependencies
2202 @noindent
2203 A given object file clearly depends on the source file which is compiled
2204 to produce it. Here we are using @dfn{depends} in the sense of a typical
2205 @code{make} utility; in other words, an object file depends on a source
2206 file if changes to the source file require the object file to be
2207 recompiled.
2208 In addition to this basic dependency, a given object may depend on
2209 additional source files as follows:
2211 @itemize @bullet
2212 @item
2213 If a file being compiled @code{with}'s a unit @var{X}, the object file
2214 depends on the file containing the spec of unit @var{X}. This includes
2215 files that are @code{with}'ed implicitly either because they are parents
2216 of @code{with}'ed child units or they are run-time units required by the
2217 language constructs used in a particular unit.
2219 @item
2220 If a file being compiled instantiates a library level generic unit, the
2221 object file depends on both the spec and body files for this generic
2222 unit.
2224 @item
2225 If a file being compiled instantiates a generic unit defined within a
2226 package, the object file depends on the body file for the package as
2227 well as the spec file.
2229 @item
2230 @findex Inline
2231 @cindex @option{-gnatn} switch
2232 If a file being compiled contains a call to a subprogram for which
2233 pragma @code{Inline} applies and inlining is activated with the
2234 @option{-gnatn} switch, the object file depends on the file containing the
2235 body of this subprogram as well as on the file containing the spec. Note
2236 that for inlining to actually occur as a result of the use of this switch,
2237 it is necessary to compile in optimizing mode.
2239 @cindex @option{-gnatN} switch
2240 The use of @option{-gnatN} activates a more extensive inlining optimization
2241 that is performed by the front end of the compiler. This inlining does
2242 not require that the code generation be optimized. Like @option{-gnatn},
2243 the use of this switch generates additional dependencies.
2245 @item
2246 If an object file O  depends on the proper body of a subunit through inlining
2247 or instantiation, it depends on the parent unit of the subunit. This means that
2248 any modification of the parent unit or one of its subunits affects the
2249 compilation of O.
2251 @item
2252 The object file for a parent unit depends on all its subunit body files.
2254 @item
2255 The previous two rules meant that for purposes of computing dependencies and
2256 recompilation, a body and all its subunits are treated as an indivisible whole.
2258 @noindent
2259 These rules are applied transitively: if unit @code{A} @code{with}'s
2260 unit @code{B}, whose elaboration calls an inlined procedure in package
2261 @code{C}, the object file for unit @code{A} will depend on the body of
2262 @code{C}, in file @file{c.adb}.
2264 The set of dependent files described by these rules includes all the
2265 files on which the unit is semantically dependent, as described in the
2266 Ada 95 Language Reference Manual. However, it is a superset of what the
2267 ARM describes, because it includes generic, inline, and subunit dependencies.
2269 An object file must be recreated by recompiling the corresponding source
2270 file if any of the source files on which it depends are modified. For
2271 example, if the @code{make} utility is used to control compilation,
2272 the rule for an Ada object file must mention all the source files on
2273 which the object file depends, according to the above definition.
2274 The determination of the necessary
2275 recompilations is done automatically when one uses @code{gnatmake}.
2276 @end itemize
2278 @node The Ada Library Information Files
2279 @section The Ada Library Information Files
2280 @cindex Ada Library Information files
2281 @cindex @file{ali} files
2283 @noindent
2284 Each compilation actually generates two output files. The first of these
2285 is the normal object file that has a @file{.o} extension. The second is a
2286 text file containing full dependency information. It has the same
2287 name as the source file, but an @file{.ali} extension.
2288 This file is known as the Ada Library Information (@file{ali}) file.
2289 The following information is contained in the @file{ali} file.
2291 @itemize @bullet
2292 @item
2293 Version information (indicates which version of GNAT was used to compile
2294 the unit(s) in question)
2296 @item
2297 Main program information (including priority and time slice settings,
2298 as well as the wide character encoding used during compilation).
2300 @item
2301 List of arguments used in the @code{gcc} command for the compilation
2303 @item
2304 Attributes of the unit, including configuration pragmas used, an indication
2305 of whether the compilation was successful, exception model used etc.
2307 @item
2308 A list of relevant restrictions applying to the unit (used for consistency)
2309 checking.
2311 @item
2312 Categorization information (e.g. use of pragma @code{Pure}).
2314 @item
2315 Information on all @code{with}'ed units, including presence of
2316 @code{Elaborate} or @code{Elaborate_All} pragmas.
2318 @item
2319 Information from any @code{Linker_Options} pragmas used in the unit
2321 @item
2322 Information on the use of @code{Body_Version} or @code{Version}
2323 attributes in the unit.
2325 @item
2326 Dependency information. This is a list of files, together with
2327 time stamp and checksum information. These are files on which
2328 the unit depends in the sense that recompilation is required
2329 if any of these units are modified.
2331 @item
2332 Cross-reference data. Contains information on all entities referenced
2333 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2334 provide cross-reference information.
2336 @end itemize
2338 @noindent
2339 For a full detailed description of the format of the @file{ali} file,
2340 see the source of the body of unit @code{Lib.Writ}, contained in file
2341 @file{lib-writ.adb} in the GNAT compiler sources.
2343 @node Binding an Ada Program
2344 @section Binding an Ada Program
2346 @noindent
2347 When using languages such as C and C++, once the source files have been
2348 compiled the only remaining step in building an executable program
2349 is linking the object modules together. This means that it is possible to
2350 link an inconsistent version of a program, in which two units have
2351 included different versions of the same header.
2353 The rules of Ada do not permit such an inconsistent program to be built.
2354 For example, if two clients have different versions of the same package,
2355 it is illegal to build a program containing these two clients.
2356 These rules are enforced by the GNAT binder, which also determines an
2357 elaboration order consistent with the Ada rules.
2359 The GNAT binder is run after all the object files for a program have
2360 been created. It is given the name of the main program unit, and from
2361 this it determines the set of units required by the program, by reading the
2362 corresponding ALI files. It generates error messages if the program is
2363 inconsistent or if no valid order of elaboration exists.
2365 If no errors are detected, the binder produces a main program, in Ada by
2366 default, that contains calls to the elaboration procedures of those
2367 compilation unit that require them, followed by
2368 a call to the main program. This Ada program is compiled to generate the
2369 object file for the main program. The name of
2370 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2371 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2372 main program unit.
2374 Finally, the linker is used to build the resulting executable program,
2375 using the object from the main program from the bind step as well as the
2376 object files for the Ada units of the program.
2378 @node Mixed Language Programming
2379 @section Mixed Language Programming
2380 @cindex Mixed Language Programming
2382 @menu
2383 * Interfacing to C::
2384 * Calling Conventions::
2385 @end menu
2387 @node Interfacing to C
2388 @subsection Interfacing to C
2389 @noindent
2390 There are two ways to
2391 build a program that contains some Ada files and some other language
2392 files depending on whether the main program is in Ada or not.
2393 If the main program is in Ada, you should proceed as follows:
2395 @enumerate
2396 @item
2397 Compile the other language files to generate object files. For instance:
2398 @smallexample
2399 gcc -c file1.c
2400 gcc -c file2.c
2401 @end smallexample
2403 @item
2404 Compile the Ada units to produce a set of object files and ALI
2405 files. For instance:
2406 @smallexample
2407 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2408 @end smallexample
2410 @item
2411 Run the Ada binder on the Ada main program. For instance:
2412 @smallexample
2413 gnatbind my_main.ali
2414 @end smallexample
2416 @item
2417 Link the Ada main program, the Ada objects and the other language
2418 objects. For instance:
2419 @smallexample
2420 gnatlink my_main.ali file1.o file2.o
2421 @end smallexample
2422 @end enumerate
2424 The three last steps can be grouped in a single command:
2425 @smallexample
2426 gnatmake my_main.adb -largs file1.o file2.o
2427 @end smallexample
2429 @cindex Binder output file
2430 @noindent
2431 If the main program is in some language other than Ada, Then you may
2432 have more than one entry point in the Ada subsystem. You must use a
2433 special option of the binder to generate callable routines to initialize
2434 and finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2435 Calls to the initialization and finalization routines must be inserted in
2436 the main program, or some other appropriate point in the code. The call to
2437 initialize the Ada units must occur before the first Ada subprogram is
2438 called, and the call to finalize the Ada units must occur after the last
2439 Ada subprogram returns. You use the same procedure for building the
2440 program as described previously. In this case, however, the binder
2441 only places the initialization and finalization subprograms into file
2442 @file{b~@var{xxx}.adb} instead of the main program.
2443 So, if the main program is not in Ada, you should proceed as follows:
2445 @enumerate
2446 @item
2447 Compile the other language files to generate object files. For instance:
2448 @smallexample
2449 gcc -c file1.c
2450 gcc -c file2.c
2451 @end smallexample
2453 @item
2454 Compile the Ada units to produce a set of object files and ALI
2455 files. For instance:
2456 @smallexample
2457 gnatmake ^-c^/ACTIONS=COMPILE^ entry_point1.adb
2458 gnatmake ^-c^/ACTIONS=COMPILE^ entry_point2.adb
2459 @end smallexample
2461 @item
2462 Run the Ada binder on the Ada main program. For instance:
2463 @smallexample
2464 gnatbind ^-n^/NOMAIN^ entry_point1.ali entry_point2.ali
2465 @end smallexample
2467 @item
2468 Link the Ada main program, the Ada objects and the other language
2469 objects. You only need to give the last entry point here. For instance:
2470 @smallexample
2471 gnatlink entry_point2.ali file1.o file2.o
2472 @end smallexample
2473 @end enumerate
2475 @node Calling Conventions
2476 @subsection Calling Conventions
2477 @cindex Foreign Languages
2478 @cindex Calling Conventions
2479 GNAT follows standard calling sequence conventions and will thus interface
2480 to any other language that also follows these conventions. The following
2481 Convention identifiers are recognized by GNAT:
2483 @itemize @bullet
2484 @cindex Interfacing to Ada
2485 @cindex Other Ada compilers
2486 @cindex Convention Ada
2487 @item
2488 Ada. This indicates that the standard Ada calling sequence will be
2489 used and all Ada data items may be passed without any limitations in the
2490 case where GNAT is used to generate both the caller and callee. It is also
2491 possible to mix GNAT generated code and code generated by another Ada
2492 compiler. In this case, the data types should be restricted to simple
2493 cases, including primitive types. Whether complex data types can be passed
2494 depends on the situation. Probably it is safe to pass simple arrays, such
2495 as arrays of integers or floats. Records may or may not work, depending
2496 on whether both compilers lay them out identically. Complex structures
2497 involving variant records, access parameters, tasks, or protected types,
2498 are unlikely to be able to be passed.
2500 Note that in the case of GNAT running
2501 on a platform that supports DEC Ada 83, a higher degree of compatibility
2502 can be guaranteed, and in particular records are layed out in an identical
2503 manner in the two compilers. Note also that if output from two different
2504 compilers is mixed, the program is responsible for dealing with elaboration
2505 issues. Probably the safest approach is to write the main program in the
2506 version of Ada other than GNAT, so that it takes care of its own elaboration
2507 requirements, and then call the GNAT-generated adainit procedure to ensure
2508 elaboration of the GNAT components. Consult the documentation of the other
2509 Ada compiler for further details on elaboration.
2511 However, it is not possible to mix the tasking run time of GNAT and
2512 DEC Ada 83, All the tasking operations must either be entirely within
2513 GNAT compiled sections of the program, or entirely within DEC Ada 83
2514 compiled sections of the program.
2516 @cindex Interfacing to Assembly
2517 @cindex Convention Assembler
2518 @item
2519 Assembler. Specifies assembler as the convention. In practice this has the
2520 same effect as convention Ada (but is not equivalent in the sense of being
2521 considered the same convention).
2523 @cindex Convention Asm
2524 @findex Asm
2525 @item
2526 Asm. Equivalent to Assembler.
2528 @cindex Convention Asm
2529 @findex Asm
2530 @item
2531 Asm. Equivalent to Assembly.
2533 @cindex Interfacing to COBOL
2534 @cindex Convention COBOL
2535 @findex COBOL
2536 @item
2537 COBOL. Data will be passed according to the conventions described
2538 in section B.4 of the Ada 95 Reference Manual.
2540 @findex C
2541 @cindex Interfacing to C
2542 @cindex Convention C
2543 @item
2544 C. Data will be passed according to the conventions described
2545 in section B.3 of the Ada 95 Reference Manual.
2547 @cindex Convention Default
2548 @findex Default
2549 @item
2550 Default. Equivalent to C.
2552 @cindex Convention External
2553 @findex External
2554 @item
2555 External. Equivalent to C.
2557 @findex C++
2558 @cindex Interfacing to C++
2559 @cindex Convention C++
2560 @item
2561 CPP. This stands for C++. For most purposes this is identical to C.
2562 See the separate description of the specialized GNAT pragmas relating to
2563 C++ interfacing for further details.
2565 @findex Fortran
2566 @cindex Interfacing to Fortran
2567 @cindex Convention Fortran
2568 @item
2569 Fortran. Data will be passed according to the conventions described
2570 in section B.5 of the Ada 95 Reference Manual.
2572 @item
2573 Intrinsic. This applies to an intrinsic operation, as defined in the Ada 95
2574 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
2575 this means that the body of the subprogram is provided by the compiler itself,
2576 usually by means of an efficient code sequence, and that the user does not
2577 supply an explicit body for it. In an application program, the pragma can only
2578 be applied to the following two sets of names, which the GNAT compiler
2579 recognizes.
2580 @itemize @bullet
2581 @item
2582 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
2583 Arithmetic.  The corresponding subprogram declaration must have
2584 two formal parameters. The
2585 first one must be a signed integer type or a modular type with a binary
2586 modulus, and the second parameter must be of type Natural.
2587 The return type must be the same as the type of the first argument. The size
2588 of this type can only be 8, 16, 32, or 64.
2589 @item binary arithmetic operators: "+", "-", "*", "/"
2590 The corresponding operator declaration must have parameters and result type
2591 that have the same root numeric type (for example, all three are long_float
2592 types). This simplifies the definition of operations that use type checking
2593 to perform dimensional checks:
2594 @smallexample
2595 type Distance is new Long_Float;
2596 type Time     is new Long_Float;
2597 type Velocity is new Long_Float;
2598 function "/" (D : Distance; T : Time)
2599   return Velocity;
2600 pragma Import (Intrinsic, "/");
2601 @end smallexample
2602 @noindent
2603 This common idiom is often programmed with a generic definition and an explicit
2604 body. The pragma makes it simpler to introduce such declarations. It incurs
2605 no overhead in compilation time or code size, because it is implemented as a
2606 single machine instruction.
2607 @end itemize
2608 @noindent
2610 @findex Stdcall
2611 @cindex Convention Stdcall
2612 @item
2613 Stdcall. This is relevant only to NT/Win95 implementations of GNAT,
2614 and specifies that the Stdcall calling sequence will be used, as defined
2615 by the NT API.
2617 @findex DLL
2618 @cindex Convention DLL
2619 @item
2620 DLL. This is equivalent to Stdcall.
2622 @findex Win32
2623 @cindex Convention Win32
2624 @item
2625 Win32. This is equivalent to Stdcall.
2627 @findex Stubbed
2628 @cindex Convention Stubbed
2629 @item
2630 Stubbed. This is a special convention that indicates that the compiler
2631 should provide a stub body that raises @code{Program_Error}.
2632 @end itemize
2634 @noindent
2635 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2636 that can be used to parametrize conventions and allow additional synonyms
2637 to be specified. For example if you have legacy code in which the convention
2638 identifier Fortran77 was used for Fortran, you can use the configuration
2639 pragma:
2641 @smallexample
2642    pragma Convention_Identifier (Fortran77, Fortran);
2643 @end smallexample
2645 @noindent
2646 And from now on the identifier Fortran77 may be used as a convention
2647 identifier (for example in an @code{Import} pragma) with the same
2648 meaning as Fortran.
2650 @node Building Mixed Ada & C++ Programs
2651 @section Building Mixed Ada & C++ Programs
2653 @noindent
2654 Building a mixed application containing both Ada and C++ code may be a
2655 challenge for the unaware programmer. As a matter of fact, this
2656 interfacing has not been standardized in the Ada 95 reference manual due
2657 to the immaturity and lack of standard of C++ at the time. This
2658 section gives a few hints that should make this task easier. In
2659 particular the first section addresses the differences with
2660 interfacing with C. The second section looks into the delicate problem
2661 of linking the complete application from its Ada and C++ parts. The last
2662 section give some hints on how the GNAT run time can be adapted in order
2663 to allow inter-language dispatching with a new C++ compiler.
2665 @menu
2666 * Interfacing to C++::
2667 * Linking a Mixed C++ & Ada Program::
2668 * A Simple Example::
2669 * Adapting the Run Time to a New C++ Compiler::
2670 @end menu
2672 @node Interfacing to C++
2673 @subsection Interfacing to C++
2675 @noindent
2676 GNAT supports interfacing with C++ compilers generating code that is
2677 compatible with the standard Application Binary Interface of the given
2678 platform.
2680 @noindent
2681 Interfacing can be done at 3 levels: simple data, subprograms and
2682 classes. In the first 2 cases, GNAT offer a specific @var{Convention
2683 CPP} that behaves exactly like @var{Convention C}. Usually C++ mangle
2684 names of subprograms and currently GNAT does not provide any help to
2685 solve the demangling problem. This problem can be addressed in 2 ways:
2686 @itemize @bullet
2687 @item
2688 by modifying the C++ code in order to force a C convention using
2689 the @var{extern "C"} syntax.
2691 @item
2692 by figuring out the mangled name and use it as the Link_Name argument of
2693 the pragma import.
2694 @end itemize
2696 @noindent
2697 Interfacing at the class level can be achieved by using the GNAT specific
2698 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
2699 Reference Manual for additional information.
2701 @node Linking a Mixed C++ & Ada Program
2702 @subsection Linking a Mixed C++ & Ada Program
2704 @noindent
2705 Usually the linker of the C++ development system must be used to link
2706 mixed applications because most C++ systems will resolve elaboration
2707 issues (such as calling constructors on global class instances)
2708 transparently during the link phase. GNAT has been adapted to ease the
2709 use of a foreign linker for the last phase. Three cases can be
2710 considered:
2711 @enumerate
2713 @item
2714 Using GNAT and G++ (GNU C++ compiler) from the same GCC
2715 installation. The c++ linker can simply be called by using the c++
2716 specific driver called @code{c++}. Note that this setup is not
2717 very common because it may request recompiling the whole GCC
2718 tree from sources and it does not allow to upgrade easily to a new
2719 version of one compiler for one of the two languages without taking the
2720 risk of destabilizing the other.
2722 @smallexample
2723 $ c++ -c file1.C
2724 $ c++ -c file2.C
2725 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
2726 @end smallexample
2728 @item
2729 Using GNAT and G++ from 2 different GCC installations. If both compilers
2730 are on the PATH, the same method can be used. It is important to be
2731 aware that environment variables such as C_INCLUDE_PATH,
2732 GCC_EXEC_PREFIX, BINUTILS_ROOT or GCC_ROOT will affect both compilers at
2733 the same time and thus may make one of the 2 compilers operate
2734 improperly if they are set for the other. In particular it is important
2735 that the link command has access to the proper gcc library @file{libgcc.a},
2736 that is to say the one that is part of the C++ compiler
2737 installation. The implicit link command as suggested in the gnatmake
2738 command from the former example can be replaced by an explicit link
2739 command with full verbosity in order to verify which library is used:
2740 @smallexample
2741 $ gnatbind ada_unit
2742 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2743 @end smallexample
2744 If there is a problem due to interfering environment variables, it can
2745 be workaround by using an intermediate script. The following example
2746 shows the proper script to use when GNAT has not been installed at its
2747 default location and g++ has been installed at its default location:
2749 @smallexample
2750 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2751 $ cat ./my_script
2752 #!/bin/sh
2753 unset BINUTILS_ROOT
2754 unset GCC_ROOT
2755 c++ $*
2756 @end smallexample
2758 @item
2759 Using a non GNU C++ compiler. The same set of command as previously
2760 described can be used to insure that the c++ linker is
2761 used. Nonetheless, you need to add the path to libgcc explicitely, since some
2762 libraries needed by GNAT are located in this directory:
2764 @smallexample
2766 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2767 $ cat ./my_script
2768 #!/bin/sh
2769 CC $* `gcc -print-libgcc-file-name`
2771 @end smallexample
2773 Where CC is the name of the non GNU C++ compiler.
2775 @end enumerate
2777 @node A Simple Example
2778 @subsection  A Simple Example
2779 @noindent
2780 The following example, provided as part of the GNAT examples, show how
2781 to achieve procedural interfacing between Ada and C++ in both
2782 directions. The C++ class A has 2 methods. The first method is exported
2783 to Ada by the means of an extern C wrapper function. The second method
2784 calls an Ada subprogram. On the Ada side, The C++ calls is modelized by
2785 a limited record with a layout comparable to the C++ class. The Ada
2786 subprogram, in turn, calls the c++ method. So from the C++ main program
2787 the code goes back and forth between the 2 languages.
2789 @noindent
2790 Here are the compilation commands
2791 @ifclear vxworks
2792 for native configurations:
2793 @smallexample
2794 $ gnatmake -c simple_cpp_interface
2795 $ c++ -c cpp_main.C
2796 $ c++ -c ex7.C
2797 $ gnatbind -n simple_cpp_interface
2798 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
2799       -lstdc++ ex7.o cpp_main.o
2800 @end smallexample
2801 @end ifclear
2802 @ifset vxworks
2803 for a GNAT VxWorks/PowerPC  configuration:
2804 @smallexample
2805 $ powerpc-wrs-vxworks-gnatmake -c simple_cpp_interface
2806 $ powerpc-wrs-vxworks-gnatbind -n simple_cpp_interface
2807 $ gnatlink simple_cpp_interface -o ada_part
2808 $ c++ppc -c -DCPU=PPC604  -I/usr/windppc/target/h  cpp_main.C
2809 $ c++ppc -c -DCPU=PPC604  -I/usr/windppc/target/h  ex7.C
2810 $ ldppc -r -o my_main my_main.o ex7.o ada_part
2811 @end smallexample
2812 @end ifset
2813 @noindent
2814 Here are the corresponding sources:
2815 @smallexample
2817 //cpp_main.C
2819 #include "ex7.h"
2821 extern "C" @{
2822   void adainit (void);
2823   void adafinal (void);
2824   void method1 (A *t);
2827 void method1 (A *t)
2829   t->method1 ();
2832 int main ()
2834   A obj;
2835   adainit ();
2836   obj.method2 (3030);
2837   adafinal ();
2840 //ex7.h
2842 class Origin @{
2843  public:
2844   int o_value;
2846 class A : public Origin @{
2847  public:
2848   void method1 (void);
2849   virtual void method2 (int v);
2850   A();
2851   int   a_value;
2854 //ex7.C
2856 #include "ex7.h"
2857 #include <stdio.h>
2859 extern "C" @{ void ada_method2 (A *t, int v);@}
2861 void A::method1 (void)
2863   a_value = 2020;
2864   printf ("in A::method1, a_value = %d \n",a_value);
2868 void A::method2 (int v)
2870    ada_method2 (this, v);
2871    printf ("in A::method2, a_value = %d \n",a_value);
2875 A::A(void)
2877    a_value = 1010;
2878   printf ("in A::A, a_value = %d \n",a_value);
2881 -- Ada sources
2882 @b{package} @b{body} Simple_Cpp_Interface @b{is}
2884    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
2885    @b{begin}
2886       Method1 (This);
2887       This.A_Value := V;
2888    @b{end} Ada_Method2;
2890 @b{end} Simple_Cpp_Interface;
2892 @b{package} Simple_Cpp_Interface @b{is}
2893    @b{type} A @b{is} @b{limited}
2894       @b{record}
2895          O_Value : Integer;
2896          A_Value : Integer;
2897       @b{end} @b{record};
2898    @b{pragma} Convention (C, A);
2900    @b{procedure} Method1 (This : @b{in} @b{out} A);
2901    @b{pragma} Import (C, Method1);
2903    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
2904    @b{pragma} Export (C, Ada_Method2);
2906 @b{end} Simple_Cpp_Interface;
2907 @end smallexample
2909 @node Adapting the Run Time to a New C++ Compiler
2910 @subsection Adapting the Run Time to a New C++ Compiler
2911 @noindent
2912 GNAT offers the capability to derive Ada 95 tagged types directly from
2913 preexisting C++ classes and . See "Interfacing with C++" in the GNAT
2914 reference manual. The mechanism used by GNAT for achieving such a goal
2915 has been made user configurable through a GNAT library unit
2916 @code{Interfaces.CPP}. The default version of this file is adapted to
2917 the GNU c++ compiler. Internal knowledge of the virtual
2918 table layout used by the new C++ compiler is needed to configure
2919 properly this unit. The Interface of this unit is known by the compiler
2920 and cannot be changed except for the value of the constants defining the
2921 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
2922 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
2923 of this unit for more details.
2925 @node Comparison between GNAT and C/C++ Compilation Models
2926 @section Comparison between GNAT and C/C++ Compilation Models
2928 @noindent
2929 The GNAT model of compilation is close to the C and C++ models. You can
2930 think of Ada specs as corresponding to header files in C. As in C, you
2931 don't need to compile specs; they are compiled when they are used. The
2932 Ada @code{with} is similar in effect to the @code{#include} of a C
2933 header.
2935 One notable difference is that, in Ada, you may compile specs separately
2936 to check them for semantic and syntactic accuracy. This is not always
2937 possible with C headers because they are fragments of programs that have
2938 less specific syntactic or semantic rules.
2940 The other major difference is the requirement for running the binder,
2941 which performs two important functions. First, it checks for
2942 consistency. In C or C++, the only defense against assembling
2943 inconsistent programs lies outside the compiler, in a makefile, for
2944 example. The binder satisfies the Ada requirement that it be impossible
2945 to construct an inconsistent program when the compiler is used in normal
2946 mode.
2948 @cindex Elaboration order control
2949 The other important function of the binder is to deal with elaboration
2950 issues. There are also elaboration issues in C++ that are handled
2951 automatically. This automatic handling has the advantage of being
2952 simpler to use, but the C++ programmer has no control over elaboration.
2953 Where @code{gnatbind} might complain there was no valid order of
2954 elaboration, a C++ compiler would simply construct a program that
2955 malfunctioned at run time.
2957 @node Comparison between GNAT and Conventional Ada Library Models
2958 @section Comparison between GNAT and Conventional Ada Library Models
2960 @noindent
2961 This section is intended to be useful to Ada programmers who have
2962 previously used an Ada compiler implementing the traditional Ada library
2963 model, as described in the Ada 95 Language Reference Manual. If you
2964 have not used such a system, please go on to the next section.
2966 @cindex GNAT library
2967 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
2968 source files themselves acts as the library. Compiling Ada programs does
2969 not generate any centralized information, but rather an object file and
2970 a ALI file, which are of interest only to the binder and linker.
2971 In a traditional system, the compiler reads information not only from
2972 the source file being compiled, but also from the centralized library.
2973 This means that the effect of a compilation depends on what has been
2974 previously compiled. In particular:
2976 @itemize @bullet
2977 @item
2978 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2979 to the version of the unit most recently compiled into the library.
2981 @item
2982 Inlining is effective only if the necessary body has already been
2983 compiled into the library.
2985 @item
2986 Compiling a unit may obsolete other units in the library.
2987 @end itemize
2989 @noindent
2990 In GNAT, compiling one unit never affects the compilation of any other
2991 units because the compiler reads only source files. Only changes to source
2992 files can affect the results of a compilation. In particular:
2994 @itemize @bullet
2995 @item
2996 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2997 to the source version of the unit that is currently accessible to the
2998 compiler.
3000 @item
3001 @cindex Inlining
3002 Inlining requires the appropriate source files for the package or
3003 subprogram bodies to be available to the compiler. Inlining is always
3004 effective, independent of the order in which units are complied.
3006 @item
3007 Compiling a unit never affects any other compilations. The editing of
3008 sources may cause previous compilations to be out of date if they
3009 depended on the source file being modified.
3010 @end itemize
3012 @noindent
3013 The most important result of these differences is that order of compilation
3014 is never significant in GNAT. There is no situation in which one is
3015 required to do one compilation before another. What shows up as order of
3016 compilation requirements in the traditional Ada library becomes, in
3017 GNAT, simple source dependencies; in other words, there is only a set
3018 of rules saying what source files must be present when a file is
3019 compiled.
3021 @node Compiling Using gcc
3022 @chapter Compiling Using @code{gcc}
3024 @noindent
3025 This chapter discusses how to compile Ada programs using the @code{gcc}
3026 command. It also describes the set of switches
3027 that can be used to control the behavior of the compiler.
3028 @menu
3029 * Compiling Programs::
3030 * Switches for gcc::
3031 * Search Paths and the Run-Time Library (RTL)::
3032 * Order of Compilation Issues::
3033 * Examples::
3034 @end menu
3036 @node Compiling Programs
3037 @section Compiling Programs
3039 @noindent
3040 The first step in creating an executable program is to compile the units
3041 of the program using the @code{gcc} command. You must compile the
3042 following files:
3044 @itemize @bullet
3045 @item
3046 the body file (@file{.adb}) for a library level subprogram or generic
3047 subprogram
3049 @item
3050 the spec file (@file{.ads}) for a library level package or generic
3051 package that has no body
3053 @item
3054 the body file (@file{.adb}) for a library level package
3055 or generic package that has a body
3057 @end itemize
3059 @noindent
3060 You need @emph{not} compile the following files
3062 @itemize @bullet
3064 @item
3065 the spec of a library unit which has a body
3067 @item
3068 subunits
3069 @end itemize
3071 @noindent
3072 because they are compiled as part of compiling related units. GNAT
3073 package specs
3074 when the corresponding body is compiled, and subunits when the parent is
3075 compiled.
3076 @cindex No code generated
3077 If you attempt to compile any of these files, you will get one of the
3078 following error messages (where fff is the name of the file you compiled):
3080 @smallexample
3081 No code generated for file @var{fff} (@var{package spec})
3082 No code generated for file @var{fff} (@var{subunit})
3083 @end smallexample
3085 @noindent
3086 The basic command for compiling a file containing an Ada unit is
3088 @smallexample
3089 $ gcc -c [@var{switches}] @file{file name}
3090 @end smallexample
3092 @noindent
3093 where @var{file name} is the name of the Ada file (usually
3094 having an extension
3095 @file{.ads} for a spec or @file{.adb} for a body).
3096 @ifclear vms
3097 You specify the
3098 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
3099 @end ifclear
3100 The result of a successful compilation is an object file, which has the
3101 same name as the source file but an extension of @file{.o} and an Ada
3102 Library Information (ALI) file, which also has the same name as the
3103 source file, but with @file{.ali} as the extension. GNAT creates these
3104 two output files in the current directory, but you may specify a source
3105 file in any directory using an absolute or relative path specification
3106 containing the directory information.
3108 @findex gnat1
3109 @code{gcc} is actually a driver program that looks at the extensions of
3110 the file arguments and loads the appropriate compiler. For example, the
3111 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3112 These programs are in directories known to the driver program (in some
3113 configurations via environment variables you set), but need not be in
3114 your path. The @code{gcc} driver also calls the assembler and any other
3115 utilities needed to complete the generation of the required object
3116 files.
3118 It is possible to supply several file names on the same @code{gcc}
3119 command. This causes @code{gcc} to call the appropriate compiler for
3120 each file. For example, the following command lists three separate
3121 files to be compiled:
3123 @smallexample
3124 $ gcc -c x.adb y.adb z.c
3125 @end smallexample
3127 @noindent
3128 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3129 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3130 The compiler generates three object files @file{x.o}, @file{y.o} and
3131 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3132 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3133 @ifclear vms
3134 except for
3135 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3136 @end ifclear
3138 @node Switches for gcc
3139 @section Switches for @code{gcc}
3141 @noindent
3142 The @code{gcc} command accepts switches that control the
3143 compilation process. These switches are fully described in this section.
3144 First we briefly list all the switches, in alphabetical order, then we
3145 describe the switches in more detail in functionally grouped sections.
3147 @menu
3148 * Output and Error Message Control::
3149 * Debugging and Assertion Control::
3150 * Run-Time Checks::
3151 * Stack Overflow Checking::
3152 * Run-Time Control::
3153 * Validity Checking::
3154 * Style Checking::
3155 * Using gcc for Syntax Checking::
3156 * Using gcc for Semantic Checking::
3157 * Compiling Ada 83 Programs::
3158 * Character Set Control::
3159 * File Naming Control::
3160 * Subprogram Inlining Control::
3161 * Auxiliary Output Control::
3162 * Debugging Control::
3163 * Units to Sources Mapping Files::
3164 @end menu
3166 @table @code
3167 @ifclear vms
3168 @cindex @code{-b} (@code{gcc})
3169 @item -b @var{target}
3170 Compile your program to run on @var{target}, which is the name of a
3171 system configuration. You must have a GNAT cross-compiler built if
3172 @var{target} is not the same as your host system.
3174 @item -B@var{dir}
3175 @cindex @code{-B} (@code{gcc})
3176 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3177 from @var{dir} instead of the default location. Only use this switch
3178 when multiple versions of the GNAT compiler are available. See the
3179 @code{gcc} manual page for further details. You would normally use the
3180 @code{-b} or @code{-V} switch instead.
3182 @item -c
3183 @cindex @code{-c} (@code{gcc})
3184 Compile. Always use this switch when compiling Ada programs.
3186 Note: for some other languages when using @code{gcc}, notably in
3187 the case of C and C++, it is possible to use
3188 use @code{gcc} without a @code{-c} switch to
3189 compile and link in one step. In the case of GNAT, you
3190 cannot use this approach, because the binder must be run
3191 and @code{gcc} cannot be used to run the GNAT binder.
3192 @end ifclear
3194 @item ^-g^/DEBUG^
3195 @cindex @code{^-g^/DEBUG^} (@code{gcc})
3196 Generate debugging information. This information is stored in the object
3197 file and copied from there to the final executable file by the linker,
3198 where it can be read by the debugger. You must use the
3199 @code{^-g^/DEBUG^} switch if you plan on using the debugger.
3201 @item ^-I^/SEARCH=^@var{dir}
3202 @cindex @code{^-I^/SEARCH^} (@code{gcc})
3203 @cindex RTL
3204 Direct GNAT to search the @var{dir} directory for source files needed by
3205 the current compilation
3206 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3208 @item ^-I-^/NOCURRENT_DIRECTORY^
3209 @cindex @code{^-I-^/NOCURRENT_DIRECTORY^} (@code{gcc})
3210 @cindex RTL
3211 Except for the source file named in the command line, do not look for source files
3212 in the directory containing the source file named in the command line
3213 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3215 @ifclear vms
3216 @item -o @var{file}
3217 @cindex @code{-o} (@code{gcc})
3218 This switch is used in @code{gcc} to redirect the generated object file
3219 and its associated ALI file. Beware of this switch with GNAT, because it may
3220 cause the object file and ALI file to have different names which in turn
3221 may confuse the binder and the linker.
3222 @end ifclear
3224 @ifclear vms
3225 @item -O[@var{n}]
3226 @cindex @code{-O} (@code{gcc})
3227 @var{n} controls the optimization level.
3229 @table @asis
3230 @item n = 0
3231 No optimization, the default setting if no @code{-O} appears
3233 @item n = 1
3234 Normal optimization, the default if you specify @code{-O} without
3235 an operand.
3237 @item n = 2
3238 Extensive optimization
3240 @item n = 3
3241 Extensive optimization with automatic inlining. This applies only to
3242 inlining within a unit. For details on control of inter-unit inlining
3243 see @xref{Subprogram Inlining Control}.
3244 @end table
3245 @end ifclear
3247 @ifset vms
3248 @item  /NOOPTIMIZE (default)
3249 @itemx /OPTIMIZE[=(keyword[,...])]
3250 Selects the level of optimization for your program. The supported
3251 keywords are as follows:
3252 @table @code
3253 @item   ALL (default)
3254 Perform most optimizations, including those that
3255 be expensive.
3257 @item   NONE
3258 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
3260 @item SOME
3261 Perform some optimizations, but omit ones that are costly.
3263 @item   DEVELOPMENT
3264 Same as @code{SOME}.
3266 @item   INLINING
3267 Full optimization, and also attempt automatic inlining of small
3268 subprograms within a unit (@pxref{Inlining of Subprograms}).
3270 @item   UNROLL_LOOPS
3271 Try to unroll loops. This keyword may be specified together with
3272 any keyword above other than @code{NONE}. Loop unrolling
3273 usually, but not always, improves the performance of programs.
3274 @end table
3275 @end ifset
3277 @item --RTS=@var{rts-path}
3278 @cindex @code{--RTS} (@code{gcc})
3279 Specifies the default location of the runtime library. Same meaning as the
3280 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
3282 @item ^-S^/ASM^
3283 @cindex @code{^-S^/ASM^} (@code{gcc})
3284 ^Used in place of @code{-c} to^Used to^
3285 cause the assembler source file to be
3286 generated, using @file{^.s^.S^} as the extension,
3287 instead of the object file.
3288 This may be useful if you need to examine the generated assembly code.
3290 @item ^-v^/VERBOSE^
3291 @cindex @code{^-v^/VERBOSE^} (@code{gcc})
3292 Show commands generated by the @code{gcc} driver. Normally used only for
3293 debugging purposes or if you need to be sure what version of the
3294 compiler you are executing.
3296 @ifclear vms
3297 @item -V @var{ver}
3298 @cindex @code{-V} (@code{gcc})
3299 Execute @var{ver} version of the compiler. This is the @code{gcc}
3300 version, not the GNAT version.
3301 @end ifclear
3303 @item -gnata
3304 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3305 activated.
3307 @item -gnatA
3308 Avoid processing @file{gnat.adc}. If a gnat.adc file is present, it will be ignored.
3310 @item -gnatb
3311 Generate brief messages to @file{stderr} even if verbose mode set.
3313 @item -gnatc
3314 Check syntax and semantics only (no code generation attempted).
3316 @item -gnatC
3317 Compress debug information and external symbol name table entries.
3319 @item -gnatD
3320 Output expanded source files for source level debugging. This switch
3321 also suppress generation of cross-reference information (see -gnatx).
3323 @item -gnatec@var{path}
3324 Specify a configuration pragma file. (see @ref{The Configuration Pragmas Files})
3326 @item -gnatem@var{path}
3327 Specify a mapping file. (see @ref{Units to Sources Mapping Files})
3329 @item -gnatE
3330 Full dynamic elaboration checks.
3332 @item -gnatf
3333 Full errors. Multiple errors per line, all undefined references.
3335 @item -gnatF
3336 Externals names are folded to all uppercase.
3338 @item -gnatg
3339 Internal GNAT implementation mode. This should not be used for
3340 applications programs, it is intended only for use by the compiler
3341 and its run-time library. For documentation, see the GNAT sources.
3343 @item -gnatG
3344 List generated expanded code in source form.
3346 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3347 Identifier character set
3348 @ifclear vms
3349 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3350 @end ifclear
3351 @ifset vms
3352 For details of the possible selections for @var{c},
3353 see @xref{Character Set Control}.
3354 @end ifset
3356 @item ^-gnath^/HELP^
3357 Output usage information. The output is written to @file{stdout}.
3359 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
3360 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3362 @item -gnatl
3363 Output full source listing with embedded error messages.
3365 @item -gnatm^^=^@var{n}
3366 Limit number of detected errors to @var{n} (1-999).
3368 @item -gnatn
3369 Activate inlining across unit boundaries for subprograms for which
3370 pragma @code{inline} is specified.
3372 @item -gnatN
3373 Activate front end inlining.
3375 @item ^-fno-inline^/INLINE=SUPPRESS^
3376 Suppresses all inlining, even if other optimization or inlining switches
3377 are set.
3379 @ifclear vms
3380 @item -fstack-check
3381 Activates stack checking. See separate section on stack checking for
3382 details of the use of this option.
3383 @end ifclear
3385 @item -gnato
3386 Enable numeric overflow checking (which is not normally enabled by
3387 default). Not that division by zero is a separate check that is not
3388 controlled by this switch (division by zero checking is on by default).
3390 @item -gnatp
3391 Suppress all checks.
3393 @item -gnatq
3394 Don't quit; try semantics, even if parse errors.
3396 @item -gnatQ
3397 Don't quit; generate @file{ali} and tree files even if illegalities.
3399 @item -gnatP
3400 Enable polling. This is required on some systems (notably Windows NT) to
3401 obtain asynchronous abort and asynchronous transfer of control capability.
3402 See the description of pragma Polling in the GNAT Reference Manual for
3403 full details.
3405 @item -gnatR[0/1/2/3][s]
3406 Output representation information for declared types and objects.
3408 @item -gnats
3409 Syntax check only.
3411 @item -gnatt
3412 Tree output file to be generated.
3414 @item -gnatT nnn
3415 Set time slice to specified number of microseconds
3417 @item -gnatu
3418 List units for this compilation.
3420 @item -gnatU
3421 Tag all error messages with the unique string "error:"
3423 @item -gnatv
3424 Verbose mode. Full error output with source lines to @file{stdout}.
3426 @item -gnatV
3427 Control level of validity checking. See separate section describing
3428 this feature.
3430 @item ^-gnatwxxx^/WARNINGS=^@var{xxx}
3431 Warning mode where
3432 @var{xxx} is a string of options describing the exact warnings that
3433 are enabled or disabled. See separate section on warning control.
3435 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3436 Wide character encoding method
3437 @ifclear vms
3438 (@var{e}=n/h/u/s/e/8).
3439 @end ifclear
3440 @ifset vms
3441 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3442 @end ifset
3444 @item -gnatx
3445 Suppress generation of cross-reference information.
3447 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3448 Enable built-in style checks. See separate section describing this feature.
3450 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3451 Distribution stub generation and compilation
3452 @ifclear vms
3453 (@var{m}=r/c for receiver/caller stubs).
3454 @end ifclear
3455 @ifset vms
3456 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3457 to be generated and compiled).
3458 @end ifset
3460 @item -gnat83
3461 Enforce Ada 83 restrictions.
3463 @ifclear vms
3464 @item -pass-exit-codes
3465 Catch exit codes from the compiler and use the most meaningful as
3466 exit status.
3467 @end ifclear
3468 @end table
3470 @ifclear vms
3471 You may combine a sequence of GNAT switches into a single switch. For
3472 example, the combined switch
3474 @cindex Combining GNAT switches
3475 @smallexample
3476 -gnatofi3
3477 @end smallexample
3479 @noindent
3480 is equivalent to specifying the following sequence of switches:
3482 @smallexample
3483 -gnato -gnatf -gnati3
3484 @end smallexample
3485 @end ifclear
3487 @noindent
3488 The following restrictions apply to the combination of switches
3489 in this manner:
3491 @itemize @bullet
3492 @item
3493 The switch @option{-gnatc} if combined with other switches must come
3494 first in the string.
3496 @item
3497 The switch @option{-gnats} if combined with other switches must come
3498 first in the string.
3500 @item
3501 Once a "y" appears in the string (that is a use of the @option{-gnaty}
3502 switch), then all further characters in the switch are interpreted
3503 as style modifiers (see description of @option{-gnaty}).
3505 @item
3506 Once a "d" appears in the string (that is a use of the @option{-gnatd}
3507 switch), then all further characters in the switch are interpreted
3508 as debug flags (see description of @option{-gnatd}).
3510 @item
3511 Once a "w" appears in the string (that is a use of the @option{-gnatw}
3512 switch), then all further characters in the switch are interpreted
3513 as warning mode modifiers (see description of @option{-gnatw}).
3515 @item
3516 Once a "V" appears in the string (that is a use of the @option{-gnatV}
3517 switch), then all further characters in the switch are interpreted
3518 as validity checking options (see description of @option{-gnatV}).
3520 @end itemize
3522 @node Output and Error Message Control
3523 @subsection Output and Error Message Control
3524 @findex stderr
3526 @noindent
3527 The standard default format for error messages is called "brief format."
3528 Brief format messages are written to @file{stderr} (the standard error
3529 file) and have the following form:
3531 @smallexample
3532 @iftex
3533 @leftskip=.7cm
3534 @end iftex
3535 e.adb:3:04: Incorrect spelling of keyword "function"
3536 e.adb:4:20: ";" should be "is"
3537 @end smallexample
3539 @noindent
3540 The first integer after the file name is the line number in the file,
3541 and the second integer is the column number within the line.
3542 @code{glide} can parse the error messages
3543 and point to the referenced character.
3544 The following switches provide control over the error message
3545 format:
3547 @table @code
3548 @item -gnatv
3549 @cindex @option{-gnatv} (@code{gcc})
3550 @findex stdout
3551 @ifclear vms
3552 The v stands for verbose.
3553 @end ifclear
3554 The effect of this setting is to write long-format error
3555 messages to @file{stdout} (the standard output file.
3556 The same program compiled with the
3557 @option{-gnatv} switch would generate:
3559 @smallexample
3560 @group
3561 @cartouche
3562 3. funcion X (Q : Integer)
3563    |
3564 >>> Incorrect spelling of keyword "function"
3565 4. return Integer;
3566                  |
3567 >>> ";" should be "is"
3568 @end cartouche
3569 @end group
3570 @end smallexample
3572 @noindent
3573 The vertical bar indicates the location of the error, and the @samp{>>>}
3574 prefix can be used to search for error messages. When this switch is
3575 used the only source lines output are those with errors.
3577 @item -gnatl
3578 @cindex @option{-gnatl} (@code{gcc})
3579 @ifclear vms
3580 The @code{l} stands for list.
3581 @end ifclear
3582 This switch causes a full listing of
3583 the file to be generated. The output might look as follows:
3585 @smallexample
3586 @group
3587 @cartouche
3588  1. procedure E is
3589  2.    V : Integer;
3590  3.    funcion X (Q : Integer)
3591        |
3592     >>> Incorrect spelling of keyword "function"
3593  4.     return Integer;
3594                       |
3595     >>> ";" should be "is"
3596  5.    begin
3597  6.       return Q + Q;
3598  7.    end;
3599  8. begin
3600  9.    V := X + X;
3601 10.end E;
3602 @end cartouche
3603 @end group
3604 @end smallexample
3606 @noindent
3607 @findex stderr
3608 When you specify the @option{-gnatv} or @option{-gnatl} switches and
3609 standard output is redirected, a brief summary is written to
3610 @file{stderr} (standard error) giving the number of error messages and
3611 warning messages generated.
3613 @item -gnatU
3614 @cindex @option{-gnatU} (@code{gcc})
3615 This switch forces all error messages to be preceded by the unique
3616 string "error:". This means that error messages take a few more
3617 characters in space, but allows easy searching for and identification
3618 of error messages.
3620 @item -gnatb
3621 @cindex @option{-gnatb} (@code{gcc})
3622 @ifclear vms
3623 The @code{b} stands for brief.
3624 @end ifclear
3625 This switch causes GNAT to generate the
3626 brief format error messages to @file{stderr} (the standard error
3627 file) as well as the verbose
3628 format message or full listing (which as usual is written to
3629 @file{stdout} (the standard output file).
3631 @item -gnatm^^=^@var{n}
3632 @cindex @option{-gnatm} (@code{gcc})
3633 @ifclear vms
3634 The @code{m} stands for maximum.
3635 @end ifclear
3636 @var{n} is a decimal integer in the
3637 range of 1 to 999 and limits the number of error messages to be
3638 generated. For example, using @option{-gnatm2} might yield
3640 @smallexample
3641 @iftex
3642 @leftskip=.7cm
3643 @end iftex
3644 e.adb:3:04: Incorrect spelling of keyword "function"
3645 e.adb:5:35: missing ".."
3646 fatal error: maximum errors reached
3647 compilation abandoned
3648 @end smallexample
3650 @item -gnatf
3651 @cindex @option{-gnatf} (@code{gcc})
3652 @cindex Error messages, suppressing
3653 @ifclear vms
3654 The @code{f} stands for full.
3655 @end ifclear
3656 Normally, the compiler suppresses error messages that are likely to be
3657 redundant. This switch causes all error
3658 messages to be generated. In particular, in the case of
3659 references to undefined variables. If a given variable is referenced
3660 several times, the normal format of messages is
3661 @smallexample
3662 @iftex
3663 @leftskip=.7cm
3664 @end iftex
3665 e.adb:7:07: "V" is undefined (more references follow)
3666 @end smallexample
3668 @noindent
3669 where the parenthetical comment warns that there are additional
3670 references to the variable @code{V}. Compiling the same program with the
3671 @option{-gnatf} switch yields
3673 @smallexample
3674 e.adb:7:07: "V" is undefined
3675 e.adb:8:07: "V" is undefined
3676 e.adb:8:12: "V" is undefined
3677 e.adb:8:16: "V" is undefined
3678 e.adb:9:07: "V" is undefined
3679 e.adb:9:12: "V" is undefined
3680 @end smallexample
3682 @item -gnatq
3683 @cindex @option{-gnatq} (@code{gcc})
3684 @ifclear vms
3685 The @code{q} stands for quit (really "don't quit").
3686 @end ifclear
3687 In normal operation mode, the compiler first parses the program and
3688 determines if there are any syntax errors. If there are, appropriate
3689 error messages are generated and compilation is immediately terminated.
3690 This switch tells
3691 GNAT to continue with semantic analysis even if syntax errors have been
3692 found. This may enable the detection of more errors in a single run. On
3693 the other hand, the semantic analyzer is more likely to encounter some
3694 internal fatal error when given a syntactically invalid tree.
3696 @item -gnatQ
3697 In normal operation mode, the @file{ali} file is not generated if any
3698 illegalities are detected in the program. The use of @option{-gnatQ} forces
3699 generation of the @file{ali} file. This file is marked as being in
3700 error, so it cannot be used for binding purposes, but it does contain
3701 reasonably complete cross-reference information, and thus may be useful
3702 for use by tools (e.g. semantic browsing tools or integrated development
3703 environments) that are driven from the @file{ali} file.
3705 In addition, if @option{-gnatt} is also specified, then the tree file is
3706 generated even if there are illegalities. It may be useful in this case
3707 to also specify @option{-gnatq} to ensure that full semantic processing
3708 occurs. The resulting tree file can be processed by ASIS, for the purpose
3709 of providing partial information about illegal units, but if the error
3710 causes the tree to be badly malformed, then ASIS may crash during the
3711 analysis.
3713 @end table
3715 @noindent
3716 In addition to error messages, which correspond to illegalities as defined
3717 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
3718 situations.
3720 @cindex Warning messages
3721 First, the compiler considers some constructs suspicious and generates a
3722 warning message to alert you to a possible error. Second, if the
3723 compiler detects a situation that is sure to raise an exception at
3724 run time, it generates a warning message. The following shows an example
3725 of warning messages:
3726 @smallexample
3727 @iftex
3728 @leftskip=.2cm
3729 @end iftex
3730 e.adb:4:24: warning: creation of object may raise Storage_Error
3731 e.adb:10:17: warning: static value out of range
3732 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
3734 @end smallexample
3736 @noindent
3737 GNAT considers a large number of situations as appropriate
3738 for the generation of warning messages. As always, warnings are not
3739 definite indications of errors. For example, if you do an out-of-range
3740 assignment with the deliberate intention of raising a
3741 @code{Constraint_Error} exception, then the warning that may be
3742 issued does not indicate an error. Some of the situations for which GNAT
3743 issues warnings (at least some of the time) are given in the following
3744 list, which is not necessarily complete.
3746 @itemize @bullet
3747 @item
3748 Possible infinitely recursive calls
3750 @item
3751 Out-of-range values being assigned
3753 @item
3754 Possible order of elaboration problems
3756 @item
3757 Unreachable code
3759 @item
3760 Fixed-point type declarations with a null range
3762 @item
3763 Variables that are never assigned a value
3765 @item
3766 Variables that are referenced before being initialized
3768 @item
3769 Task entries with no corresponding accept statement
3771 @item
3772 Duplicate accepts for the same task entry in a select
3774 @item
3775 Objects that take too much storage
3777 @item
3778 Unchecked conversion between types of differing sizes
3780 @item
3781 Missing return statements along some execution paths in a function
3783 @item
3784 Incorrect (unrecognized) pragmas
3786 @item
3787 Incorrect external names
3789 @item
3790 Allocation from empty storage pool
3792 @item
3793 Potentially blocking operations in protected types
3795 @item
3796 Suspicious parenthesization of expressions
3798 @item
3799 Mismatching bounds in an aggregate
3801 @item
3802 Attempt to return local value by reference
3804 @item
3805 Unrecognized pragmas
3807 @item
3808 Premature instantiation of a generic body
3810 @item
3811 Attempt to pack aliased components
3813 @item
3814 Out of bounds array subscripts
3816 @item
3817 Wrong length on string assignment
3819 @item
3820 Violations of style rules if style checking is enabled
3822 @item
3823 Unused with clauses
3825 @item
3826 Bit_Order usage that does not have any effect
3828 @item
3829 Compile time biased rounding of floating-point constant
3831 @item
3832 Standard.Duration used to resolve universal fixed expression
3834 @item
3835 Dereference of possibly null value
3837 @item
3838 Declaration that is likely to cause storage error
3840 @item
3841 Internal GNAT unit with'ed by application unit
3843 @item
3844 Values known to be out of range at compile time
3846 @item
3847 Unreferenced labels and variables
3849 @item
3850 Address overlays that could clobber memory
3852 @item
3853 Unexpected initialization when address clause present
3855 @item
3856 Bad alignment for address clause
3858 @item
3859 Useless type conversions
3861 @item
3862 Redundant assignment statements
3864 @item
3865 Accidental hiding of name by child unit
3867 @item
3868 Unreachable code
3870 @item
3871 Access before elaboration detected at compile time
3873 @item
3874 A range in a @code{for} loop that is known to be null or might be null
3876 @end itemize
3878 @noindent
3879 The following switches are available to control the handling of
3880 warning messages:
3882 @table @code
3883 @item -gnatwa (activate all optional errors)
3884 @cindex @option{-gnatwa} (@code{gcc})
3885 This switch activates most optional warning messages, see remaining list
3886 in this section for details on optional warning messages that can be
3887 individually controlled. The warnings that are not turned on by this
3888 switch are @option{-gnatwb} (biased rounding),
3889 @option{-gnatwd} (implicit dereferencing),
3890 and @option{-gnatwh} (hiding). All other optional warnings are
3891 turned on.
3893 @item -gnatwA (suppress all optional errors)
3894 @cindex @option{-gnatwA} (@code{gcc})
3895 This switch suppresses all optional warning messages, see remaining list
3896 in this section for details on optional warning messages that can be
3897 individually controlled.
3899 @item -gnatwb (activate warnings on biased rounding)
3900 @cindex @option{-gnatwb} (@code{gcc})
3901 @cindex Rounding, biased
3902 @cindex Biased rounding
3903 If a static floating-point expression has a value that is exactly half
3904 way between two adjacent machine numbers, then the rules of Ada
3905 (Ada Reference Manual, section 4.9(38)) require that this rounding
3906 be done away from zero, even if the normal unbiased rounding rules
3907 at run time would require rounding towards zero. This warning message
3908 alerts you to such instances where compile-time rounding and run-time
3909 rounding are not equivalent. If it is important to get proper run-time
3910 rounding, then you can force this by making one of the operands into
3911 a variable. The default is that such warnings are not generated.
3912 Note that @option{-gnatwa} does not affect the setting of
3913 this warning option.
3915 @item -gnatwB (suppress warnings on biased rounding)
3916 @cindex @option{-gnatwB} (@code{gcc})
3917 This switch disables warnings on biased rounding.
3919 @item -gnatwc (activate warnings on conditionals)
3920 @cindex @option{-gnatwc} (@code{gcc})
3921 @cindex Conditionals, constant
3922 This switch activates warnings for conditional expressions used in
3923 tests that are known to be True or False at compile time. The default
3924 is that such warnings are not generated.
3925 This warning can also be turned on using @option{-gnatwa}.
3927 @item -gnatwC (suppress warnings on conditionals)
3928 @cindex @option{-gnatwC} (@code{gcc})
3929 This switch suppresses warnings for conditional expressions used in
3930 tests that are known to be True or False at compile time.
3932 @item -gnatwd (activate warnings on implicit dereferencing)
3933 @cindex @option{-gnatwd} (@code{gcc})
3934 If this switch is set, then the use of a prefix of an access type
3935 in an indexed component, slice, or selected component without an
3936 explicit @code{.all} will generate a warning. With this warning
3937 enabled, access checks occur only at points where an explicit
3938 @code{.all} appears in the source code (assuming no warnings are
3939 generated as a result of this switch). The default is that such
3940 warnings are not generated.
3941 Note that @option{-gnatwa} does not affect the setting of
3942 this warning option.
3944 @item -gnatwD (suppress warnings on implicit dereferencing)
3945 @cindex @option{-gnatwD} (@code{gcc})
3946 @cindex Implicit dereferencing
3947 @cindex Dereferencing, implicit
3948 This switch suppresses warnings for implicit deferences in
3949 indexed components, slices, and selected components.
3951 @item -gnatwe (treat warnings as errors)
3952 @cindex @option{-gnatwe} (@code{gcc})
3953 @cindex Warnings, treat as error
3954 This switch causes warning messages to be treated as errors.
3955 The warning string still appears, but the warning messages are counted
3956 as errors, and prevent the generation of an object file.
3958 @item -gnatwf (activate warnings on unreferenced formals)
3959 @cindex @option{-gnatwf} (@code{gcc})
3960 @cindex Formals, unreferenced
3961 This switch causes a warning to be generated if a formal parameter
3962 is not referenced in the body of the subprogram. This warning can
3963 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
3965 @item -gnatwF (suppress warnings on unreferenced formals)
3966 @cindex @option{-gnatwF} (@code{gcc})
3967 This switch suppresses warnings for unreferenced formal
3968 parameters. Note that the
3969 combination @option{-gnatwu} followed by @option{-gnatwF} has the
3970 effect of warning on unreferenced entities other than subprogram
3971 formals.
3973 @item -gnatwh (activate warnings on hiding)
3974 @cindex @option{-gnatwh} (@code{gcc})
3975 @cindex Hiding of Declarations
3976 This switch activates warnings on hiding declarations.
3977 A declaration is considered hiding
3978 if it is for a non-overloadable entity, and it declares an entity with the
3979 same name as some other entity that is directly or use-visible. The default
3980 is that such warnings are not generated.
3981 Note that @option{-gnatwa} does not affect the setting of this warning option.
3983 @item -gnatwH (suppress warnings on hiding)
3984 @cindex @option{-gnatwH} (@code{gcc})
3985 This switch suppresses warnings on hiding declarations.
3987 @item -gnatwi (activate warnings on implementation units).
3988 @cindex @option{-gnatwi} (@code{gcc})
3989 This switch activates warnings for a @code{with} of an internal GNAT
3990 implementation unit, defined as any unit from the @code{Ada},
3991 @code{Interfaces}, @code{GNAT},
3992 ^^@code{DEC},^ or @code{System}
3993 hierarchies that is not
3994 documented in either the Ada Reference Manual or the GNAT
3995 Programmer's Reference Manual. Such units are intended only
3996 for internal implementation purposes and should not be @code{with}'ed
3997 by user programs. The default is that such warnings are generated
3998 This warning can also be turned on using @option{-gnatwa}.
4000 @item -gnatwI (disable warnings on implementation units).
4001 @cindex @option{-gnatwI} (@code{gcc})
4002 This switch disables warnings for a @code{with} of an internal GNAT
4003 implementation unit.
4005 @item -gnatwl (activate warnings on elaboration pragmas)
4006 @cindex @option{-gnatwl} (@code{gcc})
4007 @cindex Elaboration, warnings
4008 This switch activates warnings on missing pragma Elaborate_All statements.
4009 See the section in this guide on elaboration checking for details on
4010 when such pragma should be used. The default is that such warnings
4011 are not generated.
4012 This warning can also be turned on using @option{-gnatwa}.
4014 @item -gnatwL (suppress warnings on elaboration pragmas)
4015 @cindex @option{-gnatwL} (@code{gcc})
4016 This switch suppresses warnings on missing pragma Elaborate_All statements.
4017 See the section in this guide on elaboration checking for details on
4018 when such pragma should be used.
4020 @item -gnatwo (activate warnings on address clause overlays)
4021 @cindex @option{-gnatwo} (@code{gcc})
4022 @cindex Address Clauses, warnings
4023 This switch activates warnings for possibly unintended initialization
4024 effects of defining address clauses that cause one variable to overlap
4025 another. The default is that such warnings are generated.
4026 This warning can also be turned on using @option{-gnatwa}.
4028 @item -gnatwO (suppress warnings on address clause overlays)
4029 @cindex @option{-gnatwO} (@code{gcc})
4030 This switch suppresses warnings on possibly unintended initialization
4031 effects of defining address clauses that cause one variable to overlap
4032 another.
4034 @item -gnatwp (activate warnings on ineffective pragma Inlines)
4035 @cindex @option{-gnatwp} (@code{gcc})
4036 @cindex Inlining, warnings
4037 This switch activates warnings for failure of front end inlining
4038 (activated by @option{-gnatN}) to inline a particular call. There are
4039 many reasons for not being able to inline a call, including most
4040 commonly that the call is too complex to inline.
4041 This warning can also be turned on using @option{-gnatwa}.
4043 @item -gnatwP (suppress warnings on ineffective pragma Inlines)
4044 @cindex @option{-gnatwP} (@code{gcc})
4045 This switch suppresses warnings on ineffective pragma Inlines. If the
4046 inlining mechanism cannot inline a call, it will simply ignore the
4047 request silently.
4049 @item -gnatwr (activate warnings on redundant constructs)
4050 @cindex @option{-gnatwr} (@code{gcc})
4051 This switch activates warnings for redundant constructs. The following
4052 is the current list of constructs regarded as redundant:
4053 This warning can also be turned on using @option{-gnatwa}.
4055 @itemize @bullet
4056 @item
4057 Assignment of an item to itself.
4058 @item
4059 Type conversion that converts an expression to its own type.
4060 @item
4061 Use of the attribute @code{Base} where @code{typ'Base} is the same
4062 as @code{typ}.
4063 @item
4064 Use of pragma @code{Pack} when all components are placed by a record
4065 representation clause.
4066 @end itemize
4068 @item -gnatwR (suppress warnings on redundant constructs)
4069 @cindex @option{-gnatwR} (@code{gcc})
4070 This switch suppresses warnings for redundant constructs.
4072 @item -gnatws (suppress all warnings)
4073 @cindex @option{-gnatws} (@code{gcc})
4074 This switch completely suppresses the
4075 output of all warning messages from the GNAT front end.
4076 Note that it does not suppress warnings from the @code{gcc} back end.
4077 To suppress these back end warnings as well, use the switch @code{-w}
4078 in addition to @option{-gnatws}.
4080 @item -gnatwu (activate warnings on unused entities)
4081 @cindex @option{-gnatwu} (@code{gcc})
4082 This switch activates warnings to be generated for entities that
4083 are defined but not referenced, and for units that are @code{with}'ed
4084 and not
4085 referenced. In the case of packages, a warning is also generated if
4086 no entities in the package are referenced. This means that if the package
4087 is referenced but the only references are in @code{use}
4088 clauses or @code{renames}
4089 declarations, a warning is still generated. A warning is also generated
4090 for a generic package that is @code{with}'ed but never instantiated.
4091 In the case where a package or subprogram body is compiled, and there
4092 is a @code{with} on the corresponding spec
4093 that is only referenced in the body,
4094 a warning is also generated, noting that the
4095 @code{with} can be moved to the body. The default is that
4096 such warnings are not generated.
4097 This switch also activates warnings on unreferenced formals
4098 (it is includes the effect of @option{-gnatwf}).
4099 This warning can also be turned on using @option{-gnatwa}.
4101 @item -gnatwU (suppress warnings on unused entities)
4102 @cindex @option{-gnatwU} (@code{gcc})
4103 This switch suppresses warnings for unused entities and packages.
4104 It also turns off warnings on unreferenced formals (and thus includes
4105 the effect of @option{-gnatwF}).
4107 @noindent
4108 A string of warning parameters can be used in the same parameter. For example:
4110 @smallexample
4111 -gnatwaLe
4112 @end smallexample
4114 @noindent
4115 Would turn on all optional warnings except for elaboration pragma warnings,
4116 and also specify that warnings should be treated as errors.
4118 @item -w
4119 @cindex @code{-w}
4120 This switch suppresses warnings from the @code{gcc} backend. It may be
4121 used in conjunction with @option{-gnatws} to ensure that all warnings
4122 are suppressed during the entire compilation process.
4124 @end table
4126 @node Debugging and Assertion Control
4127 @subsection Debugging and Assertion Control
4129 @table @code
4130 @item -gnata
4131 @cindex @option{-gnata} (@code{gcc})
4132 @findex Assert
4133 @findex Debug
4134 @cindex Assertions
4136 @noindent
4137 The pragmas @code{Assert} and @code{Debug} normally have no effect and
4138 are ignored. This switch, where @samp{a} stands for assert, causes
4139 @code{Assert} and @code{Debug} pragmas to be activated.
4141 The pragmas have the form:
4143 @smallexample
4144 @group
4145 @cartouche
4146    @b{pragma} Assert (@var{Boolean-expression} [,
4147                       @var{static-string-expression}])
4148    @b{pragma} Debug (@var{procedure call})
4149 @end cartouche
4150 @end group
4151 @end smallexample
4153 @noindent
4154 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
4155 If the result is @code{True}, the pragma has no effect (other than
4156 possible side effects from evaluating the expression). If the result is
4157 @code{False}, the exception @code{Assert_Failure} declared in the package
4158 @code{System.Assertions} is
4159 raised (passing @var{static-string-expression}, if present, as the
4160 message associated with the exception). If no string expression is
4161 given the default is a string giving the file name and line number
4162 of the pragma.
4164 The @code{Debug} pragma causes @var{procedure} to be called. Note that
4165 @code{pragma Debug} may appear within a declaration sequence, allowing
4166 debugging procedures to be called between declarations.
4168 @ifset vms
4169 @item /DEBUG[=debug-level]
4170 @itemx  /NODEBUG
4171 Specifies how much debugging information is to be included in
4172 the resulting object file where 'debug-level' is one of the following:
4173 @table @code
4174 @item   TRACEBACK (default)
4175 Include both debugger symbol records and traceback
4176 the object file.
4177 @item   ALL
4178 Include both debugger symbol records and traceback in
4179 object file.
4180 @item   NONE
4181 Excludes both debugger symbol records and traceback
4182 the object file. Same as /NODEBUG.
4183 @item   SYMBOLS
4184 Includes only debugger symbol records in the object
4185 file. Note that this doesn't include traceback information.
4186 @end table
4187 @end ifset
4188 @end table
4190 @node Validity Checking
4191 @subsection Validity Checking
4192 @findex Validity Checking
4194 @noindent
4195 The Ada 95 Reference Manual has specific requirements for checking
4196 for invalid values. In particular, RM 13.9.1 requires that the
4197 evaluation of invalid values (for example from unchecked conversions),
4198 not result in erroneous execution. In GNAT, the result of such an
4199 evaluation in normal default mode is to either use the value
4200 unmodified, or to raise Constraint_Error in those cases where use
4201 of the unmodified value would cause erroneous execution. The cases
4202 where unmodified values might lead to erroneous execution are case
4203 statements (where a wild jump might result from an invalid value),
4204 and subscripts on the left hand side (where memory corruption could
4205 occur as a result of an invalid value).
4207 The @option{-gnatVx} switch allows more control over the validity checking
4208 mode. The @code{x} argument here is a string of letters which control which
4209 validity checks are performed in addition to the default checks described
4210 above.
4212 @itemize @bullet
4213 @item
4214 @option{-gnatVc} Validity checks for copies
4216 The right hand side of assignments, and the initializing values of
4217 object declarations are validity checked.
4219 @item
4220 @option{-gnatVd} Default (RM) validity checks
4222 Some validity checks are done by default following normal Ada semantics
4223 (RM 13.9.1 (9-11)).
4224 A check is done in case statements that the expression is within the range
4225 of the subtype. If it is not, Constraint_Error is raised.
4226 For assignments to array components, a check is done that the expression used
4227 as index is within the range. If it is not, Constraint_Error is raised.
4228 Both these validity checks may be turned off using switch @option{-gnatVD}.
4229 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
4230 switch @option{-gnatVd} will leave the checks turned on.
4231 Switch @option{-gnatVD} should be used only if you are sure that all such
4232 expressions have valid values. If you use this switch and invalid values
4233 are present, then the program is erroneous, and wild jumps or memory
4234 overwriting may occur.
4236 @item
4237 @option{-gnatVi} Validity checks for @code{in} mode parameters
4239 Arguments for parameters of mode @code{in} are validity checked in function
4240 and procedure calls at the point of call.
4242 @item
4243 @option{-gnatVm} Validity checks for @code{in out} mode parameters
4245 Arguments for parameters of mode @code{in out} are validity checked in
4246 procedure calls at the point of call. The @code{'m'} here stands for
4247 modify, since this concerns parameters that can be modified by the call.
4248 Note that there is no specific option to test @code{out} parameters,
4249 but any reference within the subprogram will be tested in the usual
4250 manner, and if an invalid value is copied back, any reference to it
4251 will be subject to validity checking.
4253 @item
4254 @option{-gnatVo} Validity checks for operator and attribute operands
4256 Arguments for predefined operators and attributes are validity checked.
4257 This includes all operators in package @code{Standard},
4258 the shift operators defined as intrinsic in package @code{Interfaces}
4259 and operands for attributes such as @code{Pos}.
4261 @item
4262 @option{-gnatVr} Validity checks for function returns
4264 The expression in @code{return} statements in functions is validity
4265 checked.
4267 @item
4268 @option{-gnatVs} Validity checks for subscripts
4270 All subscripts expressions are checked for validity, whether they appear
4271 on the right side or left side (in default mode only left side subscripts
4272 are validity checked).
4274 @item
4275 @option{-gnatVt} Validity checks for tests
4277 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
4278 statements are checked, as well as guard expressions in entry calls.
4280 @item
4281 @option{-gnatVf} Validity checks for floating-point values
4283 In the absence of this switch, validity checking occurs only for discrete
4284 values. If @option{-gnatVf} is specified, then validity checking also applies
4285 for floating-point values, and NaN's and infinities are considered invalid,
4286 as well as out of range values for constrained types. Note that this means
4287 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
4288 in which floating-point values are checked depends on the setting of other
4289 options. For example @option{-gnatVif} or @option{-gnatVfi} (the order does
4290 not matter) specifies that floating-point parameters of mode @code{in} should
4291 be validity checked.
4293 @item
4294 @option{-gnatVa} All validity checks
4296 All the above validity checks are turned on. That is @option{-gnatVa} is
4297 equivalent to @code{gnatVcdfimorst}.
4299 @item
4300 @option{-gnatVn} No validity checks
4302 This switch turns off all validity checking, including the default checking
4303 for case statements and left hand side subscripts. Note that the use of
4304 the switch @option{-gnatp} supresses all run-time checks, including
4305 validity checks, and thus implies @option{-gnatVn}.
4307 @end itemize
4309 The @option{-gnatV} switch may be followed by a string of letters to turn on
4310 a series of validity checking options. For example, @option{-gnatVcr} specifies
4311 that in addition to the default validity checking, copies and function
4312 return expressions be validity checked. In order to make it easier to specify
4313 a set of options, the upper case letters @code{CDFIMORST} may be used to turn
4314 off the corresponding lower case option, so for example @option{-gnatVaM} turns
4315 on all validity checking options except for checking of @code{in out}
4316 procedure arguments.
4318 The specification of additional validity checking generates extra code (and
4319 in the case of @option{-gnatva} the code expansion can be substantial. However,
4320 these additional checks can be very useful in smoking out cases of
4321 uninitialized variables, incorrect use of unchecked conversion, and other
4322 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
4323 is useful in conjunction with the extra validity checking, since this
4324 ensures that wherever possible uninitialized variables have invalid values.
4326 See also the pragma @code{Validity_Checks} which allows modification of
4327 the validity checking mode at the program source level, and also allows for
4328 temporary disabling of validity checks.
4330 @node Style Checking
4331 @subsection Style Checking
4332 @findex Style checking
4334 @noindent
4335 The -gnaty@var{^x^(option,option,..)^} switch causes the compiler to
4336 enforce specified style rules. A limited set of style rules has been used
4337 in writing the GNAT sources themselves. This switch allows user programs
4338 to activate all or some of these checks. If the source program fails a
4339 specified style check, an appropriate warning message is given, preceded by
4340 the character sequence "(style)".
4341 @ifset vms
4342 (OPTION,OPTION,..) is a sequence of keywords
4343 @end ifset
4344 @ifclear vms
4345 The string @var{x} is a sequence of letters or digits
4346 @end ifclear
4347 indicating the particular style
4348 checks to be performed. The following checks are defined:
4350 @table @code
4351 @item 1-9 (specify indentation level)
4352 If a digit from 1-9 appears in the string after @option{-gnaty} then proper
4353 indentation is checked, with the digit indicating the indentation level
4354 required. The general style of required indentation is as specified by
4355 the examples in the Ada Reference Manual. Full line comments must be
4356 aligned with the @code{--} starting on a column that is a multiple of
4357 the alignment level.
4359 @item ^a^ATTRIBUTE^ (check attribute casing)
4360 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty} then
4361 attribute names, including the case of keywords such as @code{digits}
4362 used as attributes names, must be written in mixed case, that is, the
4363 initial letter and any letter following an underscore must be uppercase.
4364 All other letters must be lowercase.
4366 @item ^b^BLANKS^ (blanks not allowed at statement end)
4367 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
4368 trailing blanks are not allowed at the end of statements. The purpose of this
4369 rule, together with h (no horizontal tabs), is to enforce a canonical format
4370 for the use of blanks to separate source tokens.
4372 @item ^c^COMMENTS^ (check comments)
4373 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty} then
4374 comments must meet the following set of rules:
4376 @itemize @bullet
4378 @item
4379 The "--" that starts the column must either start in column one, or else
4380 at least one blank must precede this sequence.
4382 @item
4383 Comments that follow other tokens on a line must have at least one blank
4384 following the "--" at the start of the comment.
4386 @item
4387 Full line comments must have two blanks following the "--" that starts
4388 the comment, with the following exceptions.
4390 @item
4391 A line consisting only of the "--" characters, possibly preceded by blanks
4392 is permitted.
4394 @item
4395 A comment starting with "--x" where x is a special character is permitted.
4396 This alows proper processing of the output generated by specialized tools
4397 including @code{gnatprep} (where --! is used) and the SPARK annnotation
4398 language (where --# is used). For the purposes of this rule, a special
4399 character is defined as being in one of the ASCII ranges
4400 16#21#..16#2F# or 16#3A#..16#3F#.
4402 @item
4403 A line consisting entirely of minus signs, possibly preceded by blanks, is
4404 permitted. This allows the construction of box comments where lines of minus
4405 signs are used to form the top and bottom of the box.
4407 @item
4408 If a comment starts and ends with "--" is permitted as long as at least
4409 one blank follows the initial "--". Together with the preceding rule,
4410 this allows the construction of box comments, as shown in the following
4411 example:
4412 @smallexample
4413 ---------------------------
4414 -- This is a box comment --
4415 -- with two text lines.  --
4416 ---------------------------
4417 @end smallexample
4418 @end itemize
4420 @item ^e^END^ (check end/exit labels)
4421 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
4422 optional labels on @code{end} statements ending subprograms and on
4423 @code{exit} statements exiting named loops, are required to be present.
4425 @item ^f^VTABS^ (no form feeds or vertical tabs)
4426 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
4427 neither form feeds nor vertical tab characters are not permitted
4428 in the source text.
4430 @item ^h^HTABS^ (no horizontal tabs)
4431 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
4432 horizontal tab characters are not permitted in the source text.
4433 Together with the b (no blanks at end of line) check, this
4434 enforces a canonical form for the use of blanks to separate
4435 source tokens.
4437 @item ^i^IF_THEN^ (check if-then layout)
4438 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
4439 then the keyword @code{then} must appear either on the same
4440 line as corresponding @code{if}, or on a line on its own, lined
4441 up under the @code{if} with at least one non-blank line in between
4442 containing all or part of the condition to be tested.
4444 @item ^k^KEYWORD^ (check keyword casing)
4445 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
4446 all keywords must be in lower case (with the exception of keywords
4447 such as @code{digits} used as attribute names to which this check
4448 does not apply).
4450 @item ^l^LAYOUT^ (check layout)
4451 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
4452 layout of statement and declaration constructs must follow the
4453 recommendations in the Ada Reference Manual, as indicated by the
4454 form of the syntax rules. For example an @code{else} keyword must
4455 be lined up with the corresponding @code{if} keyword.
4457 There are two respects in which the style rule enforced by this check
4458 option are more liberal than those in the Ada Reference Manual. First
4459 in the case of record declarations, it is permissible to put the
4460 @code{record} keyword on the same line as the @code{type} keyword, and
4461 then the @code{end} in @code{end record} must line up under @code{type}.
4462 For example, either of the following two layouts is acceptable:
4464 @smallexample
4465 @group
4466 @cartouche
4467 @b{type} q @b{is record}
4468    a : integer;
4469    b : integer;
4470 @b{end record};
4472 @b{type} q @b{is}
4473    @b{record}
4474       a : integer;
4475       b : integer;
4476    @b{end record};
4477 @end cartouche
4478 @end group
4479 @end smallexample
4481 @noindent
4482 Second, in the case of a block statement, a permitted alternative
4483 is to put the block label on the same line as the @code{declare} or
4484 @code{begin} keyword, and then line the @code{end} keyword up under
4485 the block label. For example both the following are permitted:
4487 @smallexample
4488 @group
4489 @cartouche
4490 Block : @b{declare}
4491    A : Integer := 3;
4492 @b{begin}
4493    Proc (A, A);
4494 @b{end} Block;
4496 Block :
4497    @b{declare}
4498       A : Integer := 3;
4499    @b{begin}
4500       Proc (A, A);
4501    @b{end} Block;
4502 @end cartouche
4503 @end group
4504 @end smallexample
4506 @noindent
4507 The same alternative format is allowed for loops. For example, both of
4508 the following are permitted:
4510 @smallexample
4511 @group
4512 @cartouche
4513 Clear : @b{while} J < 10 @b{loop}
4514    A (J) := 0;
4515 @b{end loop} Clear;
4517 Clear :
4518    @b{while} J < 10 @b{loop}
4519       A (J) := 0;
4520    @b{end loop} Clear;
4521 @end cartouche
4522 @end group
4523 @end smallexample
4525 @item ^m^LINE_LENGTH^ (check maximum line length)
4526 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
4527 then the length of source lines must not exceed 79 characters, including
4528 any trailing blanks. The value of 79 allows convenient display on an
4529 80 character wide device or window, allowing for possible special
4530 treatment of 80 character lines.
4532 @item ^Mnnn^MAX_LENGTH=nnn^ (set maximum line length)
4533 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
4534 the string after @option{-gnaty} then the length of lines must not exceed the
4535 given value.
4537 @item ^n^STANDARD_CASING^ (check casing of entities in Standard)
4538 If the ^letter n^word STANDARD_CASING^ appears in the string
4539 after @option{-gnaty} then any identifier from Standard must be cased
4540 to match the presentation in the Ada Reference Manual (for example,
4541 @code{Integer} and @code{ASCII.NUL}).
4543 @item ^o^ORDERED_SUBPROGRAMS^ (check order of subprogram bodies)
4544 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
4545 after @option{-gnaty} then all subprogram bodies in a given scope
4546 (e.g. a package body) must be in alphabetical order. The ordering
4547 rule uses normal Ada rules for comparing strings, ignoring casing
4548 of letters, except that if there is a trailing numeric suffix, then
4549 the value of this suffix is used in the ordering (e.g. Junk2 comes
4550 before Junk10).
4552 @item ^p^PRAGMA^ (check pragma casing)
4553 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
4554 pragma names must be written in mixed case, that is, the
4555 initial letter and any letter following an underscore must be uppercase.
4556 All other letters must be lowercase.
4558 @item ^r^REFERENCES^ (check references)
4559 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
4560 then all identifier references must be cased in the same way as the
4561 corresponding declaration. No specific casing style is imposed on
4562 identifiers. The only requirement is for consistency of references
4563 with declarations.
4565 @item ^s^SPECS^ (check separate specs)
4566 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
4567 separate declarations ("specs") are required for subprograms (a
4568 body is not allowed to serve as its own declaration). The only
4569 exception is that parameterless library level procedures are
4570 not required to have a separate declaration. This exception covers
4571 the most frequent form of main program procedures.
4573 @item ^t^TOKEN^ (check token spacing)
4574 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
4575 the following token spacing rules are enforced:
4577 @itemize @bullet
4579 @item
4580 The keywords @code{abs} and @code{not} must be followed by a space.
4582 @item
4583 The token @code{=>} must be surrounded by spaces.
4585 @item
4586 The token @code{<>} must be preceded by a space or a left parenthesis.
4588 @item
4589 Binary operators other than @code{**} must be surrounded by spaces.
4590 There is no restriction on the layout of the @code{**} binary operator.
4592 @item
4593 Colon must be surrounded by spaces.
4595 @item
4596 Colon-equal (assignment) must be surrounded by spaces.
4598 @item
4599 Comma must be the first non-blank character on the line, or be
4600 immediately preceded by a non-blank character, and must be followed
4601 by a space.
4603 @item
4604 If the token preceding a left paren ends with a letter or digit, then
4605 a space must separate the two tokens.
4607 @item
4608 A right parenthesis must either be the first non-blank character on
4609 a line, or it must be preceded by a non-blank character.
4611 @item
4612 A semicolon must not be preceded by a space, and must not be followed by
4613 a non-blank character.
4615 @item
4616 A unary plus or minus may not be followed by a space.
4618 @item
4619 A vertical bar must be surrounded by spaces.
4620 @end itemize
4622 @noindent
4623 In the above rules, appearing in column one is always permitted, that is,
4624 counts as meeting either a requirement for a required preceding space,
4625 or as meeting a requirement for no preceding space.
4627 Appearing at the end of a line is also always permitted, that is, counts
4628 as meeting either a requirement for a following space, or as meeting
4629 a requirement for no following space.
4631 @end table
4633 @noindent
4634 If any of these style rules is violated, a message is generated giving
4635 details on the violation. The initial characters of such messages are
4636 always "(style)". Note that these messages are treated as warning
4637 messages, so they normally do not prevent the generation of an object
4638 file. The @option{-gnatwe} switch can be used to treat warning messages,
4639 including style messages, as fatal errors.
4641 @noindent
4642 The switch
4643 ^@option{-gnaty} on its own (that is not followed by any letters or digits),^/STYLE_CHECKS=ALL_BUILTIN^
4644 is equivalent to ^@code{gnaty3abcefhiklmprst}, that is^^ all checking
4645 options ^are^^ enabled with
4646 the exception of ^-gnatyo^ORDERED_SUBPROGRAMS^,
4647 with an indentation level of 3. This is the standard
4648 checking option that is used for the GNAT sources.
4650 @node Run-Time Checks
4651 @subsection Run-Time Checks
4652 @cindex Division by zero
4653 @cindex Access before elaboration
4654 @cindex Checks, division by zero
4655 @cindex Checks, access before elaboration
4657 @noindent
4658 If you compile with the default options, GNAT will insert many run-time
4659 checks into the compiled code, including code that performs range
4660 checking against constraints, but not arithmetic overflow checking for
4661 integer operations (including division by zero) or checks for access
4662 before elaboration on subprogram calls. All other run-time checks, as
4663 required by the Ada 95 Reference Manual, are generated by default.
4664 The following @code{gcc} switches refine this default behavior:
4666 @table @code
4667 @item -gnatp
4668 @cindex @option{-gnatp} (@code{gcc})
4669 @cindex Suppressing checks
4670 @cindex Checks, suppressing
4671 @findex Suppress
4672 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
4673 had been present in the source. Validity checks are also suppressed (in
4674 other words @option{-gnatp} also implies @option{-gnatVn}.
4675 Use this switch to improve the performance
4676 of the code at the expense of safety in the presence of invalid data or
4677 program bugs.
4679 @item -gnato
4680 @cindex @option{-gnato} (@code{gcc})
4681 @cindex Overflow checks
4682 @cindex Check, overflow
4683 Enables overflow checking for integer operations.
4684 This causes GNAT to generate slower and larger executable
4685 programs by adding code to check for overflow (resulting in raising
4686 @code{Constraint_Error} as required by standard Ada
4687 semantics). These overflow checks correspond to situations in which
4688 the true value of the result of an operation may be outside the base
4689 range of the result type. The following example shows the distinction:
4691 @smallexample
4692 X1 : Integer := Integer'Last;
4693 X2 : Integer range 1 .. 5 := 5;
4695 X1 := X1 + 1;   -- @option{-gnato} required to catch the Constraint_Error
4696 X2 := X2 + 1;   -- range check, @option{-gnato} has no effect here
4697 @end smallexample
4699 @noindent
4700 Here the first addition results in a value that is outside the base range
4701 of Integer, and hence requires an overflow check for detection of the
4702 constraint error. The second increment operation results in a violation
4703 of the explicit range constraint, and such range checks are always
4704 performed. Basically the compiler can assume that in the absence of
4705 the @option{-gnato} switch that any value of type @code{xxx} is
4706 in range of the base type of @code{xxx}.
4708 @findex Machine_Overflows
4709 Note that the @option{-gnato} switch does not affect the code generated
4710 for any floating-point operations; it applies only to integer
4711 semantics).
4712 For floating-point, GNAT has the @code{Machine_Overflows}
4713 attribute set to @code{False} and the normal mode of operation is to
4714 generate IEEE NaN and infinite values on overflow or invalid operations
4715 (such as dividing 0.0 by 0.0).
4717 The reason that we distinguish overflow checking from other kinds of
4718 range constraint checking is that a failure of an overflow check can
4719 generate an incorrect value, but cannot cause erroneous behavior. This
4720 is unlike the situation with a constraint check on an array subscript,
4721 where failure to perform the check can result in random memory description,
4722 or the range check on a case statement, where failure to perform the check
4723 can cause a wild jump.
4725 Note again that @option{-gnato} is off by default, so overflow checking is
4726 not performed in default mode. This means that out of the box, with the
4727 default settings, GNAT does not do all the checks expected from the
4728 language description in the Ada Reference Manual. If you want all constraint
4729 checks to be performed, as described in this Manual, then you must
4730 explicitly use the -gnato switch either on the @code{gnatmake} or
4731 @code{gcc} command.
4733 @item -gnatE
4734 @cindex @option{-gnatE} (@code{gcc})
4735 @cindex Elaboration checks
4736 @cindex Check, elaboration
4737 Enables dynamic checks for access-before-elaboration
4738 on subprogram calls and generic instantiations.
4739 For full details of the effect and use of this switch,
4740 @xref{Compiling Using gcc}.
4741 @end table
4743 @findex Unsuppress
4744 @noindent
4745 The setting of these switches only controls the default setting of the
4746 checks. You may modify them using either @code{Suppress} (to remove
4747 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
4748 the program source.
4750 @node Stack Overflow Checking
4751 @subsection Stack Overflow Checking
4752 @cindex Stack Overflow Checking
4753 @cindex -fstack-check
4755 @noindent
4756 For most operating systems, @code{gcc} does not perform stack overflow
4757 checking by default. This means that if the main environment task or
4758 some other task exceeds the available stack space, then unpredictable
4759 behavior will occur.
4761 To activate stack checking, compile all units with the gcc option
4762 @code{-fstack-check}. For example:
4764 @smallexample
4765 gcc -c -fstack-check package1.adb
4766 @end smallexample
4768 @noindent
4769 Units compiled with this option will generate extra instructions to check
4770 that any use of the stack (for procedure calls or for declaring local
4771 variables in declare blocks) do not exceed the available stack space.
4772 If the space is exceeded, then a @code{Storage_Error} exception is raised.
4774 For declared tasks, the stack size is always controlled by the size
4775 given in an applicable @code{Storage_Size} pragma (or is set to
4776 the default size if no pragma is used.
4778 For the environment task, the stack size depends on
4779 system defaults and is unknown to the compiler. The stack
4780 may even dynamically grow on some systems, precluding the
4781 normal Ada semantics for stack overflow. In the worst case,
4782 unbounded stack usage, causes unbounded stack expansion
4783 resulting in the system running out of virtual memory.
4785 The stack checking may still work correctly if a fixed
4786 size stack is allocated, but this cannot be guaranteed.
4787 To ensure that a clean exception is signalled for stack
4788 overflow, set the environment variable
4789 @code{GNAT_STACK_LIMIT} to indicate the maximum
4790 stack area that can be used, as in:
4791 @cindex GNAT_STACK_LIMIT
4793 @smallexample
4794 SET GNAT_STACK_LIMIT 1600
4795 @end smallexample
4797 @noindent
4798 The limit is given in kilobytes, so the above declaration would
4799 set the stack limit of the environment task to 1.6 megabytes.
4800 Note that the only purpose of this usage is to limit the amount
4801 of stack used by the environment task. If it is necessary to
4802 increase the amount of stack for the environment task, then this
4803 is an operating systems issue, and must be addressed with the
4804 appropriate operating systems commands.
4806 @node Run-Time Control
4807 @subsection Run-Time Control
4809 @table @code
4810 @item -gnatT nnn
4811 @cindex @option{-gnatT} (@code{gcc})
4812 @cindex Time Slicing
4814 @noindent
4815 The @code{gnatT} switch can be used to specify the time-slicing value
4816 to be used for task switching between equal priority tasks. The value
4817 @code{nnn} is given in microseconds as a decimal integer.
4819 Setting the time-slicing value is only effective if the underlying thread
4820 control system can accommodate time slicing. Check the documentation of
4821 your operating system for details. Note that the time-slicing value can
4822 also be set by use of pragma @code{Time_Slice} or by use of the
4823 @code{t} switch in the gnatbind step. The pragma overrides a command
4824 line argument if both are present, and the @code{t} switch for gnatbind
4825 overrides both the pragma and the @code{gcc} command line switch.
4826 @end table
4828 @node Using gcc for Syntax Checking
4829 @subsection Using @code{gcc} for Syntax Checking
4830 @table @code
4831 @item -gnats
4832 @cindex @option{-gnats} (@code{gcc})
4833 @ifclear vms
4835 @noindent
4836 The @code{s} stands for syntax.
4837 @end ifclear
4839 Run GNAT in syntax checking only mode. For
4840 example, the command
4842 @smallexample
4843 $ gcc -c -gnats x.adb
4844 @end smallexample
4846 @noindent
4847 compiles file @file{x.adb} in syntax-check-only mode. You can check a
4848 series of files in a single command
4849 @ifclear vms
4850 , and can use wild cards to specify such a group of files.
4851 Note that you must specify the @code{-c} (compile
4852 only) flag in addition to the @option{-gnats} flag.
4853 @end ifclear
4856 You may use other switches in conjunction with @option{-gnats}. In
4857 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
4858 format of any generated error messages.
4860 The output is simply the error messages, if any. No object file or ALI
4861 file is generated by a syntax-only compilation. Also, no units other
4862 than the one specified are accessed. For example, if a unit @code{X}
4863 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
4864 check only mode does not access the source file containing unit
4865 @code{Y}.
4867 @cindex Multiple units, syntax checking
4868 Normally, GNAT allows only a single unit in a source file. However, this
4869 restriction does not apply in syntax-check-only mode, and it is possible
4870 to check a file containing multiple compilation units concatenated
4871 together. This is primarily used by the @code{gnatchop} utility
4872 (@pxref{Renaming Files Using gnatchop}).
4873 @end table
4875 @node Using gcc for Semantic Checking
4876 @subsection Using @code{gcc} for Semantic Checking
4877 @table @code
4878 @item -gnatc
4879 @cindex @option{-gnatc} (@code{gcc})
4881 @ifclear vms
4882 @noindent
4883 The @code{c} stands for check.
4884 @end ifclear
4885 Causes the compiler to operate in semantic check mode,
4886 with full checking for all illegalities specified in the
4887 Ada 95 Reference Manual, but without generation of any object code
4888 (no object file is generated).
4890 Because dependent files must be accessed, you must follow the GNAT
4891 semantic restrictions on file structuring to operate in this mode:
4893 @itemize @bullet
4894 @item
4895 The needed source files must be accessible
4896 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4898 @item
4899 Each file must contain only one compilation unit.
4901 @item
4902 The file name and unit name must match (@pxref{File Naming Rules}).
4903 @end itemize
4905 The output consists of error messages as appropriate. No object file is
4906 generated. An @file{ALI} file is generated for use in the context of
4907 cross-reference tools, but this file is marked as not being suitable
4908 for binding (since no object file is generated).
4909 The checking corresponds exactly to the notion of
4910 legality in the Ada 95 Reference Manual.
4912 Any unit can be compiled in semantics-checking-only mode, including
4913 units that would not normally be compiled (subunits,
4914 and specifications where a separate body is present).
4915 @end table
4917 @node Compiling Ada 83 Programs
4918 @subsection Compiling Ada 83 Programs
4919 @table @code
4920 @cindex Ada 83 compatibility
4921 @item -gnat83
4922 @cindex @option{-gnat83} (@code{gcc})
4923 @cindex ACVC, Ada 83 tests
4925 @noindent
4926 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
4927 specify that an Ada 83 program is to be compiled in Ada83 mode. If you specify
4928 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
4929 where this can be done easily.
4930 It is not possible to guarantee this switch does a perfect
4931 job; for example, some subtle tests, such as are
4932 found in earlier ACVC tests (that have been removed from the ACVC suite for Ada
4933 95), may not compile correctly. However, for most purposes, using
4934 this switch should help to ensure that programs that compile correctly
4935 under the @option{-gnat83} switch can be ported easily to an Ada 83
4936 compiler. This is the main use of the switch.
4938 With few exceptions (most notably the need to use @code{<>} on
4939 @cindex Generic formal parameters
4940 unconstrained generic formal parameters, the use of the new Ada 95
4941 keywords, and the use of packages
4942 with optional bodies), it is not necessary to use the
4943 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
4944 exceptions, Ada 95 is upwardly compatible with Ada 83. This
4945 means that a correct Ada 83 program is usually also a correct Ada 95
4946 program.
4948 @end table
4950 @node Character Set Control
4951 @subsection Character Set Control
4952 @table @code
4953 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4954 @cindex @code{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
4956 @noindent
4957 Normally GNAT recognizes the Latin-1 character set in source program
4958 identifiers, as described in the Ada 95 Reference Manual.
4959 This switch causes
4960 GNAT to recognize alternate character sets in identifiers. @var{c} is a
4961 single character ^^or word^ indicating the character set, as follows:
4963 @table @code
4964 @item 1
4965 Latin-1 identifiers
4967 @item 2
4968 Latin-2 letters allowed in identifiers
4970 @item 3
4971 Latin-3 letters allowed in identifiers
4973 @item 4
4974 Latin-4 letters allowed in identifiers
4976 @item 5
4977 Latin-5 (Cyrillic) letters allowed in identifiers
4979 @item 9
4980 Latin-9 letters allowed in identifiers
4982 @item ^p^PC^
4983 IBM PC letters (code page 437) allowed in identifiers
4985 @item ^8^PC850^
4986 IBM PC letters (code page 850) allowed in identifiers
4988 @item ^f^FULL_UPPER^
4989 Full upper-half codes allowed in identifiers
4991 @item ^n^NO_UPPER^
4992 No upper-half codes allowed in identifiers
4994 @item ^w^WIDE^
4995 Wide-character codes (that is, codes greater than 255)
4996 allowed in identifiers
4997 @end table
4999 @xref{Foreign Language Representation}, for full details on the
5000 implementation of these character sets.
5002 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
5003 @cindex @code{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
5004 Specify the method of encoding for wide characters.
5005 @var{e} is one of the following:
5007 @table @code
5009 @item ^h^HEX^
5010 Hex encoding (brackets coding also recognized)
5012 @item ^u^UPPER^
5013 Upper half encoding (brackets encoding also recognized)
5015 @item ^s^SHIFT_JIS^
5016 Shift/JIS encoding (brackets encoding also recognized)
5018 @item ^e^EUC^
5019 EUC encoding (brackets encoding also recognized)
5021 @item ^8^UTF8^
5022 UTF-8 encoding (brackets encoding also recognized)
5024 @item ^b^BRACKETS^
5025 Brackets encoding only (default value)
5026 @end table
5027 For full details on the these encoding
5028 methods see @xref{Wide Character Encodings}.
5029 Note that brackets coding is always accepted, even if one of the other
5030 options is specified, so for example @option{-gnatW8} specifies that both
5031 brackets and @code{UTF-8} encodings will be recognized. The units that are
5032 with'ed directly or indirectly will be scanned using the specified
5033 representation scheme, and so if one of the non-brackets scheme is
5034 used, it must be used consistently throughout the program. However,
5035 since brackets encoding is always recognized, it may be conveniently
5036 used in standard libraries, allowing these libraries to be used with
5037 any of the available coding schemes.
5038 scheme. If no @option{-gnatW?} parameter is present, then the default
5039 representation is Brackets encoding only.
5041 Note that the wide character representation that is specified (explicitly
5042 or by default) for the main program also acts as the default encoding used
5043 for Wide_Text_IO files if not specifically overridden by a WCEM form
5044 parameter.
5046 @end table
5047 @node File Naming Control
5048 @subsection File Naming Control
5050 @table @code
5051 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
5052 @cindex @option{-gnatk} (@code{gcc})
5053 Activates file name "krunching". @var{n}, a decimal integer in the range
5054 1-999, indicates the maximum allowable length of a file name (not
5055 including the @file{.ads} or @file{.adb} extension). The default is not
5056 to enable file name krunching.
5058 For the source file naming rules, @xref{File Naming Rules}.
5059 @end table
5061 @node Subprogram Inlining Control
5062 @subsection Subprogram Inlining Control
5064 @table @code
5065 @item -gnatn
5066 @cindex @option{-gnatn} (@code{gcc})
5067 @ifclear vms
5068 The @code{n} here is intended to suggest the first syllable of the
5069 word "inline".
5070 @end ifclear
5071 GNAT recognizes and processes @code{Inline} pragmas. However, for the
5072 inlining to actually occur, optimization must be enabled. To enable
5073 inlining across unit boundaries, this is, inlining a call in one unit of
5074 a subprogram declared in a @code{with}'ed unit, you must also specify
5075 this switch.
5076 In the absence of this switch, GNAT does not attempt
5077 inlining across units and does not need to access the bodies of
5078 subprograms for which @code{pragma Inline} is specified if they are not
5079 in the current unit.
5081 If you specify this switch the compiler will access these bodies,
5082 creating an extra source dependency for the resulting object file, and
5083 where possible, the call will be inlined.
5084 For further details on when inlining is possible
5085 see @xref{Inlining of Subprograms}.
5087 @item -gnatN
5088 @cindex @option{-gnatN} (@code{gcc})
5089 The front end inlining activated by this switch is generally more extensive,
5090 and quite often more effective than the standard @option{-gnatn} inlining mode.
5091 It will also generate additional dependencies.
5093 @end table
5095 @node Auxiliary Output Control
5096 @subsection Auxiliary Output Control
5098 @table @code
5099 @item -gnatt
5100 @cindex @option{-gnatt} (@code{gcc})
5101 @cindex Writing internal trees
5102 @cindex Internal trees, writing to file
5103 Causes GNAT to write the internal tree for a unit to a file (with the
5104 extension @file{.adt}.
5105 This not normally required, but is used by separate analysis tools.
5106 Typically
5107 these tools do the necessary compilations automatically, so you should
5108 not have to specify this switch in normal operation.
5110 @item -gnatu
5111 @cindex @option{-gnatu} (@code{gcc})
5112 Print a list of units required by this compilation on @file{stdout}.
5113 The listing includes all units on which the unit being compiled depends
5114 either directly or indirectly.
5116 @ifclear vms
5117 @item -pass-exit-codes
5118 @cindex @code{-pass-exit-codes} (@code{gcc})
5119 If this switch is not used, the exit code returned by @code{gcc} when
5120 compiling multiple files indicates whether all source files have
5121 been successfully used to generate object files or not.
5123 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
5124 exit status and allows an integrated development environment to better
5125 react to a compilation failure. Those exit status are:
5127 @table @asis
5128 @item 5
5129 There was an error in at least one source file.
5130 @item 3
5131 At least one source file did not generate an object file.
5132 @item 2
5133 The compiler died unexpectedly (internal error for example).
5134 @item 0
5135 An object file has been generated for every source file.
5136 @end table
5137 @end ifclear
5138 @end table
5140 @node Debugging Control
5141 @subsection Debugging Control
5143 @table @code
5144 @cindex Debugging options
5145 @ifclear vms
5146 @item -gnatd@var{x}
5147 Activate internal debugging switches. @var{x} is a letter or digit, or
5148 string of letters or digits, which specifies the type of debugging
5149 outputs desired. Normally these are used only for internal development
5150 or system debugging purposes. You can find full documentation for these
5151 switches in the body of the @code{Debug} unit in the compiler source
5152 file @file{debug.adb}.
5153 @end ifclear
5155 @item -gnatG
5156 @cindex @option{-gnatG} (@code{gcc})
5157 This switch causes the compiler to generate auxiliary output containing
5158 a pseudo-source listing of the generated expanded code. Like most Ada
5159 compilers, GNAT works by first transforming the high level Ada code into
5160 lower level constructs. For example, tasking operations are transformed
5161 into calls to the tasking run-time routines. A unique capability of GNAT
5162 is to list this expanded code in a form very close to normal Ada source.
5163 This is very useful in understanding the implications of various Ada
5164 usage on the efficiency of the generated code. There are many cases in
5165 Ada (e.g. the use of controlled types), where simple Ada statements can
5166 generate a lot of run-time code. By using @option{-gnatG} you can identify
5167 these cases, and consider whether it may be desirable to modify the coding
5168 approach to improve efficiency.
5170 The format of the output is very similar to standard Ada source, and is
5171 easily understood by an Ada programmer. The following special syntactic
5172 additions correspond to low level features used in the generated code that
5173 do not have any exact analogies in pure Ada source form. The following
5174 is a partial list of these special constructions. See the specification
5175 of package @code{Sprint} in file @file{sprint.ads} for a full list.
5177 @table @code
5178 @item new @var{xxx} [storage_pool = @var{yyy}]
5179 Shows the storage pool being used for an allocator.
5181 @item at end @var{procedure-name};
5182 Shows the finalization (cleanup) procedure for a scope.
5184 @item (if @var{expr} then @var{expr} else @var{expr})
5185 Conditional expression equivalent to the @code{x?y:z} construction in C.
5187 @item @var{target}^^^(@var{source})
5188 A conversion with floating-point truncation instead of rounding.
5190 @item @var{target}?(@var{source})
5191 A conversion that bypasses normal Ada semantic checking. In particular
5192 enumeration types and fixed-point types are treated simply as integers.
5194 @item @var{target}?^^^(@var{source})
5195 Combines the above two cases.
5197 @item @var{x} #/ @var{y}
5198 @itemx @var{x} #mod @var{y}
5199 @itemx @var{x} #* @var{y}
5200 @itemx @var{x} #rem @var{y}
5201 A division or multiplication of fixed-point values which are treated as
5202 integers without any kind of scaling.
5204 @item free @var{expr} [storage_pool = @var{xxx}]
5205 Shows the storage pool associated with a @code{free} statement.
5207 @item freeze @var{typename} [@var{actions}]
5208 Shows the point at which @var{typename} is frozen, with possible
5209 associated actions to be performed at the freeze point.
5211 @item reference @var{itype}
5212 Reference (and hence definition) to internal type @var{itype}.
5214 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
5215 Intrinsic function call.
5217 @item @var{labelname} : label
5218 Declaration of label @var{labelname}.
5220 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
5221 A multiple concatenation (same effect as @var{expr} & @var{expr} &
5222 @var{expr}, but handled more efficiently).
5224 @item [constraint_error]
5225 Raise the @code{Constraint_Error} exception.
5227 @item @var{expression}'reference
5228 A pointer to the result of evaluating @var{expression}.
5230 @item @var{target-type}!(@var{source-expression})
5231 An unchecked conversion of @var{source-expression} to @var{target-type}.
5233 @item [@var{numerator}/@var{denominator}]
5234 Used to represent internal real literals (that) have no exact
5235 representation in base 2-16 (for example, the result of compile time
5236 evaluation of the expression 1.0/27.0).
5238 @item -gnatD
5239 @cindex @option{-gnatD} (@code{gcc})
5240 This switch is used in conjunction with @option{-gnatG} to cause the expanded
5241 source, as described above to be written to files with names
5242 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
5243 for example, if the source file name is @file{hello.adb},
5244 then a file @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.
5245 The debugging information generated
5246 by the @code{gcc} @code{^-g^/DEBUG^} switch will refer to the generated
5247 @file{^xxx.dg^XXX_DG^} file. This allows you to do source level debugging using
5248 the generated code which is sometimes useful for complex code, for example
5249 to find out exactly which part of a complex construction raised an
5250 exception. This switch also suppress generation of cross-reference
5251 information (see -gnatx).
5253 @item -gnatC
5254 @cindex @option{-gnatE} (@code{gcc})
5255 In the generated debugging information, and also in the case of long external
5256 names, the compiler uses a compression mechanism if the name is very long.
5257 This compression method uses a checksum, and avoids trouble on some operating
5258 systems which have difficulty with very long names. The @option{-gnatC} switch
5259 forces this compression approach to be used on all external names and names
5260 in the debugging information tables. This reduces the size of the generated
5261 executable, at the expense of making the naming scheme more complex. The
5262 compression only affects the qualification of the name. Thus a name in
5263 the source:
5265 @smallexample
5266 Very_Long_Package.Very_Long_Inner_Package.Var
5267 @end smallexample
5269 @noindent
5270 would normally appear in these tables as:
5272 @smallexample
5273 very_long_package__very_long_inner_package__var
5274 @end smallexample
5276 @noindent
5277 but if the @option{-gnatC} switch is used, then the name appears as
5279 @smallexample
5280 XCb7e0c705__var
5281 @end smallexample
5283 @noindent
5284 Here b7e0c705 is a compressed encoding of the qualification prefix.
5285 The GNAT Ada aware version of GDB understands these encoded prefixes, so if this
5286 debugger is used, the encoding is largely hidden from the user of the compiler.
5288 @end table
5290 @item -gnatR[0|1|2|3][s]
5291 @cindex @option{-gnatR} (@code{gcc})
5292 This switch controls output from the compiler of a listing showing
5293 representation information for declared types and objects. For
5294 @option{-gnatR0}, no information is output (equivalent to omitting
5295 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
5296 so @option{-gnatR} with no parameter has the same effect), size and alignment
5297 information is listed for declared array and record types. For
5298 @option{-gnatR2}, size and alignment information is listed for all
5299 expression information for values that are computed at run time for
5300 variant records. These symbolic expressions have a mostly obvious
5301 format with #n being used to represent the value of the n'th
5302 discriminant. See source files @file{repinfo.ads/adb} in the
5303 @code{GNAT} sources for full detalis on the format of @option{-gnatR3}
5304 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
5305 the output is to a file with the name @file{^file.rep^file_REP^} where
5306 file is the name of the corresponding source file.
5308 @item -gnatx
5309 @cindex @option{-gnatx} (@code{gcc})
5310 Normally the compiler generates full cross-referencing information in
5311 the @file{ALI} file. This information is used by a number of tools,
5312 including @code{gnatfind} and @code{gnatxref}. The -gnatx switch
5313 suppresses this information. This saves some space and may slightly
5314 speed up compilation, but means that these tools cannot be used.
5315 @end table
5317 @node Units to Sources Mapping Files
5318 @subsection Units to Sources Mapping Files
5320 @table @code
5322 @item -gnatem@var{path}
5323 @cindex @option{-gnatem} (@code{gcc})
5324 A mapping file is a way to communicate to the compiler two mappings:
5325 from unit names to file names (without any directory information) and from
5326 file names to path names (with full directory information). These mappings
5327 are used by the compiler to short-circuit the path search.
5329 A mapping file is a sequence of sets of three lines. In each set,
5330 the first line is the unit name, in lower case, with "%s" appended for
5331 specifications and "%b" appended for bodies; the second line is the file
5332 name; and the third line is the path name.
5334 Example:
5335 @smallexample
5336    main%b
5337    main.2.ada
5338    /gnat/project1/sources/main.2.ada
5339 @end smallexample
5341 When the switch @option{-gnatem} is specified, the compiler will create
5342 in memory the two mappings from the specified file. If there is any problem
5343 (non existent file, truncated file or duplicate entries), no mapping
5344 will be created.
5346 Several @option{-gnatem} switches may be specified; however, only the last
5347 one on the command line will be taken into account.
5349 When using a project file, @code{gnatmake} create a temporary mapping file
5350 and communicates it to the compiler using this switch.
5352 @end table
5354 @node Search Paths and the Run-Time Library (RTL)
5355 @section Search Paths and the Run-Time Library (RTL)
5357 @noindent
5358 With the GNAT source-based library system, the compiler must be able to
5359 find source files for units that are needed by the unit being compiled.
5360 Search paths are used to guide this process.
5362 The compiler compiles one source file whose name must be given
5363 explicitly on the command line. In other words, no searching is done
5364 for this file. To find all other source files that are needed (the most
5365 common being the specs of units), the compiler examines the following
5366 directories, in the following order:
5368 @enumerate
5369 @item
5370 The directory containing the source file of the main unit being compiled
5371 (the file name on the command line).
5373 @item
5374 Each directory named by an @code{^-I^/SOURCE_SEARCH^} switch given on the @code{gcc}
5375 command line, in the order given.
5377 @item
5378 @findex ADA_INCLUDE_PATH
5379 Each of the directories listed in the value of the
5380 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
5381 @ifclear vms
5382 Construct this value
5383 exactly as the @code{PATH} environment variable: a list of directory
5384 names separated by colons (semicolons when working with the NT version).
5385 @end ifclear
5386 @ifset vms
5387 Normally, define this value as a logical name containing a comma separated
5388 list of directory names.
5390 This variable can also be defined by means of an environment string
5391 (an argument to the DEC C exec* set of functions).
5393 Logical Name:
5394 @smallexample
5395 DEFINE ANOTHER_PATH FOO:[BAG]
5396 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
5397 @end smallexample
5399 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
5400 first, followed by the standard Ada 95
5401 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
5402 If this is not redefined, the user will obtain the DEC Ada83 IO packages
5403 (Text_IO, Sequential_IO, etc)
5404 instead of the Ada95 packages. Thus, in order to get the Ada 95
5405 packages by default, ADA_INCLUDE_PATH must be redefined.
5406 @end ifset
5407 @item
5408 The content of the "ada_source_path" file which is part of the GNAT
5409 installation tree and is used to store standard libraries such as the
5410 GNAT Run Time Library (RTL) source files.
5411 @ifclear vms
5412 @ref{Installing an Ada Library}
5413 @end ifclear
5414 @end enumerate
5416 @noindent
5417 Specifying the switch @code{^-I-^/NOCURRENT_DIRECTORY^}
5418 inhibits the use of the directory
5419 containing the source file named in the command line. You can still
5420 have this directory on your search path, but in this case it must be
5421 explicitly requested with a @code{^-I^/SOURCE_SEARCH^} switch.
5423 Specifying the switch @code{-nostdinc}
5424 inhibits the search of the default location for the GNAT Run Time
5425 Library (RTL) source files.
5427 The compiler outputs its object files and ALI files in the current
5428 working directory.
5429 @ifclear vms
5430 Caution: The object file can be redirected with the @code{-o} switch;
5431 however, @code{gcc} and @code{gnat1} have not been coordinated on this
5432 so the ALI file will not go to the right place. Therefore, you should
5433 avoid using the @code{-o} switch.
5434 @end ifclear
5436 @findex System.IO
5437 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
5438 children make up the GNAT RTL, together with the simple @code{System.IO}
5439 package used in the "Hello World" example. The sources for these units
5440 are needed by the compiler and are kept together in one directory. Not
5441 all of the bodies are needed, but all of the sources are kept together
5442 anyway. In a normal installation, you need not specify these directory
5443 names when compiling or binding. Either the environment variables or
5444 the built-in defaults cause these files to be found.
5446 In addition to the language-defined hierarchies (System, Ada and
5447 Interfaces), the GNAT distribution provides a fourth hierarchy,
5448 consisting of child units of GNAT. This is a collection of generally
5449 useful routines. See the GNAT Reference Manual for further details.
5451 Besides simplifying access to the RTL, a major use of search paths is
5452 in compiling sources from multiple directories. This can make
5453 development environments much more flexible.
5455 @node Order of Compilation Issues
5456 @section Order of Compilation Issues
5458 @noindent
5459 If, in our earlier example, there was a spec for the @code{hello}
5460 procedure, it would be contained in the file @file{hello.ads}; yet this
5461 file would not have to be explicitly compiled. This is the result of the
5462 model we chose to implement library management. Some of the consequences
5463 of this model are as follows:
5465 @itemize @bullet
5466 @item
5467 There is no point in compiling specs (except for package
5468 specs with no bodies) because these are compiled as needed by clients. If
5469 you attempt a useless compilation, you will receive an error message.
5470 It is also useless to compile subunits because they are compiled as needed
5471 by the parent.
5473 @item
5474 There are no order of compilation requirements: performing a
5475 compilation never obsoletes anything. The only way you can obsolete
5476 something and require recompilations is to modify one of the
5477 source files on which it depends.
5479 @item
5480 There is no library as such, apart from the ALI files
5481 (@pxref{The Ada Library Information Files}, for information on the format of these
5482 files). For now we find it convenient to create separate ALI files, but
5483 eventually the information therein may be incorporated into the object
5484 file directly.
5486 @item
5487 When you compile a unit, the source files for the specs of all units
5488 that it @code{with}'s, all its subunits, and the bodies of any generics it
5489 instantiates must be available (reachable by the search-paths mechanism
5490 described above), or you will receive a fatal error message.
5491 @end itemize
5493 @node Examples
5494 @section Examples
5496 @noindent
5497 The following are some typical Ada compilation command line examples:
5499 @table @code
5500 @item $ gcc -c xyz.adb
5501 Compile body in file @file{xyz.adb} with all default options.
5503 @ifclear vms
5504 @item $ gcc -c -O2 -gnata xyz-def.adb
5505 @end ifclear
5506 @ifset vms
5507 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
5508 @end ifset
5510 Compile the child unit package in file @file{xyz-def.adb} with extensive
5511 optimizations, and pragma @code{Assert}/@code{Debug} statements
5512 enabled.
5514 @item $ gcc -c -gnatc abc-def.adb
5515 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
5516 mode.
5517 @end table
5519 @node Binding Using gnatbind
5520 @chapter Binding Using @code{gnatbind}
5521 @findex gnatbind
5523 @menu
5524 * Running gnatbind::
5525 * Generating the Binder Program in C::
5526 * Consistency-Checking Modes::
5527 * Binder Error Message Control::
5528 * Elaboration Control::
5529 * Output Control::
5530 * Binding with Non-Ada Main Programs::
5531 * Binding Programs with No Main Subprogram::
5532 * Summary of Binder Switches::
5533 * Command-Line Access::
5534 * Search Paths for gnatbind::
5535 * Examples of gnatbind Usage::
5536 @end menu
5538 @noindent
5539 This chapter describes the GNAT binder, @code{gnatbind}, which is used
5540 to bind compiled GNAT objects. The @code{gnatbind} program performs
5541 four separate functions:
5543 @enumerate
5544 @item
5545 Checks that a program is consistent, in accordance with the rules in
5546 Chapter 10 of the Ada 95 Reference Manual. In particular, error
5547 messages are generated if a program uses inconsistent versions of a
5548 given unit.
5550 @item
5551 Checks that an acceptable order of elaboration exists for the program
5552 and issues an error message if it cannot find an order of elaboration
5553 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
5555 @item
5556 Generates a main program incorporating the given elaboration order.
5557 This program is a small Ada package (body and spec) that
5558 must be subsequently compiled
5559 using the GNAT compiler. The necessary compilation step is usually
5560 performed automatically by @code{gnatlink}. The two most important
5561 functions of this program
5562 are to call the elaboration routines of units in an appropriate order
5563 and to call the main program.
5565 @item
5566 Determines the set of object files required by the given main program.
5567 This information is output in the forms of comments in the generated program,
5568 to be read by the @code{gnatlink} utility used to link the Ada application.
5569 @end enumerate
5571 @node Running gnatbind
5572 @section Running @code{gnatbind}
5574 @noindent
5575 The form of the @code{gnatbind} command is
5577 @smallexample
5578 $ gnatbind [@var{switches}] @var{mainprog}[.ali] [@var{switches}]
5579 @end smallexample
5581 @noindent
5582 where @var{mainprog}.adb is the Ada file containing the main program
5583 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
5584 package in two files which names are
5585 @file{b~@var{ada_main}.ads}, and @file{b~@var{ada_main}.adb}.
5586 For example, if given the
5587 parameter @samp{hello.ali}, for a main program contained in file
5588 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
5589 and @file{b~hello.adb}.
5591 When doing consistency checking, the binder takes into consideration
5592 any source files it can locate. For example, if the binder determines
5593 that the given main program requires the package @code{Pack}, whose
5594 @file{.ali}
5595 file is @file{pack.ali} and whose corresponding source spec file is
5596 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
5597 (using the same search path conventions as previously described for the
5598 @code{gcc} command). If it can locate this source file, it checks that
5599 the time stamps
5600 or source checksums of the source and its references to in @file{ali} files
5601 match. In other words, any @file{ali} files that mentions this spec must have
5602 resulted from compiling this version of the source file (or in the case
5603 where the source checksums match, a version close enough that the
5604 difference does not matter).
5606 @cindex Source files, use by binder
5607 The effect of this consistency checking, which includes source files, is
5608 that the binder ensures that the program is consistent with the latest
5609 version of the source files that can be located at bind time. Editing a
5610 source file without compiling files that depend on the source file cause
5611 error messages to be generated by the binder.
5613 For example, suppose you have a main program @file{hello.adb} and a
5614 package @code{P}, from file @file{p.ads} and you perform the following
5615 steps:
5617 @enumerate
5618 @item
5619 Enter @code{gcc -c hello.adb} to compile the main program.
5621 @item
5622 Enter @code{gcc -c p.ads} to compile package @code{P}.
5624 @item
5625 Edit file @file{p.ads}.
5627 @item
5628 Enter @code{gnatbind hello}.
5629 @end enumerate
5631 At this point, the file @file{p.ali} contains an out-of-date time stamp
5632 because the file @file{p.ads} has been edited. The attempt at binding
5633 fails, and the binder generates the following error messages:
5635 @smallexample
5636 error: "hello.adb" must be recompiled ("p.ads" has been modified)
5637 error: "p.ads" has been modified and must be recompiled
5638 @end smallexample
5640 @noindent
5641 Now both files must be recompiled as indicated, and then the bind can
5642 succeed, generating a main program. You need not normally be concerned
5643 with the contents of this file, but it is similar to the following which
5644 is the binder file generated for a simple "hello world" program.
5646 @smallexample
5647 @iftex
5648 @leftskip=0cm
5649 @end iftex
5650 --  The package is called Ada_Main unless this name is actually used
5651 --  as a unit name in the partition, in which case some other unique
5652 --  name is used.
5654 with System;
5655 package ada_main is
5657    Elab_Final_Code : Integer;
5658    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
5660    --  The main program saves the parameters (argument count,
5661    --  argument values, environment pointer) in global variables
5662    --  for later access by other units including
5663    --  Ada.Command_Line.
5665    gnat_argc : Integer;
5666    gnat_argv : System.Address;
5667    gnat_envp : System.Address;
5669    --  The actual variables are stored in a library routine. This
5670    --  is useful for some shared library situations, where there
5671    --  are problems if variables are not in the library.
5673    pragma Import (C, gnat_argc);
5674    pragma Import (C, gnat_argv);
5675    pragma Import (C, gnat_envp);
5677    --  The exit status is similarly an external location
5679    gnat_exit_status : Integer;
5680    pragma Import (C, gnat_exit_status);
5682    GNAT_Version : constant String :=
5683                     "GNAT Version: 3.15w (20010315)";
5684    pragma Export (C, GNAT_Version, "__gnat_version");
5686    --  This is the generated adafinal routine that performs
5687    --  finalization at the end of execution. In the case where
5688    --  Ada is the main program, this main program makes a call
5689    --  to adafinal at program termination.
5691    procedure adafinal;
5692    pragma Export (C, adafinal, "adafinal");
5694    --  This is the generated adainit routine that performs
5695    --  initialization at the start of execution. In the case
5696    --  where Ada is the main program, this main program makes
5697    --  a call to adainit at program startup.
5699    procedure adainit;
5700    pragma Export (C, adainit, "adainit");
5702    --  This routine is called at the start of execution. It is
5703    --  a dummy routine that is used by the debugger to breakpoint
5704    --  at the start of execution.
5706    procedure Break_Start;
5707    pragma Import (C, Break_Start, "__gnat_break_start");
5709    --  This is the actual generated main program (it would be
5710    --  suppressed if the no main program switch were used). As
5711    --  required by standard system conventions, this program has
5712    --  the external name main.
5714    function main
5715      (argc : Integer;
5716       argv : System.Address;
5717       envp : System.Address)
5718       return Integer;
5719    pragma Export (C, main, "main");
5721    --  The following set of constants give the version
5722    --  identification values for every unit in the bound
5723    --  partition. This identification is computed from all
5724    --  dependent semantic units, and corresponds to the
5725    --  string that would be returned by use of the
5726    --  Body_Version or Version attributes.
5728    type Version_32 is mod 2 ** 32;
5729    u00001 : constant Version_32 := 16#7880BEB3#;
5730    u00002 : constant Version_32 := 16#0D24CBD0#;
5731    u00003 : constant Version_32 := 16#3283DBEB#;
5732    u00004 : constant Version_32 := 16#2359F9ED#;
5733    u00005 : constant Version_32 := 16#664FB847#;
5734    u00006 : constant Version_32 := 16#68E803DF#;
5735    u00007 : constant Version_32 := 16#5572E604#;
5736    u00008 : constant Version_32 := 16#46B173D8#;
5737    u00009 : constant Version_32 := 16#156A40CF#;
5738    u00010 : constant Version_32 := 16#033DABE0#;
5739    u00011 : constant Version_32 := 16#6AB38FEA#;
5740    u00012 : constant Version_32 := 16#22B6217D#;
5741    u00013 : constant Version_32 := 16#68A22947#;
5742    u00014 : constant Version_32 := 16#18CC4A56#;
5743    u00015 : constant Version_32 := 16#08258E1B#;
5744    u00016 : constant Version_32 := 16#367D5222#;
5745    u00017 : constant Version_32 := 16#20C9ECA4#;
5746    u00018 : constant Version_32 := 16#50D32CB6#;
5747    u00019 : constant Version_32 := 16#39A8BB77#;
5748    u00020 : constant Version_32 := 16#5CF8FA2B#;
5749    u00021 : constant Version_32 := 16#2F1EB794#;
5750    u00022 : constant Version_32 := 16#31AB6444#;
5751    u00023 : constant Version_32 := 16#1574B6E9#;
5752    u00024 : constant Version_32 := 16#5109C189#;
5753    u00025 : constant Version_32 := 16#56D770CD#;
5754    u00026 : constant Version_32 := 16#02F9DE3D#;
5755    u00027 : constant Version_32 := 16#08AB6B2C#;
5756    u00028 : constant Version_32 := 16#3FA37670#;
5757    u00029 : constant Version_32 := 16#476457A0#;
5758    u00030 : constant Version_32 := 16#731E1B6E#;
5759    u00031 : constant Version_32 := 16#23C2E789#;
5760    u00032 : constant Version_32 := 16#0F1BD6A1#;
5761    u00033 : constant Version_32 := 16#7C25DE96#;
5762    u00034 : constant Version_32 := 16#39ADFFA2#;
5763    u00035 : constant Version_32 := 16#571DE3E7#;
5764    u00036 : constant Version_32 := 16#5EB646AB#;
5765    u00037 : constant Version_32 := 16#4249379B#;
5766    u00038 : constant Version_32 := 16#0357E00A#;
5767    u00039 : constant Version_32 := 16#3784FB72#;
5768    u00040 : constant Version_32 := 16#2E723019#;
5769    u00041 : constant Version_32 := 16#623358EA#;
5770    u00042 : constant Version_32 := 16#107F9465#;
5771    u00043 : constant Version_32 := 16#6843F68A#;
5772    u00044 : constant Version_32 := 16#63305874#;
5773    u00045 : constant Version_32 := 16#31E56CE1#;
5774    u00046 : constant Version_32 := 16#02917970#;
5775    u00047 : constant Version_32 := 16#6CCBA70E#;
5776    u00048 : constant Version_32 := 16#41CD4204#;
5777    u00049 : constant Version_32 := 16#572E3F58#;
5778    u00050 : constant Version_32 := 16#20729FF5#;
5779    u00051 : constant Version_32 := 16#1D4F93E8#;
5780    u00052 : constant Version_32 := 16#30B2EC3D#;
5781    u00053 : constant Version_32 := 16#34054F96#;
5782    u00054 : constant Version_32 := 16#5A199860#;
5783    u00055 : constant Version_32 := 16#0E7F912B#;
5784    u00056 : constant Version_32 := 16#5760634A#;
5785    u00057 : constant Version_32 := 16#5D851835#;
5787    --  The following Export pragmas export the version numbers
5788    --  with symbolic names ending in B (for body) or S
5789    --  (for spec) so that they can be located in a link. The
5790    --  information provided here is sufficient to track down
5791    --  the exact versions of units used in a given build.
5793    pragma Export (C, u00001, "helloB");
5794    pragma Export (C, u00002, "system__standard_libraryB");
5795    pragma Export (C, u00003, "system__standard_libraryS");
5796    pragma Export (C, u00004, "adaS");
5797    pragma Export (C, u00005, "ada__text_ioB");
5798    pragma Export (C, u00006, "ada__text_ioS");
5799    pragma Export (C, u00007, "ada__exceptionsB");
5800    pragma Export (C, u00008, "ada__exceptionsS");
5801    pragma Export (C, u00009, "gnatS");
5802    pragma Export (C, u00010, "gnat__heap_sort_aB");
5803    pragma Export (C, u00011, "gnat__heap_sort_aS");
5804    pragma Export (C, u00012, "systemS");
5805    pragma Export (C, u00013, "system__exception_tableB");
5806    pragma Export (C, u00014, "system__exception_tableS");
5807    pragma Export (C, u00015, "gnat__htableB");
5808    pragma Export (C, u00016, "gnat__htableS");
5809    pragma Export (C, u00017, "system__exceptionsS");
5810    pragma Export (C, u00018, "system__machine_state_operationsB");
5811    pragma Export (C, u00019, "system__machine_state_operationsS");
5812    pragma Export (C, u00020, "system__machine_codeS");
5813    pragma Export (C, u00021, "system__storage_elementsB");
5814    pragma Export (C, u00022, "system__storage_elementsS");
5815    pragma Export (C, u00023, "system__secondary_stackB");
5816    pragma Export (C, u00024, "system__secondary_stackS");
5817    pragma Export (C, u00025, "system__parametersB");
5818    pragma Export (C, u00026, "system__parametersS");
5819    pragma Export (C, u00027, "system__soft_linksB");
5820    pragma Export (C, u00028, "system__soft_linksS");
5821    pragma Export (C, u00029, "system__stack_checkingB");
5822    pragma Export (C, u00030, "system__stack_checkingS");
5823    pragma Export (C, u00031, "system__tracebackB");
5824    pragma Export (C, u00032, "system__tracebackS");
5825    pragma Export (C, u00033, "ada__streamsS");
5826    pragma Export (C, u00034, "ada__tagsB");
5827    pragma Export (C, u00035, "ada__tagsS");
5828    pragma Export (C, u00036, "system__string_opsB");
5829    pragma Export (C, u00037, "system__string_opsS");
5830    pragma Export (C, u00038, "interfacesS");
5831    pragma Export (C, u00039, "interfaces__c_streamsB");
5832    pragma Export (C, u00040, "interfaces__c_streamsS");
5833    pragma Export (C, u00041, "system__file_ioB");
5834    pragma Export (C, u00042, "system__file_ioS");
5835    pragma Export (C, u00043, "ada__finalizationB");
5836    pragma Export (C, u00044, "ada__finalizationS");
5837    pragma Export (C, u00045, "system__finalization_rootB");
5838    pragma Export (C, u00046, "system__finalization_rootS");
5839    pragma Export (C, u00047, "system__finalization_implementationB");
5840    pragma Export (C, u00048, "system__finalization_implementationS");
5841    pragma Export (C, u00049, "system__string_ops_concat_3B");
5842    pragma Export (C, u00050, "system__string_ops_concat_3S");
5843    pragma Export (C, u00051, "system__stream_attributesB");
5844    pragma Export (C, u00052, "system__stream_attributesS");
5845    pragma Export (C, u00053, "ada__io_exceptionsS");
5846    pragma Export (C, u00054, "system__unsigned_typesS");
5847    pragma Export (C, u00055, "system__file_control_blockS");
5848    pragma Export (C, u00056, "ada__finalization__list_controllerB");
5849    pragma Export (C, u00057, "ada__finalization__list_controllerS");
5851    -- BEGIN ELABORATION ORDER
5852    -- ada (spec)
5853    -- gnat (spec)
5854    -- gnat.heap_sort_a (spec)
5855    -- gnat.heap_sort_a (body)
5856    -- gnat.htable (spec)
5857    -- gnat.htable (body)
5858    -- interfaces (spec)
5859    -- system (spec)
5860    -- system.machine_code (spec)
5861    -- system.parameters (spec)
5862    -- system.parameters (body)
5863    -- interfaces.c_streams (spec)
5864    -- interfaces.c_streams (body)
5865    -- system.standard_library (spec)
5866    -- ada.exceptions (spec)
5867    -- system.exception_table (spec)
5868    -- system.exception_table (body)
5869    -- ada.io_exceptions (spec)
5870    -- system.exceptions (spec)
5871    -- system.storage_elements (spec)
5872    -- system.storage_elements (body)
5873    -- system.machine_state_operations (spec)
5874    -- system.machine_state_operations (body)
5875    -- system.secondary_stack (spec)
5876    -- system.stack_checking (spec)
5877    -- system.soft_links (spec)
5878    -- system.soft_links (body)
5879    -- system.stack_checking (body)
5880    -- system.secondary_stack (body)
5881    -- system.standard_library (body)
5882    -- system.string_ops (spec)
5883    -- system.string_ops (body)
5884    -- ada.tags (spec)
5885    -- ada.tags (body)
5886    -- ada.streams (spec)
5887    -- system.finalization_root (spec)
5888    -- system.finalization_root (body)
5889    -- system.string_ops_concat_3 (spec)
5890    -- system.string_ops_concat_3 (body)
5891    -- system.traceback (spec)
5892    -- system.traceback (body)
5893    -- ada.exceptions (body)
5894    -- system.unsigned_types (spec)
5895    -- system.stream_attributes (spec)
5896    -- system.stream_attributes (body)
5897    -- system.finalization_implementation (spec)
5898    -- system.finalization_implementation (body)
5899    -- ada.finalization (spec)
5900    -- ada.finalization (body)
5901    -- ada.finalization.list_controller (spec)
5902    -- ada.finalization.list_controller (body)
5903    -- system.file_control_block (spec)
5904    -- system.file_io (spec)
5905    -- system.file_io (body)
5906    -- ada.text_io (spec)
5907    -- ada.text_io (body)
5908    -- hello (body)
5909    -- END ELABORATION ORDER
5911 end ada_main;
5913 --  The following source file name pragmas allow the generated file
5914 --  names to be unique for different main programs. They are needed
5915 --  since the package name will always be Ada_Main.
5917 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
5918 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
5920 --  Generated package body for Ada_Main starts here
5922 package body ada_main is
5924    --  The actual finalization is performed by calling the
5925    --  library routine in System.Standard_Library.Adafinal
5927    procedure Do_Finalize;
5928    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
5930    -------------
5931    -- adainit --
5932    -------------
5934 @findex adainit
5935    procedure adainit is
5937       --  These booleans are set to True once the associated unit has
5938       --  been elaborated. It is also used to avoid elaborating the
5939       --  same unit twice.
5941       E040 : Boolean; pragma Import (Ada, E040, "interfaces__c_streams_E");
5942       E008 : Boolean; pragma Import (Ada, E008, "ada__exceptions_E");
5943       E014 : Boolean; pragma Import (Ada, E014, "system__exception_table_E");
5944       E053 : Boolean; pragma Import (Ada, E053, "ada__io_exceptions_E");
5945       E017 : Boolean; pragma Import (Ada, E017, "system__exceptions_E");
5946       E024 : Boolean; pragma Import (Ada, E024, "system__secondary_stack_E");
5947       E030 : Boolean; pragma Import (Ada, E030, "system__stack_checking_E");
5948       E028 : Boolean; pragma Import (Ada, E028, "system__soft_links_E");
5949       E035 : Boolean; pragma Import (Ada, E035, "ada__tags_E");
5950       E033 : Boolean; pragma Import (Ada, E033, "ada__streams_E");
5951       E046 : Boolean; pragma Import (Ada, E046, "system__finalization_root_E");
5952       E048 : Boolean; pragma Import (Ada, E048, "system__finalization_implementation_E");
5953       E044 : Boolean; pragma Import (Ada, E044, "ada__finalization_E");
5954       E057 : Boolean; pragma Import (Ada, E057, "ada__finalization__list_controller_E");
5955       E055 : Boolean; pragma Import (Ada, E055, "system__file_control_block_E");
5956       E042 : Boolean; pragma Import (Ada, E042, "system__file_io_E");
5957       E006 : Boolean; pragma Import (Ada, E006, "ada__text_io_E");
5959       --  Set_Globals is a library routine that stores away the
5960       --  value of the indicated set of global values in global
5961       --  variables within the library.
5963       procedure Set_Globals
5964         (Main_Priority            : Integer;
5965          Time_Slice_Value         : Integer;
5966          WC_Encoding              : Character;
5967          Locking_Policy           : Character;
5968          Queuing_Policy           : Character;
5969          Task_Dispatching_Policy  : Character;
5970          Adafinal                 : System.Address;
5971          Unreserve_All_Interrupts : Integer;
5972          Exception_Tracebacks     : Integer);
5973 @findex __gnat_set_globals
5974       pragma Import (C, Set_Globals, "__gnat_set_globals");
5976       --  SDP_Table_Build is a library routine used to build the
5977       --  exception tables. See unit Ada.Exceptions in files
5978       --  a-except.ads/adb for full details of how zero cost
5979       --  exception handling works. This procedure, the call to
5980       --  it, and the two following tables are all omitted if the
5981       --  build is in longjmp/setjump exception mode.
5983 @findex SDP_Table_Build
5984 @findex Zero Cost Exceptions
5985       procedure SDP_Table_Build
5986         (SDP_Addresses   : System.Address;
5987          SDP_Count       : Natural;
5988          Elab_Addresses  : System.Address;
5989          Elab_Addr_Count : Natural);
5990       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
5992       --  Table of Unit_Exception_Table addresses. Used for zero
5993       --  cost exception handling to build the top level table.
5995       ST : aliased constant array (1 .. 23) of System.Address := (
5996         Hello'UET_Address,
5997         Ada.Text_Io'UET_Address,
5998         Ada.Exceptions'UET_Address,
5999         Gnat.Heap_Sort_A'UET_Address,
6000         System.Exception_Table'UET_Address,
6001         System.Machine_State_Operations'UET_Address,
6002         System.Secondary_Stack'UET_Address,
6003         System.Parameters'UET_Address,
6004         System.Soft_Links'UET_Address,
6005         System.Stack_Checking'UET_Address,
6006         System.Traceback'UET_Address,
6007         Ada.Streams'UET_Address,
6008         Ada.Tags'UET_Address,
6009         System.String_Ops'UET_Address,
6010         Interfaces.C_Streams'UET_Address,
6011         System.File_Io'UET_Address,
6012         Ada.Finalization'UET_Address,
6013         System.Finalization_Root'UET_Address,
6014         System.Finalization_Implementation'UET_Address,
6015         System.String_Ops_Concat_3'UET_Address,
6016         System.Stream_Attributes'UET_Address,
6017         System.File_Control_Block'UET_Address,
6018         Ada.Finalization.List_Controller'UET_Address);
6020       --  Table of addresses of elaboration routines. Used for
6021       --  zero cost exception handling to make sure these
6022       --  addresses are included in the top level procedure
6023       --  address table.
6025       EA : aliased constant array (1 .. 23) of System.Address := (
6026         adainit'Code_Address,
6027         Do_Finalize'Code_Address,
6028         Ada.Exceptions'Elab_Spec'Address,
6029         System.Exceptions'Elab_Spec'Address,
6030         Interfaces.C_Streams'Elab_Spec'Address,
6031         System.Exception_Table'Elab_Body'Address,
6032         Ada.Io_Exceptions'Elab_Spec'Address,
6033         System.Stack_Checking'Elab_Spec'Address,
6034         System.Soft_Links'Elab_Body'Address,
6035         System.Secondary_Stack'Elab_Body'Address,
6036         Ada.Tags'Elab_Spec'Address,
6037         Ada.Tags'Elab_Body'Address,
6038         Ada.Streams'Elab_Spec'Address,
6039         System.Finalization_Root'Elab_Spec'Address,
6040         Ada.Exceptions'Elab_Body'Address,
6041         System.Finalization_Implementation'Elab_Spec'Address,
6042         System.Finalization_Implementation'Elab_Body'Address,
6043         Ada.Finalization'Elab_Spec'Address,
6044         Ada.Finalization.List_Controller'Elab_Spec'Address,
6045         System.File_Control_Block'Elab_Spec'Address,
6046         System.File_Io'Elab_Body'Address,
6047         Ada.Text_Io'Elab_Spec'Address,
6048         Ada.Text_Io'Elab_Body'Address);
6050    --  Start of processing for adainit
6052    begin
6054       --  Call SDP_Table_Build to build the top level procedure
6055       --  table for zero cost exception handling (omitted in
6056       --  longjmp/setjump mode).
6058       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
6060       --  Call Set_Globals to record various information for
6061       --  this partition.  The values are derived by the binder
6062       --  from information stored in the ali files by the compiler.
6064 @findex __gnat_set_globals
6065       Set_Globals
6066         (Main_Priority            => -1,
6067          --  Priority of main program, -1 if no pragma Priority used
6069          Time_Slice_Value         => -1,
6070          --  Time slice from Time_Slice pragma, -1 if none used
6072          WC_Encoding              => 'b',
6073          --  Wide_Character encoding used, default is brackets
6075          Locking_Policy           => ' ',
6076          --  Locking_Policy used, default of space means not
6077          --  specified, otherwise it is the first character of
6078          --  the policy name.
6080          Queuing_Policy           => ' ',
6081          --  Queuing_Policy used, default of space means not
6082          --  specified, otherwise it is the first character of
6083          --  the policy name.
6085          Task_Dispatching_Policy  => ' ',
6086          --  Task_Dispatching_Policy used, default of space means
6087          --  not specified, otherwise first character of the
6088          --  policy name.
6090          Adafinal                 => System.Null_Address,
6091          --  Address of Adafinal routine, not used anymore
6093          Unreserve_All_Interrupts => 0,
6094          --  Set true if pragma Unreserve_All_Interrupts was used
6096          Exception_Tracebacks     => 0);
6097          --  Indicates if exception tracebacks are enabled
6099       Elab_Final_Code := 1;
6101       --  Now we have the elaboration calls for all units in the partition.
6102       --  The Elab_Spec and Elab_Body attributes generate references to the
6103       --  implicit elaboration procedures generated by the compiler for
6104       --  each unit that requires elaboration.
6106       if not E040 then
6107          Interfaces.C_Streams'Elab_Spec;
6108       end if;
6109       E040 := True;
6110       if not E008 then
6111          Ada.Exceptions'Elab_Spec;
6112       end if;
6113       if not E014 then
6114          System.Exception_Table'Elab_Body;
6115          E014 := True;
6116       end if;
6117       if not E053 then
6118          Ada.Io_Exceptions'Elab_Spec;
6119          E053 := True;
6120       end if;
6121       if not E017 then
6122          System.Exceptions'Elab_Spec;
6123          E017 := True;
6124       end if;
6125       if not E030 then
6126          System.Stack_Checking'Elab_Spec;
6127       end if;
6128       if not E028 then
6129          System.Soft_Links'Elab_Body;
6130          E028 := True;
6131       end if;
6132       E030 := True;
6133       if not E024 then
6134          System.Secondary_Stack'Elab_Body;
6135          E024 := True;
6136       end if;
6137       if not E035 then
6138          Ada.Tags'Elab_Spec;
6139       end if;
6140       if not E035 then
6141          Ada.Tags'Elab_Body;
6142          E035 := True;
6143       end if;
6144       if not E033 then
6145          Ada.Streams'Elab_Spec;
6146          E033 := True;
6147       end if;
6148       if not E046 then
6149          System.Finalization_Root'Elab_Spec;
6150       end if;
6151       E046 := True;
6152       if not E008 then
6153          Ada.Exceptions'Elab_Body;
6154          E008 := True;
6155       end if;
6156       if not E048 then
6157          System.Finalization_Implementation'Elab_Spec;
6158       end if;
6159       if not E048 then
6160          System.Finalization_Implementation'Elab_Body;
6161          E048 := True;
6162       end if;
6163       if not E044 then
6164          Ada.Finalization'Elab_Spec;
6165       end if;
6166       E044 := True;
6167       if not E057 then
6168          Ada.Finalization.List_Controller'Elab_Spec;
6169       end if;
6170       E057 := True;
6171       if not E055 then
6172          System.File_Control_Block'Elab_Spec;
6173          E055 := True;
6174       end if;
6175       if not E042 then
6176          System.File_Io'Elab_Body;
6177          E042 := True;
6178       end if;
6179       if not E006 then
6180          Ada.Text_Io'Elab_Spec;
6181       end if;
6182       if not E006 then
6183          Ada.Text_Io'Elab_Body;
6184          E006 := True;
6185       end if;
6187       Elab_Final_Code := 0;
6188    end adainit;
6190    --------------
6191    -- adafinal --
6192    --------------
6194 @findex adafinal
6195    procedure adafinal is
6196    begin
6197       Do_Finalize;
6198    end adafinal;
6200    ----------
6201    -- main --
6202    ----------
6204    --  main is actually a function, as in the ANSI C standard,
6205    --  defined to return the exit status. The three parameters
6206    --  are the argument count, argument values and environment
6207    --  pointer.
6209 @findex Main Program
6210    function main
6211      (argc : Integer;
6212       argv : System.Address;
6213       envp : System.Address)
6214       return Integer
6215    is
6216       --  The initialize routine performs low level system
6217       --  initialization using a standard library routine which
6218       --  sets up signal handling and performs any other
6219       --  required setup. The routine can be found in file
6220       --  a-init.c.
6222 @findex __gnat_initialize
6223       procedure initialize;
6224       pragma Import (C, initialize, "__gnat_initialize");
6226       --  The finalize routine performs low level system
6227       --  finalization using a standard library routine. The
6228       --  routine is found in file a-final.c and in the standard
6229       --  distribution is a dummy routine that does nothing, so
6230       --  really this is a hook for special user finalization.
6232 @findex __gnat_finalize
6233       procedure finalize;
6234       pragma Import (C, finalize, "__gnat_finalize");
6236       --  We get to the main program of the partition by using
6237       --  pragma Import because if we try to with the unit and
6238       --  call it Ada style, then not only do we waste time
6239       --  recompiling it, but also, we don't really know the right
6240       --  switches (e.g. identifier character set) to be used
6241       --  to compile it.
6243       procedure Ada_Main_Program;
6244       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
6246    --  Start of processing for main
6248    begin
6249       --  Save global variables
6251       gnat_argc := argc;
6252       gnat_argv := argv;
6253       gnat_envp := envp;
6255       --  Call low level system initialization
6257       Initialize;
6259       --  Call our generated Ada initialization routine
6261       adainit;
6263       --  This is the point at which we want the debugger to get
6264       --  control
6266       Break_Start;
6268       --  Now we call the main program of the partition
6270       Ada_Main_Program;
6272       --  Perform Ada finalization
6274       adafinal;
6276       --  Perform low level system finalization
6278       Finalize;
6280       --  Return the proper exit status
6281       return (gnat_exit_status);
6282    end;
6284 --  This section is entirely comments, so it has no effect on the
6285 --  compilation of the Ada_Main package. It provides the list of
6286 --  object files and linker options, as well as some standard
6287 --  libraries needed for the link. The gnatlink utility parses
6288 --  this b~hello.adb file to read these comment lines to generate
6289 --  the appropriate command line arguments for the call to the
6290 --  system linker. The BEGIN/END lines are used for sentinels for
6291 --  this parsing operation.
6293 --  The exact file names will of course depend on the environment,
6294 --  host/target and location of files on the host system.
6296 @findex Object file list
6297 -- BEGIN Object file/option list
6298    --   ./hello.o
6299    --   -L./
6300    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
6301    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
6302 -- END Object file/option list
6304 end ada_main;
6306 @end smallexample
6308 @noindent
6309 The Ada code in the above example is exactly what is generated by the
6310 binder. We have added comments to more clearly indicate the function
6311 of each part of the generated @code{Ada_Main} package.
6313 The code is standard Ada in all respects, and can be processed by any
6314 tools that handle Ada. In particular, it is possible to use the debugger
6315 in Ada mode to debug the generated Ada_Main package. For example, suppose
6316 that for reasons that you do not understand, your program is blowing up
6317 during elaboration of the body of @code{Ada.Text_IO}. To chase this bug
6318 down, you can place a breakpoint on the call:
6320 @smallexample
6321 Ada.Text_Io'Elab_Body;
6322 @end smallexample
6324 @noindent
6325 and trace the elaboration routine for this package to find out where
6326 the problem might be (more usually of course you would be debugging
6327 elaboration code in your own application).
6329 @node Generating the Binder Program in C
6330 @section Generating the Binder Program in C
6331 @noindent
6332 In most normal usage, the default mode of @code{gnatbind} which is to
6333 generate the main package in Ada, as described in the previous section.
6334 In particular, this means that any Ada programmer can read and understand
6335 the generated main program. It can also be debugged just like any other
6336 Ada code provided the @code{-g} switch is used for @code{gnatbind}
6337 and @code{gnatlink}.
6339 However for some purposes it may be convenient to generate the main
6340 program in C rather than Ada. This may for example be helpful when you
6341 are generating a mixed language program with the main program in C. The
6342 GNAT compiler itself is an example. The use of the @code{-C} switch
6343 for both @code{gnatbind} and @code{gnatlink} will cause the program to
6344 be generated in C (and compiled using the gnu C compiler). The
6345 following shows the C code generated for the same "Hello World"
6346 program:
6348 @smallexample
6350 #ifdef __STDC__
6351 #define PARAMS(paramlist) paramlist
6352 #else
6353 #define PARAMS(paramlist) ()
6354 #endif
6356 extern void __gnat_set_globals
6357  PARAMS ((int, int, int, int, int, int,
6358           void (*) PARAMS ((void)), int, int));
6359 extern void adafinal PARAMS ((void));
6360 extern void adainit PARAMS ((void));
6361 extern void system__standard_library__adafinal PARAMS ((void));
6362 extern int main PARAMS ((int, char **, char **));
6363 extern void exit PARAMS ((int));
6364 extern void __gnat_break_start PARAMS ((void));
6365 extern void _ada_hello PARAMS ((void));
6366 extern void __gnat_initialize PARAMS ((void));
6367 extern void __gnat_finalize PARAMS ((void));
6369 extern void ada__exceptions___elabs PARAMS ((void));
6370 extern void system__exceptions___elabs PARAMS ((void));
6371 extern void interfaces__c_streams___elabs PARAMS ((void));
6372 extern void system__exception_table___elabb PARAMS ((void));
6373 extern void ada__io_exceptions___elabs PARAMS ((void));
6374 extern void system__stack_checking___elabs PARAMS ((void));
6375 extern void system__soft_links___elabb PARAMS ((void));
6376 extern void system__secondary_stack___elabb PARAMS ((void));
6377 extern void ada__tags___elabs PARAMS ((void));
6378 extern void ada__tags___elabb PARAMS ((void));
6379 extern void ada__streams___elabs PARAMS ((void));
6380 extern void system__finalization_root___elabs PARAMS ((void));
6381 extern void ada__exceptions___elabb PARAMS ((void));
6382 extern void system__finalization_implementation___elabs PARAMS ((void));
6383 extern void system__finalization_implementation___elabb PARAMS ((void));
6384 extern void ada__finalization___elabs PARAMS ((void));
6385 extern void ada__finalization__list_controller___elabs PARAMS ((void));
6386 extern void system__file_control_block___elabs PARAMS ((void));
6387 extern void system__file_io___elabb PARAMS ((void));
6388 extern void ada__text_io___elabs PARAMS ((void));
6389 extern void ada__text_io___elabb PARAMS ((void));
6391 extern int __gnat_inside_elab_final_code;
6393 extern int gnat_argc;
6394 extern char **gnat_argv;
6395 extern char **gnat_envp;
6396 extern int gnat_exit_status;
6398 char __gnat_version[] = "GNAT Version: 3.15w (20010315)";
6399 void adafinal () @{
6400    system__standard_library__adafinal ();
6403 void adainit ()
6405    extern char ada__exceptions_E;
6406    extern char system__exceptions_E;
6407    extern char interfaces__c_streams_E;
6408    extern char system__exception_table_E;
6409    extern char ada__io_exceptions_E;
6410    extern char system__secondary_stack_E;
6411    extern char system__stack_checking_E;
6412    extern char system__soft_links_E;
6413    extern char ada__tags_E;
6414    extern char ada__streams_E;
6415    extern char system__finalization_root_E;
6416    extern char system__finalization_implementation_E;
6417    extern char ada__finalization_E;
6418    extern char ada__finalization__list_controller_E;
6419    extern char system__file_control_block_E;
6420    extern char system__file_io_E;
6421    extern char ada__text_io_E;
6423    extern void *__gnat_hello__SDP;
6424    extern void *__gnat_ada__text_io__SDP;
6425    extern void *__gnat_ada__exceptions__SDP;
6426    extern void *__gnat_gnat__heap_sort_a__SDP;
6427    extern void *__gnat_system__exception_table__SDP;
6428    extern void *__gnat_system__machine_state_operations__SDP;
6429    extern void *__gnat_system__secondary_stack__SDP;
6430    extern void *__gnat_system__parameters__SDP;
6431    extern void *__gnat_system__soft_links__SDP;
6432    extern void *__gnat_system__stack_checking__SDP;
6433    extern void *__gnat_system__traceback__SDP;
6434    extern void *__gnat_ada__streams__SDP;
6435    extern void *__gnat_ada__tags__SDP;
6436    extern void *__gnat_system__string_ops__SDP;
6437    extern void *__gnat_interfaces__c_streams__SDP;
6438    extern void *__gnat_system__file_io__SDP;
6439    extern void *__gnat_ada__finalization__SDP;
6440    extern void *__gnat_system__finalization_root__SDP;
6441    extern void *__gnat_system__finalization_implementation__SDP;
6442    extern void *__gnat_system__string_ops_concat_3__SDP;
6443    extern void *__gnat_system__stream_attributes__SDP;
6444    extern void *__gnat_system__file_control_block__SDP;
6445    extern void *__gnat_ada__finalization__list_controller__SDP;
6447    void **st[23] = @{
6448      &__gnat_hello__SDP,
6449      &__gnat_ada__text_io__SDP,
6450      &__gnat_ada__exceptions__SDP,
6451      &__gnat_gnat__heap_sort_a__SDP,
6452      &__gnat_system__exception_table__SDP,
6453      &__gnat_system__machine_state_operations__SDP,
6454      &__gnat_system__secondary_stack__SDP,
6455      &__gnat_system__parameters__SDP,
6456      &__gnat_system__soft_links__SDP,
6457      &__gnat_system__stack_checking__SDP,
6458      &__gnat_system__traceback__SDP,
6459      &__gnat_ada__streams__SDP,
6460      &__gnat_ada__tags__SDP,
6461      &__gnat_system__string_ops__SDP,
6462      &__gnat_interfaces__c_streams__SDP,
6463      &__gnat_system__file_io__SDP,
6464      &__gnat_ada__finalization__SDP,
6465      &__gnat_system__finalization_root__SDP,
6466      &__gnat_system__finalization_implementation__SDP,
6467      &__gnat_system__string_ops_concat_3__SDP,
6468      &__gnat_system__stream_attributes__SDP,
6469      &__gnat_system__file_control_block__SDP,
6470      &__gnat_ada__finalization__list_controller__SDP@};
6472    extern void ada__exceptions___elabs ();
6473    extern void system__exceptions___elabs ();
6474    extern void interfaces__c_streams___elabs ();
6475    extern void system__exception_table___elabb ();
6476    extern void ada__io_exceptions___elabs ();
6477    extern void system__stack_checking___elabs ();
6478    extern void system__soft_links___elabb ();
6479    extern void system__secondary_stack___elabb ();
6480    extern void ada__tags___elabs ();
6481    extern void ada__tags___elabb ();
6482    extern void ada__streams___elabs ();
6483    extern void system__finalization_root___elabs ();
6484    extern void ada__exceptions___elabb ();
6485    extern void system__finalization_implementation___elabs ();
6486    extern void system__finalization_implementation___elabb ();
6487    extern void ada__finalization___elabs ();
6488    extern void ada__finalization__list_controller___elabs ();
6489    extern void system__file_control_block___elabs ();
6490    extern void system__file_io___elabb ();
6491    extern void ada__text_io___elabs ();
6492    extern void ada__text_io___elabb ();
6494    void (*ea[23]) () = @{
6495      adainit,
6496      system__standard_library__adafinal,
6497      ada__exceptions___elabs,
6498      system__exceptions___elabs,
6499      interfaces__c_streams___elabs,
6500      system__exception_table___elabb,
6501      ada__io_exceptions___elabs,
6502      system__stack_checking___elabs,
6503      system__soft_links___elabb,
6504      system__secondary_stack___elabb,
6505      ada__tags___elabs,
6506      ada__tags___elabb,
6507      ada__streams___elabs,
6508      system__finalization_root___elabs,
6509      ada__exceptions___elabb,
6510      system__finalization_implementation___elabs,
6511      system__finalization_implementation___elabb,
6512      ada__finalization___elabs,
6513      ada__finalization__list_controller___elabs,
6514      system__file_control_block___elabs,
6515      system__file_io___elabb,
6516      ada__text_io___elabs,
6517      ada__text_io___elabb@};
6519    __gnat_SDP_Table_Build (&st, 23, ea, 23);
6520    __gnat_set_globals (
6521       -1,      /* Main_Priority              */
6522       -1,      /* Time_Slice_Value           */
6523       'b',     /* WC_Encoding                */
6524       ' ',     /* Locking_Policy             */
6525       ' ',     /* Queuing_Policy             */
6526       ' ',     /* Tasking_Dispatching_Policy */
6527       0,       /* Finalization routine address, not used anymore */
6528       0,       /* Unreserve_All_Interrupts */
6529       0);      /* Exception_Tracebacks */
6531    __gnat_inside_elab_final_code = 1;
6533    if (ada__exceptions_E == 0) @{
6534       ada__exceptions___elabs ();
6535    @}
6536    if (system__exceptions_E == 0) @{
6537       system__exceptions___elabs ();
6538       system__exceptions_E++;
6539    @}
6540    if (interfaces__c_streams_E == 0) @{
6541       interfaces__c_streams___elabs ();
6542    @}
6543    interfaces__c_streams_E = 1;
6544    if (system__exception_table_E == 0) @{
6545       system__exception_table___elabb ();
6546       system__exception_table_E++;
6547    @}
6548    if (ada__io_exceptions_E == 0) @{
6549       ada__io_exceptions___elabs ();
6550       ada__io_exceptions_E++;
6551    @}
6552    if (system__stack_checking_E == 0) @{
6553       system__stack_checking___elabs ();
6554    @}
6555    if (system__soft_links_E == 0) @{
6556       system__soft_links___elabb ();
6557       system__soft_links_E++;
6558    @}
6559    system__stack_checking_E = 1;
6560    if (system__secondary_stack_E == 0) @{
6561       system__secondary_stack___elabb ();
6562       system__secondary_stack_E++;
6563    @}
6564    if (ada__tags_E == 0) @{
6565       ada__tags___elabs ();
6566    @}
6567    if (ada__tags_E == 0) @{
6568       ada__tags___elabb ();
6569       ada__tags_E++;
6570    @}
6571    if (ada__streams_E == 0) @{
6572       ada__streams___elabs ();
6573       ada__streams_E++;
6574    @}
6575    if (system__finalization_root_E == 0) @{
6576       system__finalization_root___elabs ();
6577    @}
6578    system__finalization_root_E = 1;
6579    if (ada__exceptions_E == 0) @{
6580       ada__exceptions___elabb ();
6581       ada__exceptions_E++;
6582    @}
6583    if (system__finalization_implementation_E == 0) @{
6584       system__finalization_implementation___elabs ();
6585    @}
6586    if (system__finalization_implementation_E == 0) @{
6587       system__finalization_implementation___elabb ();
6588       system__finalization_implementation_E++;
6589    @}
6590    if (ada__finalization_E == 0) @{
6591       ada__finalization___elabs ();
6592    @}
6593    ada__finalization_E = 1;
6594    if (ada__finalization__list_controller_E == 0) @{
6595       ada__finalization__list_controller___elabs ();
6596    @}
6597    ada__finalization__list_controller_E = 1;
6598    if (system__file_control_block_E == 0) @{
6599       system__file_control_block___elabs ();
6600       system__file_control_block_E++;
6601    @}
6602    if (system__file_io_E == 0) @{
6603       system__file_io___elabb ();
6604       system__file_io_E++;
6605    @}
6606    if (ada__text_io_E == 0) @{
6607       ada__text_io___elabs ();
6608    @}
6609    if (ada__text_io_E == 0) @{
6610       ada__text_io___elabb ();
6611       ada__text_io_E++;
6612    @}
6614    __gnat_inside_elab_final_code = 0;
6616 int main (argc, argv, envp)
6617     int argc;
6618     char **argv;
6619     char **envp;
6621    gnat_argc = argc;
6622    gnat_argv = argv;
6623    gnat_envp = envp;
6625    __gnat_initialize ();
6626    adainit ();
6627    __gnat_break_start ();
6629    _ada_hello ();
6631    system__standard_library__adafinal ();
6632    __gnat_finalize ();
6633    exit (gnat_exit_status);
6635 unsigned helloB = 0x7880BEB3;
6636 unsigned system__standard_libraryB = 0x0D24CBD0;
6637 unsigned system__standard_libraryS = 0x3283DBEB;
6638 unsigned adaS = 0x2359F9ED;
6639 unsigned ada__text_ioB = 0x47C85FC4;
6640 unsigned ada__text_ioS = 0x496FE45C;
6641 unsigned ada__exceptionsB = 0x74F50187;
6642 unsigned ada__exceptionsS = 0x6736945B;
6643 unsigned gnatS = 0x156A40CF;
6644 unsigned gnat__heap_sort_aB = 0x033DABE0;
6645 unsigned gnat__heap_sort_aS = 0x6AB38FEA;
6646 unsigned systemS = 0x0331C6FE;
6647 unsigned system__exceptionsS = 0x20C9ECA4;
6648 unsigned system__exception_tableB = 0x68A22947;
6649 unsigned system__exception_tableS = 0x394BADD5;
6650 unsigned gnat__htableB = 0x08258E1B;
6651 unsigned gnat__htableS = 0x367D5222;
6652 unsigned system__machine_state_operationsB = 0x4F3B7492;
6653 unsigned system__machine_state_operationsS = 0x182F5CF4;
6654 unsigned system__storage_elementsB = 0x2F1EB794;
6655 unsigned system__storage_elementsS = 0x102C83C7;
6656 unsigned system__secondary_stackB = 0x1574B6E9;
6657 unsigned system__secondary_stackS = 0x708E260A;
6658 unsigned system__parametersB = 0x56D770CD;
6659 unsigned system__parametersS = 0x237E39BE;
6660 unsigned system__soft_linksB = 0x08AB6B2C;
6661 unsigned system__soft_linksS = 0x1E2491F3;
6662 unsigned system__stack_checkingB = 0x476457A0;
6663 unsigned system__stack_checkingS = 0x5299FCED;
6664 unsigned system__tracebackB = 0x2971EBDE;
6665 unsigned system__tracebackS = 0x2E9C3122;
6666 unsigned ada__streamsS = 0x7C25DE96;
6667 unsigned ada__tagsB = 0x39ADFFA2;
6668 unsigned ada__tagsS = 0x769A0464;
6669 unsigned system__string_opsB = 0x5EB646AB;
6670 unsigned system__string_opsS = 0x63CED018;
6671 unsigned interfacesS = 0x0357E00A;
6672 unsigned interfaces__c_streamsB = 0x3784FB72;
6673 unsigned interfaces__c_streamsS = 0x2E723019;
6674 unsigned system__file_ioB = 0x623358EA;
6675 unsigned system__file_ioS = 0x31F873E6;
6676 unsigned ada__finalizationB = 0x6843F68A;
6677 unsigned ada__finalizationS = 0x63305874;
6678 unsigned system__finalization_rootB = 0x31E56CE1;
6679 unsigned system__finalization_rootS = 0x23169EF3;
6680 unsigned system__finalization_implementationB = 0x6CCBA70E;
6681 unsigned system__finalization_implementationS = 0x604AA587;
6682 unsigned system__string_ops_concat_3B = 0x572E3F58;
6683 unsigned system__string_ops_concat_3S = 0x01F57876;
6684 unsigned system__stream_attributesB = 0x1D4F93E8;
6685 unsigned system__stream_attributesS = 0x30B2EC3D;
6686 unsigned ada__io_exceptionsS = 0x34054F96;
6687 unsigned system__unsigned_typesS = 0x7B9E7FE3;
6688 unsigned system__file_control_blockS = 0x2FF876A8;
6689 unsigned ada__finalization__list_controllerB = 0x5760634A;
6690 unsigned ada__finalization__list_controllerS = 0x5D851835;
6692 /* BEGIN ELABORATION ORDER
6693 ada (spec)
6694 gnat (spec)
6695 gnat.heap_sort_a (spec)
6696 gnat.htable (spec)
6697 gnat.htable (body)
6698 interfaces (spec)
6699 system (spec)
6700 system.parameters (spec)
6701 system.standard_library (spec)
6702 ada.exceptions (spec)
6703 system.exceptions (spec)
6704 system.parameters (body)
6705 gnat.heap_sort_a (body)
6706 interfaces.c_streams (spec)
6707 interfaces.c_streams (body)
6708 system.exception_table (spec)
6709 system.exception_table (body)
6710 ada.io_exceptions (spec)
6711 system.storage_elements (spec)
6712 system.storage_elements (body)
6713 system.machine_state_operations (spec)
6714 system.machine_state_operations (body)
6715 system.secondary_stack (spec)
6716 system.stack_checking (spec)
6717 system.soft_links (spec)
6718 system.soft_links (body)
6719 system.stack_checking (body)
6720 system.secondary_stack (body)
6721 system.standard_library (body)
6722 system.string_ops (spec)
6723 system.string_ops (body)
6724 ada.tags (spec)
6725 ada.tags (body)
6726 ada.streams (spec)
6727 system.finalization_root (spec)
6728 system.finalization_root (body)
6729 system.string_ops_concat_3 (spec)
6730 system.string_ops_concat_3 (body)
6731 system.traceback (spec)
6732 system.traceback (body)
6733 ada.exceptions (body)
6734 system.unsigned_types (spec)
6735 system.stream_attributes (spec)
6736 system.stream_attributes (body)
6737 system.finalization_implementation (spec)
6738 system.finalization_implementation (body)
6739 ada.finalization (spec)
6740 ada.finalization (body)
6741 ada.finalization.list_controller (spec)
6742 ada.finalization.list_controller (body)
6743 system.file_control_block (spec)
6744 system.file_io (spec)
6745 system.file_io (body)
6746 ada.text_io (spec)
6747 ada.text_io (body)
6748 hello (body)
6749    END ELABORATION ORDER */
6751 /* BEGIN Object file/option list
6752 ./hello.o
6753 -L./
6754 -L/usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/
6755 /usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/libgnat.a
6756 -lexc
6757    END Object file/option list */
6759 @end smallexample
6761 @noindent
6762 Here again, the C code is exactly what is generated by the binder. The
6763 functions of the various parts of this code correspond in an obvious
6764 manner with the commented Ada code shown in the example in the previous
6765 section.
6767 @node Consistency-Checking Modes
6768 @section Consistency-Checking Modes
6770 @noindent
6771 As described in the previous section, by default @code{gnatbind} checks
6772 that object files are consistent with one another and are consistent
6773 with any source files it can locate. The following switches control binder
6774 access to sources.
6776 @table @code
6777 @item ^-s^/READ_SOURCES=ALL^
6778 @cindex @code{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
6779 Require source files to be present. In this mode, the binder must be
6780 able to locate all source files that are referenced, in order to check
6781 their consistency. In normal mode, if a source file cannot be located it
6782 is simply ignored. If you specify this switch, a missing source
6783 file is an error.
6785 @item ^-x^/READ_SOURCES=NONE^
6786 @cindex @code{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
6787 Exclude source files. In this mode, the binder only checks that ALI
6788 files are consistent with one another. Source files are not accessed.
6789 The binder runs faster in this mode, and there is still a guarantee that
6790 the resulting program is self-consistent.
6791 If a source file has been edited since it was last compiled, and you
6792 specify this switch, the binder will not detect that the object
6793 file is out of date with respect to the source file. Note that this is the
6794 mode that is automatically used by @code{gnatmake} because in this
6795 case the checking against sources has already been performed by
6796 @code{gnatmake} in the course of compilation (i.e. before binding).
6798 @ifset vms
6799 @item /READ_SOURCES=AVAILABLE
6800 This is the default mode in which source files are checked if they are
6801 available, and ignored if they are not available.
6802 @end ifset
6803 @end table
6805 @node Binder Error Message Control
6806 @section Binder Error Message Control
6808 @noindent
6809 The following switches provide control over the generation of error
6810 messages from the binder:
6812 @table @code
6813 @item ^-v^/REPORT_ERRORS=VERBOSE^
6814 @cindex @code{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
6815 Verbose mode. In the normal mode, brief error messages are generated to
6816 @file{stderr}. If this switch is present, a header is written
6817 to @file{stdout} and any error messages are directed to @file{stdout}.
6818 All that is written to @file{stderr} is a brief summary message.
6820 @item ^-b^/REPORT_ERRORS=BRIEF^
6821 @cindex @code{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
6822 Generate brief error messages to @file{stderr} even if verbose mode is
6823 specified. This is relevant only when used with the
6824 @code{^-v^/REPORT_ERRORS=VERBOSE^} switch.
6826 @ifclear vms
6827 @item -m@var{n}
6828 @cindex @code{-m} (@code{gnatbind})
6829 Limits the number of error messages to @var{n}, a decimal integer in the
6830 range 1-999. The binder terminates immediately if this limit is reached.
6832 @item -M@var{xxx}
6833 @cindex @code{-M} (@code{gnatbind})
6834 Renames the generated main program from @code{main} to @code{xxx}.
6835 This is useful in the case of some cross-building environments, where
6836 the actual main program is separate from the one generated
6837 by @code{gnatbind}.
6838 @end ifclear
6840 @item ^-ws^/WARNINGS=SUPPRESS^
6841 @cindex @code{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
6842 @cindex Warnings
6843 Suppress all warning messages.
6845 @item ^-we^/WARNINGS=ERROR^
6846 @cindex @code{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
6847 Treat any warning messages as fatal errors.
6849 @ifset vms
6850 @item /WARNINGS=NORMAL
6851 Standard mode with warnings generated, but warnings do not get treated
6852 as errors.
6853 @end ifset
6855 @item ^-t^/NOTIME_STAMP_CHECK^
6856 @cindex @code{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
6857 @cindex Time stamp checks, in binder
6858 @cindex Binder consistency checks
6859 @cindex Consistency checks, in binder
6860 The binder performs a number of consistency checks including:
6862 @itemize @bullet
6863 @item
6864 Check that time stamps of a given source unit are consistent
6865 @item
6866 Check that checksums of a given source unit are consistent
6867 @item
6868 Check that consistent versions of @code{GNAT} were used for compilation
6869 @item
6870 Check consistency of configuration pragmas as required
6871 @end itemize
6873 @noindent
6874 Normally failure of such checks, in accordance with the consistency
6875 requirements of the Ada Reference Manual, causes error messages to be
6876 generated which abort the binder and prevent the output of a binder
6877 file and subsequent link to obtain an executable.
6879 The @code{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
6880 into warnings, so that
6881 binding and linking can continue to completion even in the presence of such
6882 errors. The result may be a failed link (due to missing symbols), or a
6883 non-functional executable which has undefined semantics.
6884 @emph{This means that
6885 @code{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
6886 with extreme care.}
6887 @end table
6889 @node Elaboration Control
6890 @section Elaboration Control
6892 @noindent
6893 The following switches provide additional control over the elaboration
6894 order. For full details see @xref{Elaboration Order Handling in GNAT}.
6896 @table @code
6897 @item ^-p^/PESSIMISTIC_ELABORATION^
6898 @cindex @code{^-h^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
6899 Normally the binder attempts to choose an elaboration order that is
6900 likely to minimize the likelihood of an elaboration order error resulting
6901 in raising a @code{Program_Error} exception. This switch reverses the
6902 action of the binder, and requests that it deliberately choose an order
6903 that is likely to maximize the likelihood of an elaboration error.
6904 This is useful in ensuring portability and avoiding dependence on
6905 accidental fortuitous elaboration ordering.
6907 Normally it only makes sense to use the @code{-p} switch if dynamic
6908 elaboration checking is used (@option{-gnatE} switch used for compilation).
6909 This is because in the default static elaboration mode, all necessary
6910 @code{Elaborate_All} pragmas are implicitly inserted. These implicit
6911 pragmas are still respected by the binder in @code{-p} mode, so a
6912 safe elaboration order is assured.
6913 @end table
6915 @node Output Control
6916 @section Output Control
6918 @noindent
6919 The following switches allow additional control over the output
6920 generated by the binder.
6922 @table @code
6924 @item ^-A^/BIND_FILE=ADA^
6925 @cindex @code{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
6926 Generate binder program in Ada (default). The binder program is named
6927 @file{b~@var{mainprog}.adb} by default. This can be changed with
6928 @code{-o} @code{gnatbind} option.
6930 @item ^-c^/NOOUTPUT^
6931 @cindex @code{^-c^/NOOUTPUT^} (@code{gnatbind})
6932 Check only. Do not generate the binder output file. In this mode the
6933 binder performs all error checks but does not generate an output file.
6935 @item ^-C^/BIND_FILE=C^
6936 @cindex @code{^-C^/BIND_FILE=C^} (@code{gnatbind})
6937 Generate binder program in C. The binder program is named
6938 @file{b_@var{mainprog}.c}. This can be changed with @code{-o} @code{gnatbind}
6939 option.
6941 @item ^-e^/ELABORATION_DEPENDENCIES^
6942 @cindex @code{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
6943 Output complete list of elaboration-order dependencies, showing the
6944 reason for each dependency. This output can be rather extensive but may
6945 be useful in diagnosing problems with elaboration order. The output is
6946 written to @file{stdout}.
6948 @item ^-h^/HELP^
6949 @cindex @code{^-h^/HELP^} (@code{gnatbind})
6950 Output usage information. The output is written to @file{stdout}.
6952 @item ^-K^/LINKER_OPTION_LIST^
6953 @cindex @code{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
6954 Output linker options to @file{stdout}. Includes library search paths,
6955 contents of pragmas Ident and Linker_Options, and libraries added
6956 by @code{gnatbind}.
6958 @item ^-l^/ORDER_OF_ELABORATION^
6959 @cindex @code{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
6960 Output chosen elaboration order. The output is written to @file{stdout}.
6962 @item ^-O^/OBJECT_LIST^
6963 @cindex @code{^-O^/OBJECT_LIST^} (@code{gnatbind})
6964 Output full names of all the object files that must be linked to provide
6965 the Ada component of the program. The output is written to @file{stdout}.
6966 This list includes the files explicitly supplied and referenced by the user
6967 as well as implicitly referenced run-time unit files. The latter are
6968 omitted if the corresponding units reside in shared libraries. The
6969 directory names for the run-time units depend on the system configuration.
6971 @item ^-o ^/OUTPUT=^@var{file}
6972 @cindex @code{^-o^/OUTPUT^} (@code{gnatbind})
6973 Set name of output file to @var{file} instead of the normal
6974 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
6975 binder generated body filename. In C mode you would normally give
6976 @var{file} an extension of @file{.c} because it will be a C source program.
6977 Note that if this option is used, then linking must be done manually.
6978 It is not possible to use gnatlink in this case, since it cannot locate
6979 the binder file.
6981 @item ^-r^/RESTRICTION_LIST^
6982 @cindex @code{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
6983 Generate list of @code{pragma Rerstrictions} that could be applied to
6984 the current unit. This is useful for code audit purposes, and also may
6985 be used to improve code generation in some cases.
6987 @end table
6989 @node Binding with Non-Ada Main Programs
6990 @section Binding with Non-Ada Main Programs
6992 @noindent
6993 In our description so far we have assumed that the main
6994 program is in Ada, and that the task of the binder is to generate a
6995 corresponding function @code{main} that invokes this Ada main
6996 program. GNAT also supports the building of executable programs where
6997 the main program is not in Ada, but some of the called routines are
6998 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
6999 The following switch is used in this situation:
7001 @table @code
7002 @item ^-n^/NOMAIN^
7003 @cindex @code{^-n^/NOMAIN^} (@code{gnatbind})
7004 No main program. The main program is not in Ada.
7005 @end table
7007 @noindent
7008 In this case, most of the functions of the binder are still required,
7009 but instead of generating a main program, the binder generates a file
7010 containing the following callable routines:
7012 @table @code
7013 @item adainit
7014 @findex adainit
7015 You must call this routine to initialize the Ada part of the program by
7016 calling the necessary elaboration routines. A call to @code{adainit} is
7017 required before the first call to an Ada subprogram.
7019 Note that it is assumed that the basic execution environment must be setup
7020 to be appropriate for Ada execution at the point where the first Ada
7021 subprogram is called. In particular, if the Ada code will do any
7022 floating-point operations, then the FPU must be setup in an appropriate
7023 manner. For the case of the x86, for example, full precision mode is
7024 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7025 that the FPU is in the right state.
7027 @item adafinal
7028 @findex adafinal
7029 You must call this routine to perform any library-level finalization
7030 required by the Ada subprograms. A call to @code{adafinal} is required
7031 after the last call to an Ada subprogram, and before the program
7032 terminates.
7033 @end table
7035 @noindent
7036 If the @code{^-n^/NOMAIN^} switch
7037 @cindex Binder, multiple input files
7038 is given, more than one ALI file may appear on
7039 the command line for @code{gnatbind}. The normal @dfn{closure}
7040 calculation is performed for each of the specified units. Calculating
7041 the closure means finding out the set of units involved by tracing
7042 @code{with} references. The reason it is necessary to be able to
7043 specify more than one ALI file is that a given program may invoke two or
7044 more quite separate groups of Ada units.
7046 The binder takes the name of its output file from the last specified ALI
7047 file, unless overridden by the use of the @code{^-o file^/OUTPUT=file^}.
7048 The output is an Ada unit in source form that can
7049 be compiled with GNAT unless the -C switch is used in which case the
7050 output is a C source file, which must be compiled using the C compiler.
7051 This compilation occurs automatically as part of the @code{gnatlink}
7052 processing.
7054 Currently the GNAT run time requires a FPU using 80 bits mode
7055 precision. Under targets where this is not the default it is required to
7056 call GNAT.Float_Control.Reset before using floating point numbers (this
7057 include float computation, float input and output) in the Ada code. A
7058 side effect is that this could be the wrong mode for the foreign code
7059 where floating point computation could be broken after this call.
7061 @node Binding Programs with No Main Subprogram
7062 @section Binding Programs with No Main Subprogram
7064 @noindent
7065 It is possible to have an Ada program which does not have a main
7066 subprogram. This program will call the elaboration routines of all the
7067 packages, then the finalization routines.
7069 The following switch is used to bind programs organized in this manner:
7071 @table @code
7072 @item ^-z^/ZERO_MAIN^
7073 @cindex @code{^-z^/ZERO_MAIN^} (@code{gnatbind})
7074 Normally the binder checks that the unit name given on the command line
7075 corresponds to a suitable main subprogram. When this switch is used,
7076 a list of ALI files can be given, and the execution of the program
7077 consists of elaboration of these units in an appropriate order.
7078 @end table
7080 @node Summary of Binder Switches
7081 @section Summary of Binder Switches
7083 @noindent
7084 The following are the switches available with @code{gnatbind}:
7086 @table @code
7087 @item ^-aO^/OBJECT_SEARCH^
7088 Specify directory to be searched for ALI files.
7090 @item ^-aI^/SOURCE_SEARCH^
7091 Specify directory to be searched for source file.
7093 @item ^-A^/BIND_FILE=ADA^
7094 Generate binder program in Ada (default)
7096 @item ^-b^/REPORT_ERRORS=BRIEF^
7097 Generate brief messages to @file{stderr} even if verbose mode set.
7099 @item ^-c^/NOOUTPUT^
7100 Check only, no generation of binder output file.
7102 @item ^-C^/BIND_FILE=C^
7103 Generate binder program in C
7105 @item ^-e^/ELABORATION_DEPENDENCIES^
7106 Output complete list of elaboration-order dependencies.
7108 @item -E
7109 Store tracebacks in exception occurrences when the target supports it.
7110 This is the default with the zero cost exception mechanism.
7111 This option is currently supported on the following targets:
7112 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7113 See also the packages @code{GNAT.Traceback} and
7114 @code{GNAT.Traceback.Symbolic} for more information.
7115 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
7116 @code{gcc} option.
7118 @item -h
7119 Output usage (help) information
7121 @item ^-I^/SEARCH^
7122 Specify directory to be searched for source and ALI files.
7124 @item ^-I-^/NOCURRENT_DIRECTORY^
7125 Do not look for sources in the current directory where @code{gnatbind} was
7126 invoked, and do not look for ALI files in the directory containing the
7127 ALI file named in the @code{gnatbind} command line.
7129 @item ^-l^/ORDER_OF_ELABORATION^
7130 Output chosen elaboration order.
7132 @item -Lxxx
7133 Binds the units for library building. In this case the adainit and
7134 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
7135 are renamed to xxxinit and xxxfinal. Implies -n.
7136 @ifclear vms
7137 See @pxref{GNAT and Libraries} for more details.
7138 @end ifclear
7140 @item -Mxyz
7141 Rename generated main program from main to xyz
7143 @item ^-m^/ERROR_LIMIT=^@var{n}
7144 Limit number of detected errors to @var{n} (1-999).
7145 @ifset wnt
7146 Furthermore, under Windows, the sources pointed to by the libraries path
7147 set in the registry are not searched for.
7148 @end ifset
7150 @item ^-n^/NOMAIN^
7151 No main program.
7153 @item -nostdinc
7154 Do not look for sources in the system default directory.
7156 @item -nostdlib
7157 Do not look for library files in the system default directory.
7159 @item --RTS=@var{rts-path}
7160 @cindex @code{--RTS} (@code{gnatbind})
7161 Specifies the default location of the runtime library. Same meaning as the
7162 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
7164 @item ^-o ^/OUTPUT=^@var{file}
7165 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7166 Note that if this option is used, then linking must be done manually,
7167 gnatlink cannot be used.
7169 @item ^-O^/OBJECT_LIST^
7170 Output object list.
7172 @item -p
7173 Pessimistic (worst-case) elaboration order
7175 @item ^-s^/READ_SOURCES=ALL^
7176 Require all source files to be present.
7178 @ifclear vms
7179 @item -static
7180 Link against a static GNAT run time.
7182 @item -shared
7183 Link against a shared GNAT run time when available.
7184 @end ifclear
7186 @item ^-t^/NOTIME_STAMP_CHECK^
7187 Tolerate time stamp and other consistency errors
7189 @item -T@var{n}
7190 Set the time slice value to n microseconds. A value of zero means no time
7191 slicing and also indicates to the tasking run time to match as close as
7192 possible to the annex D requirements of the RM.
7194 @item ^-v^/REPORT_ERRORS=VERBOSE^
7195 Verbose mode. Write error messages, header, summary output to
7196 @file{stdout}.
7198 @ifclear vms
7199 @item -w@var{x}
7200 Warning mode (@var{x}=s/e for suppress/treat as error)
7201 @end ifclear
7203 @ifset vms
7204 @item /WARNINGS=NORMAL
7205 Normal warnings mode. Warnings are issued but ignored
7207 @item /WARNINGS=SUPPRESS
7208 All warning messages are suppressed
7210 @item /WARNINGS=ERROR
7211 Warning messages are treated as fatal errors
7212 @end ifset
7214 @item ^-x^/READ_SOURCES=NONE^
7215 Exclude source files (check object consistency only).
7217 @ifset vms
7218 @item /READ_SOURCES=AVAILABLE
7219 Default mode, in which sources are checked for consistency only if
7220 they are available.
7221 @end ifset
7223 @item ^-z^/ZERO_MAIN^
7224 No main subprogram.
7226 @end table
7228 @ifclear vms
7229 You may obtain this listing by running the program @code{gnatbind} with
7230 no arguments.
7231 @end ifclear
7233 @node Command-Line Access
7234 @section Command-Line Access
7236 @noindent
7237 The package @code{Ada.Command_Line} provides access to the command-line
7238 arguments and program name. In order for this interface to operate
7239 correctly, the two variables
7241 @smallexample
7242 @group
7243 @cartouche
7244 int gnat_argc;
7245 char **gnat_argv;
7246 @end cartouche
7247 @end group
7248 @end smallexample
7250 @noindent
7251 @findex gnat_argv
7252 @findex gnat_argc
7253 are declared in one of the GNAT library routines. These variables must
7254 be set from the actual @code{argc} and @code{argv} values passed to the
7255 main program. With no @code{^n^/NOMAIN^} present, @code{gnatbind}
7256 generates the C main program to automatically set these variables.
7257 If the @code{^n^/NOMAIN^} switch is used, there is no automatic way to
7258 set these variables. If they are not set, the procedures in
7259 @code{Ada.Command_Line} will not be available, and any attempt to use
7260 them will raise @code{Constraint_Error}. If command line access is
7261 required, your main program must set @code{gnat_argc} and
7262 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7265 @node Search Paths for gnatbind
7266 @section Search Paths for @code{gnatbind}
7268 @noindent
7269 The binder takes the name of an ALI file as its argument and needs to
7270 locate source files as well as other ALI files to verify object consistency.
7272 For source files, it follows exactly the same search rules as @code{gcc}
7273 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7274 directories searched are:
7276 @enumerate
7277 @item
7278 The directory containing the ALI file named in the command line, unless
7279 the switch @code{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7281 @item
7282 All directories specified by @code{^-I^/SEARCH^}
7283 switches on the @code{gnatbind}
7284 command line, in the order given.
7286 @item
7287 @findex ADA_OBJECTS_PATH
7288 Each of the directories listed in the value of the
7289 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7290 @ifclear vms
7291 Construct this value
7292 exactly as the @code{PATH} environment variable: a list of directory
7293 names separated by colons (semicolons when working with the NT version
7294 of GNAT).
7295 @end ifclear
7296 @ifset vms
7297 Normally, define this value as a logical name containing a comma separated
7298 list of directory names.
7300 This variable can also be defined by means of an environment string
7301 (an argument to the DEC C exec* set of functions).
7303 Logical Name:
7304 @smallexample
7305 DEFINE ANOTHER_PATH FOO:[BAG]
7306 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7307 @end smallexample
7309 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7310 first, followed by the standard Ada 95
7311 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7312 If this is not redefined, the user will obtain the DEC Ada83 IO packages
7313 (Text_IO, Sequential_IO, etc)
7314 instead of the Ada95 packages. Thus, in order to get the Ada 95
7315 packages by default, ADA_OBJECTS_PATH must be redefined.
7316 @end ifset
7318 @item
7319 The content of the "ada_object_path" file which is part of the GNAT
7320 installation tree and is used to store standard libraries such as the
7321 GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is
7322 specified.
7323 @ifclear vms
7324 @ref{Installing an Ada Library}
7325 @end ifclear
7326 @end enumerate
7328 @noindent
7329 In the binder the switch @code{^-I^/SEARCH^}
7330 is used to specify both source and
7331 library file paths. Use @code{^-aI^/SOURCE_SEARCH^}
7332 instead if you want to specify
7333 source paths only, and @code{^-aO^/LIBRARY_SEARCH^}
7334 if you want to specify library paths
7335 only. This means that for the binder
7336 @code{^-I^/SEARCH=^}@var{dir} is equivalent to
7337 @code{^-aI^/SOURCE_SEARCH=^}@var{dir}
7338 @code{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7339 The binder generates the bind file (a C language source file) in the
7340 current working directory.
7342 @findex Ada
7343 @findex System
7344 @findex Interfaces
7345 @findex GNAT
7346 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7347 children make up the GNAT Run-Time Library, together with the package
7348 GNAT and its children, which contain a set of useful additional
7349 library functions provided by GNAT. The sources for these units are
7350 needed by the compiler and are kept together in one directory. The ALI
7351 files and object files generated by compiling the RTL are needed by the
7352 binder and the linker and are kept together in one directory, typically
7353 different from the directory containing the sources. In a normal
7354 installation, you need not specify these directory names when compiling
7355 or binding. Either the environment variables or the built-in defaults
7356 cause these files to be found.
7358 Besides simplifying access to the RTL, a major use of search paths is
7359 in compiling sources from multiple directories. This can make
7360 development environments much more flexible.
7362 @node Examples of gnatbind Usage
7363 @section Examples of @code{gnatbind} Usage
7365 @noindent
7366 This section contains a number of examples of using the GNAT binding
7367 utility @code{gnatbind}.
7369 @table @code
7370 @item gnatbind hello
7371 The main program @code{Hello} (source program in @file{hello.adb}) is
7372 bound using the standard switch settings. The generated main program is
7373 @file{b~hello.adb}. This is the normal, default use of the binder.
7375 @ifclear vms
7376 @item gnatbind hello -o mainprog.adb
7377 @end ifclear
7378 @ifset vms
7379 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7380 @end ifset
7381 The main program @code{Hello} (source program in @file{hello.adb}) is
7382 bound using the standard switch settings. The generated main program is
7383 @file{mainprog.adb} with the associated spec in
7384 @file{mainprog.ads}. Note that you must specify the body here not the
7385 spec, in the case where the output is in Ada. Note that if this option
7386 is used, then linking must be done manually, since gnatlink will not
7387 be able to find the generated file.
7389 @ifclear vms
7390 @item gnatbind main -C -o mainprog.c -x
7391 @end ifclear
7392 @ifset vms
7393 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7394 @end ifset
7395 The main program @code{Main} (source program in
7396 @file{main.adb}) is bound, excluding source files from the
7397 consistency checking, generating
7398 the file @file{mainprog.c}.
7400 @ifclear vms
7401 @item gnatbind -x main_program -C -o mainprog.c
7402 This command is exactly the same as the previous example. Switches may
7403 appear anywhere in the command line, and single letter switches may be
7404 combined into a single switch.
7405 @end ifclear
7407 @ifclear vms
7408 @item gnatbind -n math dbase -C -o ada-control.c
7409 @end ifclear
7410 @ifset vms
7411 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7412 @end ifset
7413 The main program is in a language other than Ada, but calls to
7414 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7415 to @code{gnatbind} generates the file @file{ada-control.c} containing
7416 the @code{adainit} and @code{adafinal} routines to be called before and
7417 after accessing the Ada units.
7418 @end table
7420 @node Linking Using gnatlink
7421 @chapter Linking Using @code{gnatlink}
7422 @findex gnatlink
7424 @noindent
7425 This chapter discusses @code{gnatlink}, a utility program used to link
7426 Ada programs and build an executable file. This is a simple program
7427 that invokes the Unix linker (via the @code{gcc}
7428 command) with a correct list of object files and library references.
7429 @code{gnatlink} automatically determines the list of files and
7430 references for the Ada part of a program. It uses the binder file
7431 generated by the binder to determine this list.
7433 @menu
7434 * Running gnatlink::
7435 * Switches for gnatlink::
7436 * Setting Stack Size from gnatlink::
7437 * Setting Heap Size from gnatlink::
7438 @end menu
7440 @node Running gnatlink
7441 @section Running @code{gnatlink}
7443 @noindent
7444 The form of the @code{gnatlink} command is
7446 @smallexample
7447 $ gnatlink [@var{switches}] @var{mainprog}[.ali] [@var{non-Ada objects}]
7448       [@var{linker options}]
7449 @end smallexample
7451 @noindent
7452 @file{@var{mainprog}.ali} references the ALI file of the main program.
7453 The @file{.ali} extension of this file can be omitted. From this
7454 reference, @code{gnatlink} locates the corresponding binder file
7455 @file{b~@var{mainprog}.adb} and, using the information in this file along
7456 with the list of non-Ada objects and linker options, constructs a Unix
7457 linker command file to create the executable.
7459 The arguments following @file{@var{mainprog}.ali} are passed to the
7460 linker uninterpreted. They typically include the names of object files
7461 for units written in other languages than Ada and any library references
7462 required to resolve references in any of these foreign language units,
7463 or in @code{pragma Import} statements in any Ada units.
7465 @var{linker options} is an optional list of linker specific
7466 switches. The default linker called by gnatlink is @var{gcc} which in
7467 turn calls the appropriate system linker usually called
7468 @var{ld}. Standard options for the linker such as @code{-lmy_lib} or
7469 @code{-Ldir} can be added as is. For options that are not recognized by
7470 @var{gcc} as linker options, the @var{gcc} switches @code{-Xlinker} or
7471 @code{-Wl,} shall be used. Refer to the GCC documentation for
7472 details. Here is an example showing how to generate a linker map
7473 assuming that the underlying linker is GNU ld:
7475 @smallexample
7476 $ gnatlink my_prog -Wl,-Map,MAPFILE
7477 @end smallexample
7479 Using @var{linker options} it is possible to set the program stack and
7480 heap size. See @pxref{Setting Stack Size from gnatlink} and
7481 @pxref{Setting Heap Size from gnatlink}.
7483 @code{gnatlink} determines the list of objects required by the Ada
7484 program and prepends them to the list of objects passed to the linker.
7485 @code{gnatlink} also gathers any arguments set by the use of
7486 @code{pragma Linker_Options} and adds them to the list of arguments
7487 presented to the linker.
7489 @ifset vms
7490 @code{gnatlink} accepts the following types of extra files on the command
7491 line: objects (.OBJ), libraries (.OLB), shareable images (.EXE), and
7492 options files (.OPT). These are recognized and handled according to their
7493 extension.
7494 @end ifset
7496 @node Switches for gnatlink
7497 @section Switches for @code{gnatlink}
7499 @noindent
7500 The following switches are available with the @code{gnatlink} utility:
7502 @table @code
7504 @item ^-A^/BIND_FILE=ADA^
7505 @cindex @code{^-A^/BIND_FILE=ADA^} (@code{gnatlink})
7506 The binder has generated code in Ada. This is the default.
7508 @item ^-C^/BIND_FILE=C^
7509 @cindex @code{^-C^/BIND_FILE=C^} (@code{gnatlink})
7510 If instead of generating a file in Ada, the binder has generated one in
7511 C, then the linker needs to know about it. Use this switch to signal
7512 to @code{gnatlink} that the binder has generated C code rather than
7513 Ada code.
7515 @item -f
7516 @cindex Command line length
7517 @cindex @code{-f} (@code{gnatlink})
7518 On some targets, the command line length is limited, and @code{gnatlink}
7519 will generate a separate file for the linker if the list of object files
7520 is too long. The @code{-f} flag forces this file to be generated even if
7521 the limit is not exceeded. This is useful in some cases to deal with
7522 special situations where the command line length is exceeded.
7524 @item ^-g^/DEBUG^
7525 @cindex Debugging information, including
7526 @cindex @code{^-g^/DEBUG^} (@code{gnatlink})
7527 The option to include debugging information causes the Ada bind file (in
7528 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7529 @code{^-g^/DEBUG^}.
7530 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7531 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7532 Without @code{^-g^/DEBUG^}, the binder removes these files by
7533 default. The same procedure apply if a C bind file was generated using
7534 @code{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames are
7535 @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7537 @ifclear vms
7538 @item -n
7539 @cindex @code{-n} (@code{gnatlink})
7540 Do not compile the file generated by the binder. This may be used when
7541 a link is rerun with different options, but there is no need to recompile
7542 the binder file.
7543 @end ifclear
7545 @item ^-v^/VERBOSE^
7546 @cindex @code{^-v^/VERBOSE^} (@code{gnatlink})
7547 Causes additional information to be output, including a full list of the
7548 included object files. This switch option is most useful when you want
7549 to see what set of object files are being used in the link step.
7551 @ifclear vms
7552 @item -v -v
7553 @cindex @code{-v -v} (@code{gnatlink})
7554 Very verbose mode. Requests that the compiler operate in verbose mode when
7555 it compiles the binder file, and that the system linker run in verbose mode.
7556 @end ifclear
7558 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7559 @cindex @code{^-o^/EXECUTABLE^} (@code{gnatlink})
7560 @var{exec-name} specifies an alternate name for the generated
7561 executable program. If this switch is omitted, the executable has the same
7562 name as the main unit. For example, @code{gnatlink try.ali} creates
7563 an executable called @file{^try^TRY.EXE^}.
7565 @ifclear vms
7566 @item -b @var{target}
7567 @cindex @code{-b} (@code{gnatlink})
7568 Compile your program to run on @var{target}, which is the name of a
7569 system configuration. You must have a GNAT cross-compiler built if
7570 @var{target} is not the same as your host system.
7572 @item -B@var{dir}
7573 @cindex @code{-B} (@code{gnatlink})
7574 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7575 from @var{dir} instead of the default location. Only use this switch
7576 when multiple versions of the GNAT compiler are available. See the
7577 @code{gcc} manual page for further details. You would normally use the
7578 @code{-b} or @code{-V} switch instead.
7580 @item --GCC=@var{compiler_name}
7581 @cindex @code{--GCC=compiler_name} (@code{gnatlink})
7582 Program used for compiling the binder file. The default is
7583 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
7584 @code{compiler_name} contains spaces or other separator characters. As
7585 an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
7586 @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
7587 inserted after your command name. Thus in the above example the compiler
7588 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
7589 If several @code{--GCC=compiler_name} are used, only the last
7590 @var{compiler_name} is taken into account. However, all the additional
7591 switches are also taken into account. Thus,
7592 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7593 @code{--GCC="bar -x -y -z -t"}.
7595 @item --LINK=@var{name}
7596 @cindex @code{--LINK=} (@code{gnatlink})
7597 @var{name} is the name of the linker to be invoked. This is especially
7598 useful in mixed language programs since languages such as c++ require
7599 their own linker to be used. When this switch is omitted, the default
7600 name for the linker is (@file{gcc}). When this switch is used, the
7601 specified linker is called instead of (@file{gcc}) with exactly the same
7602 parameters that would have been passed to (@file{gcc}) so if the desired
7603 linker requires different parameters it is necessary to use a wrapper
7604 script that massages the parameters before invoking the real linker. It
7605 may be useful to control the exact invocation by using the verbose
7606 switch.
7608 @end ifclear
7610 @ifset vms
7611 @item /DEBUG=TRACEBACK
7612 @cindex @code{/DEBUG=TRACEBACK} (@code{gnatlink})
7613 This qualifier causes sufficient information to be included in the
7614 executable file to allow a traceback, but does not include the full
7615 symbol information needed by the debugger.
7617 @item /IDENTIFICATION="<string>"
7618 "<string>" specifies the string to be stored in the image file identification
7619 field in the image header. It overrides any pragma Ident specified string.
7621 @item /NOINHIBIT-EXEC
7622 Generate the executable file even if there are linker warnings.
7624 @item /NOSTART_FILES
7625 Don't link in the object file containing the "main" transfer address.
7626 Used when linking with a foreign language main program compiled with a
7627 Digital compiler.
7629 @item /STATIC
7630 Prefer linking with object libraries over shareable images, even without
7631 /DEBUG.
7632 @end ifset
7634 @end table
7636 @node Setting Stack Size from gnatlink
7637 @section Setting Stack Size from @code{gnatlink}
7639 @noindent
7640 It is possible to specify the program stack size from @code{gnatlink}.
7641 Assuming that the underlying linker is GNU ld there is two ways to do so:
7643 @itemize @bullet
7645 @item using @code{-Xlinker} linker option
7647 @smallexample
7648 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
7649 @end smallexample
7651 This set the stack reserve size to 0x10000 bytes and the stack commit
7652 size to 0x1000 bytes.
7654 @item using @code{-Wl} linker option
7656 @smallexample
7657 $ gnatlink hello -Wl,--stack=0x1000000
7658 @end smallexample
7660 This set the stack reserve size to 0x1000000 bytes. Note that with
7661 @code{-Wl} option it is not possible to set the stack commit size
7662 because the coma is a separator for this option.
7664 @end itemize
7666 @node Setting Heap Size from gnatlink
7667 @section Setting Heap Size from @code{gnatlink}
7669 @noindent
7670 It is possible to specify the program heap size from @code{gnatlink}.
7671 Assuming that the underlying linker is GNU ld there is two ways to do so:
7673 @itemize @bullet
7675 @item using @code{-Xlinker} linker option
7677 @smallexample
7678 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
7679 @end smallexample
7681 This set the heap reserve size to 0x10000 bytes and the heap commit
7682 size to 0x1000 bytes.
7684 @item using @code{-Wl} linker option
7686 @smallexample
7687 $ gnatlink hello -Wl,--heap=0x1000000
7688 @end smallexample
7690 This set the heap reserve size to 0x1000000 bytes. Note that with
7691 @code{-Wl} option it is not possible to set the heap commit size
7692 because the coma is a separator for this option.
7694 @end itemize
7696 @node The GNAT Make Program gnatmake
7697 @chapter The GNAT Make Program @code{gnatmake}
7698 @findex gnatmake
7700 @menu
7701 * Running gnatmake::
7702 * Switches for gnatmake::
7703 * Mode Switches for gnatmake::
7704 * Notes on the Command Line::
7705 * How gnatmake Works::
7706 * Examples of gnatmake Usage::
7707 @end menu
7708 @noindent
7709 A typical development cycle when working on an Ada program consists of
7710 the following steps:
7712 @enumerate
7713 @item
7714 Edit some sources to fix bugs.
7716 @item
7717 Add enhancements.
7719 @item
7720 Compile all sources affected.
7722 @item
7723 Rebind and relink.
7725 @item
7726 Test.
7727 @end enumerate
7729 @noindent
7730 The third step can be tricky, because not only do the modified files
7731 @cindex Dependency rules
7732 have to be compiled, but any files depending on these files must also be
7733 recompiled. The dependency rules in Ada can be quite complex, especially
7734 in the presence of overloading, @code{use} clauses, generics and inlined
7735 subprograms.
7737 @code{gnatmake} automatically takes care of the third and fourth steps
7738 of this process. It determines which sources need to be compiled,
7739 compiles them, and binds and links the resulting object files.
7741 Unlike some other Ada make programs, the dependencies are always
7742 accurately recomputed from the new sources. The source based approach of
7743 the GNAT compilation model makes this possible. This means that if
7744 changes to the source program cause corresponding changes in
7745 dependencies, they will always be tracked exactly correctly by
7746 @code{gnatmake}.
7748 @node Running gnatmake
7749 @section Running @code{gnatmake}
7751 @noindent
7752 The usual form of the @code{gnatmake} command is
7754 @smallexample
7755 $ gnatmake [@var{switches}] @var{file_name} [@var{file_names}] [@var{mode_switches}]
7756 @end smallexample
7758 @noindent
7759 The only required argument is one @var{file_name}, which specifies
7760 a compilation unit that is a main program. Several @var{file_names} can be
7761 specified: this will result in several executables being built.
7762 If @code{switches} are present, they can be placed before the first
7763 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
7764 If @var{mode_switches} are present, they must always be placed after
7765 the last @var{file_name} and all @code{switches}.
7767 If you are using standard file extensions (.adb and .ads), then the
7768 extension may be omitted from the @var{file_name} arguments. However, if
7769 you are using non-standard extensions, then it is required that the
7770 extension be given. A relative or absolute directory path can be
7771 specified in a @var{file_name}, in which case, the input source file will
7772 be searched for in the specified directory only. Otherwise, the input
7773 source file will first be searched in the directory where
7774 @code{gnatmake} was invoked and if it is not found, it will be search on
7775 the source path of the compiler as described in
7776 @ref{Search Paths and the Run-Time Library (RTL)}.
7778 When several @var{file_names} are specified, if an executable needs to be
7779 rebuilt and relinked, all subsequent executables will be rebuilt and
7780 relinked, even if this would not be absolutely necessary.
7782 All @code{gnatmake} output (except when you specify
7783 @code{^-M^/DEPENDENCIES_LIST^}) is to
7784 @file{stderr}. The output produced by the
7785 @code{^-M^/DEPENDENCIES_LIST^} switch is send to
7786 @file{stdout}.
7788 @node Switches for gnatmake
7789 @section Switches for @code{gnatmake}
7791 @noindent
7792 You may specify any of the following switches to @code{gnatmake}:
7794 @table @code
7795 @ifclear vms
7796 @item --GCC=@var{compiler_name}
7797 @cindex @code{--GCC=compiler_name} (@code{gnatmake})
7798 Program used for compiling. The default is `@code{gcc}'. You need to use
7799 quotes around @var{compiler_name} if @code{compiler_name} contains
7800 spaces or other separator characters. As an example @code{--GCC="foo -x
7801 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
7802 compiler. Note that switch @code{-c} is always inserted after your
7803 command name. Thus in the above example the compiler command that will
7804 be used by @code{gnatmake} will be @code{foo -c -x -y}.
7805 If several @code{--GCC=compiler_name} are used, only the last
7806 @var{compiler_name} is taken into account. However, all the additional
7807 switches are also taken into account. Thus,
7808 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7809 @code{--GCC="bar -x -y -z -t"}.
7811 @item --GNATBIND=@var{binder_name}
7812 @cindex @code{--GNATBIND=binder_name} (@code{gnatmake})
7813 Program used for binding. The default is `@code{gnatbind}'. You need to
7814 use quotes around @var{binder_name} if @var{binder_name} contains spaces
7815 or other separator characters. As an example @code{--GNATBIND="bar -x
7816 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
7817 binder. Binder switches that are normally appended by @code{gnatmake} to
7818 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
7820 @item --GNATLINK=@var{linker_name}
7821 @cindex @code{--GNATLINK=linker_name} (@code{gnatmake})
7822 Program used for linking. The default is `@code{gnatlink}'. You need to
7823 use quotes around @var{linker_name} if @var{linker_name} contains spaces
7824 or other separator characters. As an example @code{--GNATLINK="lan -x
7825 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
7826 linker. Linker switches that are normally appended by @code{gnatmake} to
7827 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
7829 @end ifclear
7831 @item ^-a^/ALL_FILES^
7832 @cindex @code{^-a^/ALL_FILES^} (@code{gnatmake})
7833 Consider all files in the make process, even the GNAT internal system
7834 files (for example, the predefined Ada library files), as well as any
7835 locked files. Locked files are files whose ALI file is write-protected.
7836 By default,
7837 @code{gnatmake} does not check these files,
7838 because the assumption is that the GNAT internal files are properly up
7839 to date, and also that any write protected ALI files have been properly
7840 installed. Note that if there is an installation problem, such that one
7841 of these files is not up to date, it will be properly caught by the
7842 binder.
7843 You may have to specify this switch if you are working on GNAT
7844 itself. @code{^-a^/ALL_FILES^} is also useful in conjunction with
7845 @code{^-f^/FORCE_COMPILE^}
7846 if you need to recompile an entire application,
7847 including run-time files, using special configuration pragma settings,
7848 such as a non-standard @code{Float_Representation} pragma.
7849 By default
7850 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
7851 internal files with
7852 @ifclear vms
7853 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7854 @end ifclear
7855 @ifset vms
7856 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
7857 @end ifset
7859 @item ^-b^/ACTIONS=BIND^
7860 @cindex @code{^-b^/ACTIONS=BIND^} (@code{gnatmake})
7861 Bind only. Can be combined with @code{^-c^/ACTIONS=COMPILE^} to do compilation
7862 and binding, but no link. Can be combined with @code{^-l^/ACTIONS=LINK^}
7863 to do binding and linking. When not combined with @code{^-c^/ACTIONS=COMPILE^}
7864 all the units in the closure of the main program must have been previously
7865 compiled and must be up to date. The root unit specified by @var{file_name}
7866 may be given without extension, with the source extension or, if no GNAT
7867 Project File is specified, with the ALI file extension.
7869 @item ^-c^/ACTIONS=COMPILE^
7870 @cindex @code{^-c^/ACTIONS=COMPILE^} (@code{gnatmake})
7871 Compile only. Do not perform binding, except when @code{^-b^/ACTIONS=BIND^}
7872 is also specified. Do not perform linking, except if both
7873 @code{^-b^/ACTIONS=BIND^} and
7874  @code{^-l^/ACTIONS=LINK^} are also specified.
7875 If the root unit specified by @var{file_name} is not a main unit, this is the
7876 default. Otherwise @code{gnatmake} will attempt binding and linking
7877 unless all objects are up to date and the executable is more recent than
7878 the objects.
7880 @item ^-C^/MAPPING^
7881 @cindex @code{^-C^/MAPPING^} (@code{gnatmake})
7882 Use a mapping file. A mapping file is a way to communicate to the compiler
7883 two mappings: from unit names to file names (without any directory information)
7884 and from file names to path names (with full directory information).
7885 These mappings are used by the compiler to short-circuit the path search.
7886 When @code{gnatmake} is invoked with this switch, it will create a mapping
7887 file, initially populated by the project manager, if @code{-P} is used,
7888 otherwise initially empty. Each invocation of the compiler will add the newly
7889 accessed sources to the mapping file. This will improve the source search
7890 during the next invocation of the compiler.
7892 @item ^-f^/FORCE_COMPILE^
7893 @cindex @code{^-f^/FORCE_COMPILE^} (@code{gnatmake})
7894 Force recompilations. Recompile all sources, even though some object
7895 files may be up to date, but don't recompile predefined or GNAT internal
7896 files or locked files (files with a write-protected ALI file),
7897 unless the @code{^-a^/ALL_FILES^} switch is also specified.
7899 @item
7900 @item ^-i^/IN_PLACE^
7901 @cindex @code{^-i^/IN_PLACE^} (@code{gnatmake})
7902 In normal mode, @code{gnatmake} compiles all object files and ALI files
7903 into the current directory. If the @code{^-i^/IN_PLACE^} switch is used,
7904 then instead object files and ALI files that already exist are overwritten
7905 in place. This means that once a large project is organized into separate
7906 directories in the desired manner, then @code{gnatmake} will automatically
7907 maintain and update this organization. If no ALI files are found on the
7908 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
7909 the new object and ALI files are created in the
7910 directory containing the source being compiled. If another organization
7911 is desired, where objects and sources are kept in different directories,
7912 a useful technique is to create dummy ALI files in the desired directories.
7913 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
7914 the corresponding source file, and it will be put the resulting object
7915 and ALI files in the directory where it found the dummy file.
7917 @item ^-j^/PROCESSES=^@var{n}
7918 @cindex @code{^-j^/PROCESSES^} (@code{gnatmake})
7919 @cindex Parallel make
7920 Use @var{n} processes to carry out the (re)compilations. On a
7921 multiprocessor machine compilations will occur in parallel. In the
7922 event of compilation errors, messages from various compilations might
7923 get interspersed (but @code{gnatmake} will give you the full ordered
7924 list of failing compiles at the end). If this is problematic, rerun
7925 the make process with n set to 1 to get a clean list of messages.
7927 @item ^-k^/CONTINUE_ON_ERROR^
7928 @cindex @code{^-k^/CONTINUE_ON_ERROR^} (@code{gnatmake})
7929 Keep going. Continue as much as possible after a compilation error. To
7930 ease the programmer's task in case of compilation errors, the list of
7931 sources for which the compile fails is given when @code{gnatmake}
7932 terminates.
7934 If @code{gnatmake} is invoked with several @file{file_names} and with this
7935 switch, if there are compilation errors when building an executable,
7936 @code{gnatmake} will not attempt to build the following executables.
7938 @item ^-l^/ACTIONS=LINK^
7939 @cindex @code{^-l^/ACTIONS=LINK^} (@code{gnatmake})
7940 Link only. Can be combined with @code{^-b^/ACTIONS=BIND^} to binding
7941 and linking. Linking will not be performed if combined with
7942 @code{^-c^/ACTIONS=COMPILE^}
7943 but not with @code{^-b^/ACTIONS=BIND^}.
7944 When not combined with @code{^-b^/ACTIONS=BIND^}
7945 all the units in the closure of the main program must have been previously
7946 compiled and must be up to date, and the main program need to have been bound.
7947 The root unit specified by @var{file_name}
7948 may be given without extension, with the source extension or, if no GNAT
7949 Project File is specified, with the ALI file extension.
7951 @item ^-m^/MINIMAL_RECOMPILATION^
7952 @cindex @code{^-m^/MINIMAL_RECOMPILATION^} (@code{gnatmake})
7953 Specifies that the minimum necessary amount of recompilations
7954 be performed. In this mode @code{gnatmake} ignores time
7955 stamp differences when the only
7956 modifications to a source file consist in adding/removing comments,
7957 empty lines, spaces or tabs. This means that if you have changed the
7958 comments in a source file or have simply reformatted it, using this
7959 switch will tell gnatmake not to recompile files that depend on it
7960 (provided other sources on which these files depend have undergone no
7961 semantic modifications). Note that the debugging information may be
7962 out of date with respect to the sources if the @code{-m} switch causes
7963 a compilation to be switched, so the use of this switch represents a
7964 trade-off between compilation time and accurate debugging information.
7966 @item ^-M^/DEPENDENCIES_LIST^
7967 @cindex Dependencies, producing list
7968 @cindex @code{^-M^/DEPENDENCIES_LIST^} (@code{gnatmake})
7969 Check if all objects are up to date. If they are, output the object
7970 dependences to @file{stdout} in a form that can be directly exploited in
7971 a @file{Makefile}. By default, each source file is prefixed with its
7972 (relative or absolute) directory name. This name is whatever you
7973 specified in the various @code{^-aI^/SOURCE_SEARCH^}
7974 and @code{^-I^/SEARCH^} switches. If you use
7975 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
7976 @code{^-q^/QUIET^}
7977 (see below), only the source file names,
7978 without relative paths, are output. If you just specify the
7979 @code{^-M^/DEPENDENCIES_LIST^}
7980 switch, dependencies of the GNAT internal system files are omitted. This
7981 is typically what you want. If you also specify
7982 the @code{^-a^/ALL_FILES^} switch,
7983 dependencies of the GNAT internal files are also listed. Note that
7984 dependencies of the objects in external Ada libraries (see switch
7985 @code{^-aL^/SKIP_MISSING=^}@var{dir} in the following list) are never reported.
7987 @item ^-n^/DO_OBJECT_CHECK^
7988 @cindex @code{^-n^/DO_OBJECT_CHECK^} (@code{gnatmake})
7989 Don't compile, bind, or link. Checks if all objects are up to date.
7990 If they are not, the full name of the first file that needs to be
7991 recompiled is printed.
7992 Repeated use of this option, followed by compiling the indicated source
7993 file, will eventually result in recompiling all required units.
7995 @item ^-o ^/EXECUTABLE=^@var{exec_name}
7996 @cindex @code{^-o^/EXECUTABLE^} (@code{gnatmake})
7997 Output executable name. The name of the final executable program will be
7998 @var{exec_name}. If the @code{^-o^/EXECUTABLE^} switch is omitted the default
7999 name for the executable will be the name of the input file in appropriate form
8000 for an executable file on the host system.
8002 This switch cannot be used when invoking @code{gnatmake} with several
8003 @file{file_names}.
8005 @item ^-q^/QUIET^
8006 @cindex @code{^-q^/QUIET^} (@code{gnatmake})
8007 Quiet. When this flag is not set, the commands carried out by
8008 @code{gnatmake} are displayed.
8010 @item ^-s^/SWITCH_CHECK/^
8011 @cindex @code{^-s^/SWITCH_CHECK^} (@code{gnatmake})
8012 Recompile if compiler switches have changed since last compilation.
8013 All compiler switches but -I and -o are taken into account in the
8014 following way:
8015 orders between different ``first letter'' switches are ignored, but
8016 orders between same switches are taken into account. For example,
8017 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O} is equivalent
8018 to @code{-O -g}.
8020 @item ^-u^/UNIQUE^
8021 @cindex @code{^-u^/UNIQUE^} (@code{gnatmake})
8022 Unique. Recompile at most the main file. It implies -c. Combined with
8023 -f, it is equivalent to calling the compiler directly.
8025 @item ^-v^/REASONS^
8026 @cindex @code{^-v^/REASONS^} (@code{gnatmake})
8027 Verbose. Displays the reason for all recompilations @code{gnatmake}
8028 decides are necessary.
8030 @item ^-z^/NOMAIN^
8031 @cindex @code{^-z^/NOMAIN^} (@code{gnatmake})
8032 No main subprogram. Bind and link the program even if the unit name
8033 given on the command line is a package name. The resulting executable
8034 will execute the elaboration routines of the package and its closure,
8035 then the finalization routines.
8037 @item @code{gcc} @asis{switches}
8038 @ifclear vms
8039 The switch @code{-g} or any uppercase switch (other than @code{-A},
8040 @code{-L} or
8041 @code{-S}) or any switch that is more than one character is passed to
8042 @code{gcc} (e.g. @code{-O}, @option{-gnato,} etc.)
8043 @end ifclear
8044 @ifset vms
8045 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8046 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8047 automatically treated as a compiler switch, and passed on to all
8048 compilations that are carried out.
8049 @end ifset
8050 @end table
8052 @noindent
8053 Source and library search path switches:
8055 @table @code
8056 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8057 @cindex @code{^-aI^/SOURCE_SEARCH^} (@code{gnatmake})
8058 When looking for source files also look in directory @var{dir}.
8059 The order in which source files search is undertaken is
8060 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8062 @item ^-aL^/SKIP_MISSING=^@var{dir}
8063 @cindex @code{^-aL^/SKIP_MISSING^} (@code{gnatmake})
8064 Consider @var{dir} as being an externally provided Ada library.
8065 Instructs @code{gnatmake} to skip compilation units whose @file{.ali}
8066 files have been located in directory @var{dir}. This allows you to have
8067 missing bodies for the units in @var{dir} and to ignore out of date bodies
8068 for the same units. You still need to specify
8069 the location of the specs for these units by using the switches
8070 @code{^-aI^/SOURCE_SEARCH=^@var{dir}}
8071 or @code{^-I^/SEARCH=^@var{dir}}.
8072 Note: this switch is provided for compatibility with previous versions
8073 of @code{gnatmake}. The easier method of causing standard libraries
8074 to be excluded from consideration is to write-protect the corresponding
8075 ALI files.
8077 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8078 @cindex @code{^-aO^/OBJECT_SEARCH^} (@code{gnatmake})
8079 When searching for library and object files, look in directory
8080 @var{dir}. The order in which library files are searched is described in
8081 @ref{Search Paths for gnatbind}.
8083 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8084 @cindex Search paths, for @code{gnatmake}
8085 @cindex @code{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@code{gnatmake})
8086 Equivalent to @code{^-aL^/SKIP_MISSING=^@var{dir}
8087 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8089 @item ^-I^/SEARCH=^@var{dir}
8090 @cindex @code{^-I^/SEARCH^} (@code{gnatmake})
8091 Equivalent to @code{^-aO^/OBJECT_SEARCH=^@var{dir}
8092 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8094 @item ^-I-^/NOCURRENT_DIRECTORY^
8095 @cindex @code{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatmake})
8096 @cindex Source files, suppressing search
8097 Do not look for source files in the directory containing the source
8098 file named in the command line.
8099 Do not look for ALI or object files in the directory
8100 where @code{gnatmake} was invoked.
8102 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8103 @cindex @code{^-L^/LIBRARY_SEARCH^} (@code{gnatmake})
8104 @cindex Linker libraries
8105 Add directory @var{dir} to the list of directories in which the linker
8106 @ifset wnt
8107 Furthermore, under Windows, the sources pointed to by the libraries path
8108 set in the registry are not searched for.
8109 @end ifset
8110 will search for libraries. This is equivalent to
8111 @code{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8113 @item -nostdinc
8114 @cindex @code{-nostdinc} (@code{gnatmake})
8115 Do not look for source files in the system default directory.
8117 @item -nostdlib
8118 @cindex @code{-nostdlib} (@code{gnatmake})
8119 Do not look for library files in the system default directory.
8121 @item --RTS=@var{rts-path}
8122 @cindex @code{--RTS} (@code{gnatmake})
8123 Specifies the default location of the runtime library. We look for the runtime
8124 in the following directories, and stop as soon as a valid runtime is found
8125 ("adainclude" or "ada_source_path", and "adalib" or "ada_object_path" present):
8127 @itemize @bullet
8128 @item <current directory>/$rts_path
8130 @item <default-search-dir>/$rts_path
8132 @item <default-search-dir>/rts-$rts_path
8133 @end itemize
8135 @noindent
8136 The selected path is handled like a normal RTS path.
8138 @end table
8140 @node Mode Switches for gnatmake
8141 @section Mode Switches for @code{gnatmake}
8143 @noindent
8144 The mode switches (referred to as @code{mode_switches}) allow the
8145 inclusion of switches that are to be passed to the compiler itself, the
8146 binder or the linker. The effect of a mode switch is to cause all
8147 subsequent switches up to the end of the switch list, or up to the next
8148 mode switch, to be interpreted as switches to be passed on to the
8149 designated component of GNAT.
8151 @table @code
8152 @item -cargs @var{switches}
8153 @cindex @code{-cargs} (@code{gnatmake})
8154 Compiler switches. Here @var{switches} is a list of switches
8155 that are valid switches for @code{gcc}. They will be passed on to
8156 all compile steps performed by @code{gnatmake}.
8158 @item -bargs @var{switches}
8159 @cindex @code{-bargs} (@code{gnatmake})
8160 Binder switches. Here @var{switches} is a list of switches
8161 that are valid switches for @code{gcc}. They will be passed on to
8162 all bind steps performed by @code{gnatmake}.
8164 @item -largs @var{switches}
8165 @cindex @code{-largs} (@code{gnatmake})
8166 Linker switches. Here @var{switches} is a list of switches
8167 that are valid switches for @code{gcc}. They will be passed on to
8168 all link steps performed by @code{gnatmake}.
8169 @end table
8171 @node Notes on the Command Line
8172 @section Notes on the Command Line
8174 @noindent
8175 This section contains some additional useful notes on the operation
8176 of the @code{gnatmake} command.
8178 @itemize @bullet
8179 @item
8180 @cindex Recompilation, by @code{gnatmake}
8181 If @code{gnatmake} finds no ALI files, it recompiles the main program
8182 and all other units required by the main program.
8183 This means that @code{gnatmake}
8184 can be used for the initial compile, as well as during subsequent steps of
8185 the development cycle.
8187 @item
8188 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8189 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8190 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8191 warning.
8193 @item
8194 In @code{gnatmake} the switch @code{^-I^/SEARCH^}
8195 is used to specify both source and
8196 library file paths. Use @code{^-aI^/SOURCE_SEARCH^}
8197 instead if you just want to specify
8198 source paths only and @code{^-aO^/OBJECT_SEARCH^}
8199 if you want to specify library paths
8200 only.
8202 @item
8203 @code{gnatmake} examines both an ALI file and its corresponding object file
8204 for consistency. If an ALI is more recent than its corresponding object,
8205 or if the object file is missing, the corresponding source will be recompiled.
8206 Note that @code{gnatmake} expects an ALI and the corresponding object file
8207 to be in the same directory.
8209 @item
8210 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8211 This may conveniently be used to exclude standard libraries from
8212 consideration and in particular it means that the use of the
8213 @code{^-f^/FORCE_COMPILE^} switch will not recompile these files
8214 unless @code{^-a^/ALL_FILES^} is also specified.
8216 @item
8217 @code{gnatmake} has been designed to make the use of Ada libraries
8218 particularly convenient. Assume you have an Ada library organized
8219 as follows: @var{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8220 of your Ada compilation units,
8221 whereas @var{^include-dir^[INCLUDE_DIR]^} contains the
8222 specs of these units, but no bodies. Then to compile a unit
8223 stored in @code{main.adb}, which uses this Ada library you would just type
8225 @smallexample
8226 @ifclear vms
8227 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8228 @end ifclear
8229 @ifset vms
8230 $ gnatmake /SOURCE_SEARCH=@var{[INCLUDE_DIR]}
8231            /SKIP_MISSING=@var{[OBJ_DIR]} main
8232 @end ifset
8233 @end smallexample
8235 @item
8236 Using @code{gnatmake} along with the
8237 @code{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8238 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8239 this switch,
8240 you can update the comments/format of your
8241 source files without having to recompile everything. Note, however, that
8242 adding or deleting lines in a source files may render its debugging
8243 info obsolete. If the file in question is a spec, the impact is rather
8244 limited, as that debugging info will only be useful during the
8245 elaboration phase of your program. For bodies the impact can be more
8246 significant. In all events, your debugger will warn you if a source file
8247 is more recent than the corresponding object, and alert you to the fact
8248 that the debugging information may be out of date.
8249 @end itemize
8251 @node How gnatmake Works
8252 @section How @code{gnatmake} Works
8254 @noindent
8255 Generally @code{gnatmake} automatically performs all necessary
8256 recompilations and you don't need to worry about how it works. However,
8257 it may be useful to have some basic understanding of the @code{gnatmake}
8258 approach and in particular to understand how it uses the results of
8259 previous compilations without incorrectly depending on them.
8261 First a definition: an object file is considered @dfn{up to date} if the
8262 corresponding ALI file exists and its time stamp predates that of the
8263 object file and if all the source files listed in the
8264 dependency section of this ALI file have time stamps matching those in
8265 the ALI file. This means that neither the source file itself nor any
8266 files that it depends on have been modified, and hence there is no need
8267 to recompile this file.
8269 @code{gnatmake} works by first checking if the specified main unit is up
8270 to date. If so, no compilations are required for the main unit. If not,
8271 @code{gnatmake} compiles the main program to build a new ALI file that
8272 reflects the latest sources. Then the ALI file of the main unit is
8273 examined to find all the source files on which the main program depends,
8274 and @code{gnatmake} recursively applies the above procedure on all these files.
8276 This process ensures that @code{gnatmake} only trusts the dependencies
8277 in an existing ALI file if they are known to be correct. Otherwise it
8278 always recompiles to determine a new, guaranteed accurate set of
8279 dependencies. As a result the program is compiled "upside down" from what may
8280 be more familiar as the required order of compilation in some other Ada
8281 systems. In particular, clients are compiled before the units on which
8282 they depend. The ability of GNAT to compile in any order is critical in
8283 allowing an order of compilation to be chosen that guarantees that
8284 @code{gnatmake} will recompute a correct set of new dependencies if
8285 necessary.
8287 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
8288 imported by several of the executables, it will be recompiled at most once.
8290 @node Examples of gnatmake Usage
8291 @section Examples of @code{gnatmake} Usage
8293 @table @code
8294 @item gnatmake hello.adb
8295 Compile all files necessary to bind and link the main program
8296 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8297 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8299 @item gnatmake main1 main2 main3
8300 Compile all files necessary to bind and link the main programs
8301 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8302 (containing unit @code{Main2}) and @file{main3.adb}
8303 (containing unit @code{Main3}) and bind and link the resulting object files
8304 to generate three executable files @file{^main1^MAIN1.EXE^},
8305 @file{^main2^MAIN2.EXE^}
8306 and @file{^main3^MAIN3.EXE^}.
8308 @ifclear vms
8309 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8310 @end ifclear
8312 @ifset vms
8313 @item gnatmake Main_Unit /QUIET /COMPILER_QUALIFIERS /OPTIMIZE=ALL /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8314 @end ifset
8315 Compile all files necessary to bind and link the main program unit
8316 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8317 be done with optimization level 2 and the order of elaboration will be
8318 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8319 displaying commands it is executing.
8320 @end table
8322 @node Renaming Files Using gnatchop
8323 @chapter Renaming Files Using @code{gnatchop}
8324 @findex gnatchop
8326 @noindent
8327 This chapter discusses how to handle files with multiple units by using
8328 the @code{gnatchop} utility. This utility is also useful in renaming
8329 files to meet the standard GNAT default file naming conventions.
8331 @menu
8332 * Handling Files with Multiple Units::
8333 * Operating gnatchop in Compilation Mode::
8334 * Command Line for gnatchop::
8335 * Switches for gnatchop::
8336 * Examples of gnatchop Usage::
8337 @end menu
8339 @node Handling Files with Multiple Units
8340 @section Handling Files with Multiple Units
8342 @noindent
8343 The basic compilation model of GNAT requires that a file submitted to the
8344 compiler have only one unit and there be a strict correspondence
8345 between the file name and the unit name.
8347 The @code{gnatchop} utility allows both of these rules to be relaxed,
8348 allowing GNAT to process files which contain multiple compilation units
8349 and files with arbitrary file names. @code{gnatchop}
8350 reads the specified file and generates one or more output files,
8351 containing one unit per file. The unit and the file name correspond,
8352 as required by GNAT.
8354 If you want to permanently restructure a set of "foreign" files so that
8355 they match the GNAT rules, and do the remaining development using the
8356 GNAT structure, you can simply use @code{gnatchop} once, generate the
8357 new set of files and work with them from that point on.
8359 Alternatively, if you want to keep your files in the "foreign" format,
8360 perhaps to maintain compatibility with some other Ada compilation
8361 system, you can set up a procedure where you use @code{gnatchop} each
8362 time you compile, regarding the source files that it writes as temporary
8363 files that you throw away.
8365 @node Operating gnatchop in Compilation Mode
8366 @section Operating gnatchop in Compilation Mode
8368 @noindent
8369 The basic function of @code{gnatchop} is to take a file with multiple units
8370 and split it into separate files. The boundary between files is reasonably
8371 clear, except for the issue of comments and pragmas. In default mode, the
8372 rule is that any pragmas between units belong to the previous unit, except
8373 that configuration pragmas always belong to the following unit. Any comments
8374 belong to the following unit. These rules
8375 almost always result in the right choice of
8376 the split point without needing to mark it explicitly and most users will
8377 find this default to be what they want. In this default mode it is incorrect to
8378 submit a file containing only configuration pragmas, or one that ends in
8379 configuration pragmas, to @code{gnatchop}.
8381 However, using a special option to activate "compilation mode",
8382 @code{gnatchop}
8383 can perform another function, which is to provide exactly the semantics
8384 required by the RM for handling of configuration pragmas in a compilation.
8385 In the absence of configuration pragmas (at the main file level), this
8386 option has no effect, but it causes such configuration pragmas to be handled
8387 in a quite different manner.
8389 First, in compilation mode, if @code{gnatchop} is given a file that consists of
8390 only configuration pragmas, then this file is appended to the
8391 @file{gnat.adc} file in the current directory. This behavior provides
8392 the required behavior described in the RM for the actions to be taken
8393 on submitting such a file to the compiler, namely that these pragmas
8394 should apply to all subsequent compilations in the same compilation
8395 environment. Using GNAT, the current directory, possibly containing a
8396 @file{gnat.adc} file is the representation
8397 of a compilation environment. For more information on the
8398 @file{gnat.adc} file, see the section on handling of configuration
8399 pragmas @pxref{Handling of Configuration Pragmas}.
8401 Second, in compilation mode, if @code{gnatchop}
8402 is given a file that starts with
8403 configuration pragmas, and contains one or more units, then these
8404 configuration pragmas are prepended to each of the chopped files. This
8405 behavior provides the required behavior described in the RM for the
8406 actions to be taken on compiling such a file, namely that the pragmas
8407 apply to all units in the compilation, but not to subsequently compiled
8408 units.
8410 Finally, if configuration pragmas appear between units, they are appended
8411 to the previous unit. This results in the previous unit being illegal,
8412 since the compiler does not accept configuration pragmas that follow
8413 a unit. This provides the required RM behavior that forbids configuration
8414 pragmas other than those preceding the first compilation unit of a
8415 compilation.
8417 For most purposes, @code{gnatchop} will be used in default mode. The
8418 compilation mode described above is used only if you need exactly
8419 accurate behavior with respect to compilations, and you have files
8420 that contain multiple units and configuration pragmas. In this
8421 circumstance the use of @code{gnatchop} with the compilation mode
8422 switch provides the required behavior, and is for example the mode
8423 in which GNAT processes the ACVC tests.
8425 @node Command Line for gnatchop
8426 @section Command Line for @code{gnatchop}
8428 @noindent
8429 The @code{gnatchop} command has the form:
8431 @smallexample
8432 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
8433       [@var{directory}]
8434 @end smallexample
8436 @noindent
8437 The only required argument is the file name of the file to be chopped.
8438 There are no restrictions on the form of this file name. The file itself
8439 contains one or more Ada units, in normal GNAT format, concatenated
8440 together. As shown, more than one file may be presented to be chopped.
8442 When run in default mode, @code{gnatchop} generates one output file in
8443 the current directory for each unit in each of the files.
8445 @var{directory}, if specified, gives the name of the directory to which
8446 the output files will be written. If it is not specified, all files are
8447 written to the current directory.
8449 For example, given a
8450 file called @file{hellofiles} containing
8452 @smallexample
8453 @group
8454 @cartouche
8455 @b{procedure} hello;
8457 @b{with} Text_IO; @b{use} Text_IO;
8458 @b{procedure} hello @b{is}
8459 @b{begin}
8460    Put_Line ("Hello");
8461 @b{end} hello;
8462 @end cartouche
8463 @end group
8464 @end smallexample
8466 @noindent
8467 the command
8469 @smallexample
8470 $ gnatchop ^hellofiles^HELLOFILES.^
8471 @end smallexample
8473 @noindent
8474 generates two files in the current directory, one called
8475 @file{hello.ads} containing the single line that is the procedure spec,
8476 and the other called @file{hello.adb} containing the remaining text. The
8477 original file is not affected. The generated files can be compiled in
8478 the normal manner.
8480 @node Switches for gnatchop
8481 @section Switches for @code{gnatchop}
8483 @noindent
8484 @code{gnatchop} recognizes the following switches:
8486 @table @code
8488 @item ^-c^/COMPILATION^
8489 @cindex @code{^-c^/COMPILATION^} (@code{gnatchop})
8490 Causes @code{gnatchop} to operate in compilation mode, in which
8491 configuration pragmas are handled according to strict RM rules. See
8492 previous section for a full description of this mode.
8494 @ifclear vms
8495 @item -gnatxxx
8496 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
8497 used to parse the given file. Not all @code{xxx} options make sense,
8498 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
8499 process a source file that uses Latin-2 coding for identifiers.
8500 @end ifclear
8502 @item ^-h^/HELP^
8503 Causes @code{gnatchop} to generate a brief help summary to the standard
8504 output file showing usage information.
8506 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
8507 @cindex @code{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
8508 Limit generated file names to the specified number @code{mm}
8509 of characters.
8510 This is useful if the
8511 resulting set of files is required to be interoperable with systems
8512 which limit the length of file names.
8513 @ifset vms
8514 If no value is given, or
8515 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
8516 a default of 39, suitable for OpenVMS Alpha
8517 Systems, is assumed
8518 @end ifset
8519 @ifclear vms
8520 No space is allowed between the @code{-k} and the numeric value. The numeric
8521 value may be omitted in which case a default of @code{-k8},
8522 suitable for use
8523 with DOS-like file systems, is used. If no @code{-k} switch
8524 is present then
8525 there is no limit on the length of file names.
8526 @end ifclear
8528 @item ^-p^/PRESERVE^
8529 @cindex @code{^-p^/PRESERVE^} (@code{gnatchop})
8530 Causes the file ^modification^creation^ time stamp of the input file to be
8531 preserved and used for the time stamp of the output file(s). This may be
8532 useful for preserving coherency of time stamps in an enviroment where
8533 @code{gnatchop} is used as part of a standard build process.
8535 @item ^-q^/QUIET^
8536 @cindex @code{^-q^/QUIET^} (@code{gnatchop})
8537 Causes output of informational messages indicating the set of generated
8538 files to be suppressed. Warnings and error messages are unaffected.
8540 @item ^-r^/REFERENCE^
8541 @cindex @code{^-r^/REFERENCE^} (@code{gnatchop})
8542 @findex Source_Reference
8543 Generate @code{Source_Reference} pragmas. Use this switch if the output
8544 files are regarded as temporary and development is to be done in terms
8545 of the original unchopped file. This switch causes
8546 @code{Source_Reference} pragmas to be inserted into each of the
8547 generated files to refers back to the original file name and line number.
8548 The result is that all error messages refer back to the original
8549 unchopped file.
8550 In addition, the debugging information placed into the object file (when
8551 the @code{^-g^/DEBUG^} switch of @code{gcc} or @code{gnatmake} is specified) also
8552 refers back to this original file so that tools like profilers and
8553 debuggers will give information in terms of the original unchopped file.
8555 If the original file to be chopped itself contains
8556 a @code{Source_Reference}
8557 pragma referencing a third file, then gnatchop respects
8558 this pragma, and the generated @code{Source_Reference} pragmas
8559 in the chopped file refer to the original file, with appropriate
8560 line numbers. This is particularly useful when @code{gnatchop}
8561 is used in conjunction with @code{gnatprep} to compile files that
8562 contain preprocessing statements and multiple units.
8564 @item ^-v^/VERBOSE^
8565 @cindex @code{^-v^/VERBOSE^} (@code{gnatchop})
8566 Causes @code{gnatchop} to operate in verbose mode. The version
8567 number and copyright notice are output, as well as exact copies of
8568 the gnat1 commands spawned to obtain the chop control information.
8570 @item ^-w^/OVERWRITE^
8571 @cindex @code{^-w^/OVERWRITE^} (@code{gnatchop})
8572 Overwrite existing file names. Normally @code{gnatchop} regards it as a
8573 fatal error if there is already a file with the same name as a
8574 file it would otherwise output, in other words if the files to be
8575 chopped contain duplicated units. This switch bypasses this
8576 check, and causes all but the last instance of such duplicated
8577 units to be skipped.
8579 @ifclear vms
8580 @item --GCC=xxxx
8581 @cindex @code{--GCC=} (@code{gnatchop})
8582 Specify the path of the GNAT parser to be used. When this switch is used,
8583 no attempt is made to add the prefix to the GNAT parser executable.
8584 @end ifclear
8585 @end table
8587 @node Examples of gnatchop Usage
8588 @section Examples of @code{gnatchop} Usage
8590 @table @code
8591 @ifset vms
8592 @item gnatchop /OVERWRITE HELLO_S.ADA [ICHBIAH.FILES]
8593 @end ifset
8594 @ifclear vms
8595 @item gnatchop -w hello_s.ada ichbiah/files
8596 @end ifclear
8598 Chops the source file @file{hello_s.ada}. The output files will be
8599 placed in the directory @file{^ichbiah/files^[ICHBIAH.FILES]^},
8600 overwriting any
8601 files with matching names in that directory (no files in the current
8602 directory are modified).
8604 @item gnatchop ^archive^ARCHIVE.^
8605 Chops the source file @file{^archive^ARCHIVE.^}
8606 into the current directory. One
8607 useful application of @code{gnatchop} is in sending sets of sources
8608 around, for example in email messages. The required sources are simply
8609 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
8610 command), and then
8611 @code{gnatchop} is used at the other end to reconstitute the original
8612 file names.
8614 @item gnatchop file1 file2 file3 direc
8615 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
8616 the resulting files in the directory @file{direc}. Note that if any units
8617 occur more than once anywhere within this set of files, an error message
8618 is generated, and no files are written. To override this check, use the
8619 @code{^-w^/OVERWRITE^} switch,
8620 in which case the last occurrence in the last file will
8621 be the one that is output, and earlier duplicate occurrences for a given
8622 unit will be skipped.
8623 @end table
8625 @node Configuration Pragmas
8626 @chapter Configuration Pragmas
8627 @cindex Configuration pragmas
8628 @cindex Pragmas, configuration
8630 @noindent
8631 In Ada 95, configuration pragmas include those pragmas described as
8632 such in the Ada 95 Reference Manual, as well as
8633 implementation-dependent pragmas that are configuration pragmas. See the
8634 individual descriptions of pragmas in the GNAT Reference Manual for
8635 details on these additional GNAT-specific configuration pragmas. Most
8636 notably, the pragma @code{Source_File_Name}, which allows
8637 specifying non-default names for source files, is a configuration
8638 pragma. The following is a complete list of configuration pragmas
8639 recognized by @code{GNAT}:
8641 @smallexample
8642    Ada_83
8643    Ada_95
8644    C_Pass_By_Copy
8645    Component_Alignment
8646    Discard_Names
8647    Elaboration_Checks
8648    Eliminate
8649    Extend_System
8650    Extensions_Allowed
8651    External_Name_Casing
8652    Float_Representation
8653    Initialize_Scalars
8654    License
8655    Locking_Policy
8656    Long_Float
8657    No_Run_Time
8658    Normalize_Scalars
8659    Polling
8660    Propagate_Exceptions
8661    Queuing_Policy
8662    Ravenscar
8663    Restricted_Run_Time
8664    Restrictions
8665    Reviewable
8666    Source_File_Name
8667    Style_Checks
8668    Suppress
8669    Task_Dispatching_Policy
8670    Unsuppress
8671    Use_VADS_Size
8672    Warnings
8673    Validity_Checks
8674 @end smallexample
8676 @menu
8677 * Handling of Configuration Pragmas::
8678 * The Configuration Pragmas Files::
8679 @end menu
8681 @node Handling of Configuration Pragmas
8682 @section Handling of Configuration Pragmas
8684 Configuration pragmas may either appear at the start of a compilation
8685 unit, in which case they apply only to that unit, or they may apply to
8686 all compilations performed in a given compilation environment.
8688 GNAT also provides the @code{gnatchop} utility to provide an automatic
8689 way to handle configuration pragmas following the semantics for
8690 compilations (that is, files with multiple units), described in the RM.
8691 See section @pxref{Operating gnatchop in Compilation Mode} for details.
8692 However, for most purposes, it will be more convenient to edit the
8693 @file{gnat.adc} file that contains configuration pragmas directly,
8694 as described in the following section.
8696 @node The Configuration Pragmas Files
8697 @section The Configuration Pragmas Files
8698 @cindex @file{gnat.adc}
8700 @noindent
8701 In GNAT a compilation environment is defined by the current
8702 directory at the time that a compile command is given. This current
8703 directory is searched for a file whose name is @file{gnat.adc}. If
8704 this file is present, it is expected to contain one or more
8705 configuration pragmas that will be applied to the current compilation.
8706 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
8707 considered.
8709 Configuration pragmas may be entered into the @file{gnat.adc} file
8710 either by running @code{gnatchop} on a source file that consists only of
8711 configuration pragmas, or more conveniently  by
8712 direct editing of the @file{gnat.adc} file, which is a standard format
8713 source file.
8715 In addition to @file{gnat.adc}, one additional file containing configuration
8716 pragmas may be applied to the current compilation using the switch
8717 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
8718 contains only configuration pragmas. These configuration pragmas are
8719 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
8720 is present and switch @option{-gnatA} is not used).
8722 It is allowed to specify several switches @option{-gnatec}, however only
8723 the last one on the command line will be taken into account.
8725 @ifset vms
8726 Of special interest to GNAT OpenVMS Alpha is the following configuration pragma:
8728 @smallexample
8729 @cartouche
8730 @b{pragma} Extend_System (Aux_DEC);
8731 @end cartouche
8732 @end smallexample
8734 @noindent
8735 In the presence of this pragma, GNAT adds to the definition of the
8736 predefined package SYSTEM all the additional types and subprograms that are
8737 defined in DEC Ada. See @pxref{Compatibility with DEC Ada} for details.
8738 @end ifset
8740 @node Handling Arbitrary File Naming Conventions Using gnatname
8741 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
8742 @cindex Arbitrary File Naming Conventions
8744 @menu
8745 * Arbitrary File Naming Conventions::
8746 * Running gnatname::
8747 * Switches for gnatname::
8748 * Examples of gnatname Usage::
8749 @end menu
8751 @node Arbitrary File Naming Conventions
8752 @section Arbitrary File Naming Conventions
8754 @noindent
8755 The GNAT compiler must be able to know the source file name of a compilation unit.
8756 When using the standard GNAT default file naming conventions (@code{.ads} for specs,
8757 @code{.adb} for bodies), the GNAT compiler does not need additional information.
8759 @noindent
8760 When the source file names do not follow the standard GNAT default file naming
8761 conventions, the GNAT compiler must be given additional information through
8762 a configuration pragmas file (see @ref{Configuration Pragmas}) or a project file.
8763 When the non standard file naming conventions are well-defined, a small number of
8764 pragmas @code{Source_File_Name} specifying a naming pattern
8765 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
8766 if the file naming conventions are irregular or arbitrary, a number
8767 of pragma @code{Source_File_Name} for individual compilation units must be defined.
8768 To help maintain the correspondence between compilation unit names and
8769 source file names within the compiler,
8770 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
8771 set of files.
8773 @node Running gnatname
8774 @section Running @code{gnatname}
8776 @noindent
8777 The usual form of the @code{gnatname} command is
8779 @smallexample
8780 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
8781 @end smallexample
8783 @noindent
8784 All of the arguments are optional. If invoked without any argument,
8785 @code{gnatname} will display its usage.
8787 @noindent
8788 When used with at least one naming pattern, @code{gnatname} will attempt to
8789 find all the compilation units in files that follow at least one of the
8790 naming patterns. To find these compilation units,
8791 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
8792 regular files.
8794 @noindent
8795 One or several Naming Patterns may be given as arguments to @code{gnatname}.
8796 Each Naming Pattern is enclosed between double quotes.
8797 A Naming Pattern is a regular expression similar to the wildcard patterns
8798 used in file names by the Unix shells or the DOS prompt.
8800 @noindent
8801 Examples of Naming Patterns are
8803 @smallexample
8804    "*.[12].ada"
8805    "*.ad[sb]*"
8806    "body_*"    "spec_*"
8807 @end smallexample
8809 @noindent
8810 For a more complete description of the syntax of Naming Patterns, see the second kind
8811 of regular expressions described in @file{g-regexp.ads} (the "Glob" regular
8812 expressions).
8814 @noindent
8815 When invoked with no switches, @code{gnatname} will create a configuration
8816 pragmas file @file{gnat.adc} in the current working directory, with pragmas
8817 @code{Source_File_Name} for each file that contains a valid Ada unit.
8819 @node Switches for gnatname
8820 @section Switches for @code{gnatname}
8822 @noindent
8823 Switches for @code{gnatname} must precede any specified Naming Pattern.
8825 @noindent
8826 You may specify any of the following switches to @code{gnatname}:
8828 @table @code
8830 @item -c@file{file}
8831 @cindex @code{-c} (@code{gnatname})
8832 Create a configuration pragmas file @file{file} (instead of the default
8833 @file{gnat.adc}). There may be zero, one or more space between @code{-c} and
8834 @file{file}. @file{file} may include directory information. @file{file} must be
8835 writeable. There may be only one switch @code{-c}. When a switch @code{-c} is
8836 specified, no switch @code{-P} may be specified (see below).
8838 @item -d@file{dir}
8839 @cindex @code{-d} (@code{gnatname})
8840 Look for source files in directory @file{dir}. There may be zero, one or more spaces
8841 between @code{-d} and @file{dir}. When a switch @code{-d} is specified,
8842 the current working directory will not be searched for source files, unless it
8843 is explictly
8844 specified with a @code{-d} or @code{-D} switch. Several switches @code{-d} may be
8845 specified. If @file{dir} is a relative path, it is relative to the directory of
8846 the configuration pragmas file specified with switch @code{-c}, or to the directory
8847 of the project file specified with switch @code{-P} or, if neither switch @code{-c}
8848 nor switch @code{-P} are specified, it is relative to the current working
8849 directory. The directory
8850 specified with switch @code{-c} must exist and be readable.
8852 @item -D@file{file}
8853 @cindex @code{-D} (@code{gnatname})
8854 Look for source files in all directories listed in text file @file{file}. There may be
8855 zero, one or more spaces between @code{-d} and @file{dir}. @file{file}
8856 must be an existing, readable text file. Each non empty line in @file{file} must be
8857 a directory. Specifying switch @code{-D} is equivalent to specifying as many switches
8858 @code{-d} as there are non empty lines in @file{file}.
8860 @item -h
8861 @cindex @code{-h} (@code{gnatname})
8862 Output usage (help) information. The output is written to @file{stdout}.
8864 @item -P@file{proj}
8865 @cindex @code{-P} (@code{gnatname})
8866 Create or update project file @file{proj}. There may be zero, one or more space
8867 between @code{-P} and @file{proj}. @file{proj} may include directory information.
8868 @file{proj} must be writeable. There may be only one switch @code{-P}.
8869 When a switch @code{-P} is specified, no switch @code{-c} may be specified.
8871 @item -v
8872 @cindex @code{-v} (@code{gnatname})
8873 Verbose mode. Output detailed explanation of behavior to @file{stdout}. This includes
8874 name of the file written, the name of the directories to search and, for each file
8875 in those directories whose name matches at least one of the Naming Patterns, an
8876 indication of whether the file contains a unit, and if so the name of the unit.
8878 @item -v -v
8879 Very Verbose mode. In addition to the output produced in verbose mode, for each file
8880 in the searched directories whose name matches none of the Naming Patterns, an
8881 indication is given that there is no match.
8883 @item -x@file{pattern}
8884 Excluded patterns. Using this switch, it is possible to exclude some files
8885 that would match the name patterns. For example,
8886 @code{"gnatname -x "*_nt.ada" "*.ada"} will look for Ada units in all files
8887 with the @file{.ada} extension, except those whose names end with
8888 @file{_nt.ada}.
8890 @end table
8892 @node Examples of gnatname Usage
8893 @section Examples of @code{gnatname} Usage
8895 @smallexample
8896 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
8897 @end smallexample
8899 In this example, the directory @file{/home/me} must already exist and be
8900 writeable. In addition, the directory @file{/home/me/sources} (specified by
8901 @code{-d sources}) must exist and be readable. Note the optional spaces after
8902 @code{-c} and @code{-d}.
8904 @smallexample
8905 $ gnatname -P/home/me/proj -x "*_nt_body.ada" -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
8906 @end smallexample
8908 Note that several switches @code{-d} may be used, even in conjunction with one
8909 or several switches @code{-D}. Several Naming Patterns and one excluded pattern
8910 are used in this example.
8913 @c *****************************************
8914 @c * G N A T  P r o j e c t  M a n a g e r *
8915 @c *****************************************
8916 @node GNAT Project Manager
8917 @chapter GNAT Project Manager
8919 @menu
8920 * Introduction::
8921 * Examples of Project Files::
8922 * Project File Syntax::
8923 * Objects and Sources in Project Files::
8924 * Importing Projects::
8925 * Project Extension::
8926 * External References in Project Files::
8927 * Packages in Project Files::
8928 * Variables from Imported Projects::
8929 * Naming Schemes::
8930 * Library Projects::
8931 * Switches Related to Project Files::
8932 * Tools Supporting Project Files::
8933 * An Extended Example::
8934 * Project File Complete Syntax::
8935 @end menu
8938 @c ****************
8939 @c * Introduction *
8940 @c ****************
8942 @node Introduction
8943 @section Introduction
8945 @noindent
8946 This chapter describes GNAT's @emph{Project Manager}, a facility that
8947 lets you configure various properties for a collection of source files.  In
8948 particular, you can specify:
8949 @itemize @bullet
8950 @item
8951 The directory or set of directories containing the source files, and/or the
8952 names of the specific source files themselves
8953 @item
8954 The directory in which the compiler's output
8955 (@file{ALI} files, object files, tree files) will be placed
8956 @item
8957 The directory in which the executable programs will be placed
8958 @item
8959 Switch settings for any of the project-enabled tools (@command{gnatmake},
8960 compiler, binder, linker, @code{gnatls}, @code{gnatxref}, @code{gnatfind});
8961 you can apply these settings either globally or to individual units
8962 @item
8963 The source files containing the main subprogram(s) to be built
8964 @item
8965 The source programming language(s) (currently Ada and/or C)
8966 @item
8967 Source file naming conventions; you can specify these either globally or for
8968 individual units
8969 @end itemize
8971 @menu
8972 * Project Files::
8973 @end menu
8975 @node Project Files
8976 @subsection Project Files
8978 @noindent
8979 A @dfn{project} is a specific set of values for these properties.  You can
8980 define a project's settings in a @dfn{project file}, a text file with an
8981 Ada-like syntax; a property value is either a string or a list of strings.
8982 Properties that are not explicitly set receive default values.  A project
8983 file may interrogate the values of @dfn{external variables} (user-defined
8984 command-line switches or environment variables), and it may specify property
8985 settings conditionally, based on the value of such variables.
8987 In simple cases, a project's source files depend only on other source files
8988 in the same project, or on the predefined libraries.  ("Dependence" is in
8989 the technical sense; for example, one Ada unit "with"ing another.)  However,
8990 the Project Manager also allows much more sophisticated arrangements,
8991 with the source files in one project depending on source files in other
8992 projects:
8993 @itemize @bullet
8994 @item
8995 One project can @emph{import} other projects containing needed source files.
8996 @item
8997 You can organize GNAT projects in a hierarchy: a @emph{child} project
8998 can extend a @emph{parent} project, inheriting the parent's source files and
8999 optionally overriding any of them with alternative versions
9000 @end itemize
9002 @noindent
9003 More generally, the Project Manager lets you structure large development
9004 efforts into hierarchical subsystems, with build decisions deferred to the
9005 subsystem level and thus different compilation environments (switch settings)
9006 used for different subsystems.
9008 The Project Manager is invoked through the @option{-P@emph{projectfile}}
9009 switch to @command{gnatmake} or to the @command{gnat} front driver.
9010 If you want to define (on the command line) an external variable that is
9011 queried by the project file, additionally use the
9012 @option{-X@emph{vbl}=@emph{value}} switch.
9013 The Project Manager parses and interprets the project file, and drives the
9014 invoked tool based on the project settings.
9016 The Project Manager supports a wide range of development strategies,
9017 for systems of all sizes.  Some typical practices that are easily handled:
9018 @itemize @bullet
9019 @item
9020 Using a common set of source files, but generating object files in different
9021 directories via different switch settings
9022 @item
9023 Using a mostly-shared set of source files, but with different versions of
9024 some unit or units
9025 @end itemize
9027 @noindent
9028 The destination of an executable can be controlled inside a project file
9029 using the @option{-o} switch. In the absence of such a switch either inside
9030 the project file or on the command line, any executable files generated by
9031 @command{gnatmake} will be placed in the directory @code{Exec_Dir} specified
9032 in the project file. If no @code{Exec_Dir} is specified, they will be placed
9033 in the object directory of the project.
9035 You can use project files to achieve some of the effects of a source
9036 versioning system (for example, defining separate projects for
9037 the different sets of sources that comprise different releases) but the
9038 Project Manager is independent of any source configuration management tools
9039 that might be used by the developers.
9041 The next section introduces the main features of GNAT's project facility
9042 through a sequence of examples; subsequent sections will present the syntax
9043 and semantics in more detail.
9046 @c *****************************
9047 @c * Examples of Project Files *
9048 @c *****************************
9050 @node Examples of Project Files
9051 @section Examples of Project Files
9052 @noindent
9053 This section illustrates some of the typical uses of project files and
9054 explains their basic structure and behavior.
9056 @menu
9057 * Common Sources with Different Switches and Different Output Directories::
9058 * Using External Variables::
9059 * Importing Other Projects::
9060 * Extending a Project::
9061 @end menu
9063 @node Common Sources with Different Switches and Different Output Directories
9064 @subsection Common Sources with Different Switches and Different Output Directories
9066 @menu
9067 * Source Files::
9068 * Specifying the Object Directory::
9069 * Specifying the Exec Directory::
9070 * Project File Packages::
9071 * Specifying Switch Settings::
9072 * Main Subprograms::
9073 * Source File Naming Conventions::
9074 * Source Language(s)::
9075 @end menu
9077 @noindent
9078 Assume that the Ada source files @file{pack.ads}, @file{pack.adb}, and
9079 @file{proc.adb} are in the @file{/common} directory.  The file
9080 @file{proc.adb} contains an Ada main subprogram @code{Proc} that "with"s
9081 package @code{Pack}.  We want to compile these source files under two sets
9082 of switches:
9083 @itemize @bullet
9084 @item
9085 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
9086 and the @option{-gnata}, @option{-gnato}, and @option{-gnatE} switches to the
9087 compiler; the compiler's output is to appear in @file{/common/debug}
9088 @item
9089 When preparing a release version, we want to pass the @option{-O2} switch to
9090 the compiler; the compiler's output is to appear in @file{/common/release}
9091 @end itemize
9093 @noindent
9094 The GNAT project files shown below, respectively @file{debug.gpr} and
9095 @file{release.gpr} in the @file{/common} directory, achieve these effects.
9097 Diagrammatically:
9098 @smallexample
9099 @group
9100 /common
9101   debug.gpr
9102   release.gpr
9103   pack.ads
9104   pack.adb
9105   proc.adb
9106 @end group
9107 @group
9108 /common/debug @{-g, -gnata, -gnato, -gnatE@}
9109   proc.ali, proc.o
9110   pack.ali, pack.o
9111 @end group
9112 @group
9113 /common/release @{-O2@}
9114   proc.ali, proc.o
9115   pack.ali, pack.o
9116 @end group
9117 @end smallexample
9118 Here are the project files:
9119 @smallexample
9120 @group
9121 project Debug is
9122   for Object_Dir use "debug";
9123   for Main use ("proc");
9125   package Builder is
9126     for Default_Switches ("Ada") use ("-g");
9127   end Builder;
9128 @end group
9130 @group
9131   package Compiler is
9132     for Default_Switches ("Ada")
9133        use ("-fstack-check", "-gnata", "-gnato", "-gnatE");
9134   end Compiler;
9135 end Debug;
9136 @end group
9137 @end smallexample
9139 @smallexample
9140 @group
9141 project Release is
9142   for Object_Dir use "release";
9143   for Exec_Dir use ".";
9144   for Main use ("proc");
9146   package Compiler is
9147     for Default_Switches ("Ada") use ("-O2");
9148   end Compiler;
9149 end Release;
9150 @end group
9151 @end smallexample
9153 @noindent
9154 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
9155 insensitive), and analogously the project defined by @file{release.gpr} is
9156 @code{"Release"}.  For consistency the file should have the same name as the
9157 project, and the project file's extension should be @code{"gpr"}. These
9158 conventions are not required, but a warning is issued if they are not followed.
9160 If the current directory is @file{/temp}, then the command
9161 @smallexample
9162 gnatmake -P/common/debug.gpr
9163 @end smallexample
9165 @noindent
9166 generates object and ALI files in @file{/common/debug}, and the @code{proc}
9167 executable also in @file{/common/debug}, using the switch settings defined in
9168 the project file.
9170 Likewise, the command
9171 @smallexample
9172 gnatmake -P/common/release.gpr
9173 @end smallexample
9175 @noindent
9176 generates object and ALI files in @file{/common/release}, and the @code{proc}
9177 executable in @file{/common}, using the switch settings from the project file.
9179 @node Source Files
9180 @unnumberedsubsubsec Source Files
9182 @noindent
9183 If a project file does not explicitly specify a set of source directories or
9184 a set of source files, then by default the project's source files are the
9185 Ada source files in the project file directory.  Thus @file{pack.ads},
9186 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
9188 @node Specifying the Object Directory
9189 @unnumberedsubsubsec Specifying the Object Directory
9191 @noindent
9192 Several project properties are modeled by Ada-style @emph{attributes};
9193 you define the property by supplying the equivalent of an Ada attribute
9194 definition clause in the project file.
9195 A project's object directory is such a property; the corresponding
9196 attribute is @code{Object_Dir}, and its value is a string expression.  A
9197 directory may be specified either as absolute or as relative; in the latter
9198 case, it is relative to the project file directory.  Thus the compiler's
9199 output is directed to @file{/common/debug} (for the @code{Debug} project)
9200 and to @file{/common/release} (for the @code{Release} project).  If
9201 @code{Object_Dir} is not specified, then the default is the project file
9202 directory.
9204 @node Specifying the Exec Directory
9205 @unnumberedsubsubsec Specifying the Exec Directory
9207 @noindent
9208 A project's exec directory is another property; the corresponding
9209 attribute is @code{Exec_Dir}, and its value is also a string expression,
9210 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
9211 then the default is the object directory (which may also be the project file
9212 directory if attribute @code{Object_Dir} is not specified). Thus the executable
9213 is placed in @file{/common/debug} for the @code{Debug} project (attribute
9214 @code{Exec_Dir} not specified) and in @file{/common} for the @code{Release}
9215 project.
9217 @node Project File Packages
9218 @unnumberedsubsubsec Project File Packages
9220 @noindent
9221 A GNAT tool integrated with the Project Manager is modeled by a
9222 corresponding package in the project file.
9223 The @code{Debug} project defines the packages @code{Builder}
9224 (for @command{gnatmake}) and @code{Compiler};
9225 the @code{Release} project defines only the @code{Compiler} package.
9227 The Ada package syntax is not to be taken literally.  Although packages in
9228 project files bear a surface resemblance to packages in Ada source code, the
9229 notation is simply a way to convey a grouping of properties for a named
9230 entity.  Indeed, the package names permitted in project files are restricted
9231 to a predefined set, corresponding to the project-aware tools, and the contents
9232 of packages are limited to a small set of constructs.
9233 The packages in the example above contain attribute definitions.
9236 @node Specifying Switch Settings
9237 @unnumberedsubsubsec Specifying Switch Settings
9239 @noindent
9240 Switch settings for a project-aware tool can be specified through attributes
9241 in the package corresponding to the tool.
9242 The example above illustrates one of the relevant attributes,
9243 @code{Default_Switches}, defined in the packages in both project files.
9244 Unlike simple attributes like @code{Source_Dirs}, @code{Default_Switches} is
9245 known as an @emph{associative array}.  When you define this attribute, you must
9246 supply an "index" (a literal string), and the effect of the attribute
9247 definition is to set the value of the "array" at the specified "index".
9248 For the @code{Default_Switches} attribute, the index is a programming
9249 language (in our case, Ada) , and the value specified (after @code{use})
9250 must be a list of string expressions.
9252 The attributes permitted in project files are restricted to a predefined set.
9253 Some may appear at project level, others in packages.
9254 For any attribute that is an associate array, the index must always be a
9255 literal string, but the restrictions on this string (e.g., a file name or a
9256 language name) depend on the individual attribute.
9257 Also depending on the attribute, its specified value will need to be either a
9258 string or a string list.
9260 In the @code{Debug} project, we set the switches for two tools,
9261 @command{gnatmake} and the compiler, and thus we include corresponding
9262 packages, with each package defining the @code{Default_Switches} attribute
9263 with index @code{"Ada"}.
9264 Note that the package corresponding to
9265 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
9266 similar, but with just the @code{Compiler} package.
9268 In project @code{Debug} above the switches starting with @option{-gnat} that
9269 are specified in package @code{Compiler} could have been placed in package
9270 @code{Builder}, since @command{gnatmake} transmits all such switches to the
9271 compiler.
9273 @node Main Subprograms
9274 @unnumberedsubsubsec Main Subprograms
9276 @noindent
9277 One of the properties of a project is its list of main subprograms (actually
9278 a list of names of source files containing main subprograms, with the file
9279 extension optional.  This property is captured in the @code{Main} attribute,
9280 whose value is a list of strings.  If a project defines the @code{Main}
9281 attribute, then you do not need to identify the main subprogram(s) when
9282 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
9284 @node Source File Naming Conventions
9285 @unnumberedsubsubsec Source File Naming Conventions
9287 @noindent
9288 Since the project files do not specify any source file naming conventions,
9289 the GNAT defaults are used.  The mechanism for defining source file naming
9290 conventions -- a package named @code{Naming} -- will be described below
9291 (@pxref{Naming Schemes}).
9293 @node Source Language(s)
9294 @unnumberedsubsubsec Source Language(s)
9296 @noindent
9297 Since the project files do not specify a @code{Languages} attribute, by
9298 default the GNAT tools assume that the language of the project file is Ada.
9299 More generally, a project can comprise source files
9300 in Ada, C, and/or other languages.
9302 @node Using External Variables
9303 @subsection Using External Variables
9305 @noindent
9306 Instead of supplying different project files for debug and release, we can
9307 define a single project file that queries an external variable (set either
9308 on the command line or via an environment variable) in order to
9309 conditionally define the appropriate settings.  Again, assume that the
9310 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
9311 located in directory @file{/common}.  The following project file,
9312 @file{build.gpr}, queries the external variable named @code{STYLE} and
9313 defines an object directory and switch settings based on whether the value
9314 is @code{"deb"} (debug) or @code{"rel"} (release), where the default is
9315 @code{"deb"}.
9317 @smallexample
9318 @group
9319 project Build is
9320   for Main use ("proc");
9322   type Style_Type is ("deb", "rel");
9323   Style : Style_Type := external ("STYLE", "deb");
9325   case Style is
9326     when "deb" =>
9327       for Object_Dir use "debug";
9329     when "rel" =>
9330       for Object_Dir use "release";
9331       for Exec_Dir use ".";
9332   end case;
9333 @end group
9335 @group
9336   package Builder is
9338     case Style is
9339       when "deb" =>
9340         for Default_Switches ("Ada") use ("-g");
9341     end case;
9343   end Builder;
9344 @end group
9346 @group
9347   package Compiler is
9349     case Style is
9350       when "deb" =>
9351         for Default_Switches ("Ada") use ("-gnata", "-gnato", "-gnatE");
9353       when "rel" =>
9354         for Default_Switches ("Ada") use ("-O2");
9355     end case;
9357   end Compiler;
9359 end Build;
9360 @end group
9361 @end smallexample
9363 @noindent
9364 @code{Style_Type} is an example of a @emph{string type}, which is the project
9365 file analog of an Ada enumeration type but containing string literals rather
9366 than identifiers.  @code{Style} is declared as a variable of this type.
9368 The form @code{external("STYLE", "deb")} is known as an
9369 @emph{external reference}; its first argument is the name of an
9370 @emph{external variable}, and the second argument is a default value to be
9371 used if the external variable doesn't exist.  You can define an external
9372 variable on the command line via the @option{-X} switch, or you can use an
9373 environment variable as an external variable.
9375 Each @code{case} construct is expanded by the Project Manager based on the
9376 value of @code{Style}. Thus the command
9377 @smallexample
9378 gnatmake -P/common/build.gpr -XSTYLE=deb
9379 @end smallexample
9381 @noindent
9382 is equivalent to the @command{gnatmake} invocation using the project file
9383 @file{debug.gpr} in the earlier example.  So is the command
9384 @smallexample
9385 gnatmake -P/common/build.gpr
9386 @end smallexample
9388 @noindent
9389 since @code{"deb"} is the default for @code{STYLE}.
9391 Analogously,
9392 @smallexample
9393 gnatmake -P/common/build.gpr -XSTYLE=rel
9394 @end smallexample
9396 @noindent
9397 is equivalent to the @command{gnatmake} invocation using the project file
9398 @file{release.gpr} in the earlier example.
9401 @node Importing Other Projects
9402 @subsection Importing Other Projects
9404 @noindent
9405 A compilation unit in a source file in one project may depend on compilation
9406 units in source files in other projects.  To obtain this behavior, the
9407 dependent project must @emph{import} the projects containing the needed source
9408 files.  This effect is embodied in syntax similar to an Ada @code{with} clause,
9409 but the "with"ed entities are strings denoting project files.
9411 As an example, suppose that the two projects @code{GUI_Proj} and
9412 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
9413 @file{comm_proj.gpr} in directories @file{/gui} and @file{/comm},
9414 respectively.  Assume that the source files for @code{GUI_Proj} are
9415 @file{gui.ads} and @file{gui.adb}, and that the source files for
9416 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, with each set of
9417 files located in its respective project file directory.  Diagrammatically:
9419 @smallexample
9420 @group
9421 /gui
9422   gui_proj.gpr
9423   gui.ads
9424   gui.adb
9425 @end group
9427 @group
9428 /comm
9429   comm_proj.gpr
9430   comm.ads
9431   comm.adb
9432 @end group
9433 @end smallexample
9435 @noindent
9436 We want to develop an application in directory @file{/app} that "with"s the
9437 packages @code{GUI} and @code{Comm}, using the properties of the
9438 corresponding project files (e.g. the switch settings and object directory).
9439 Skeletal code for a main procedure might be something like the following:
9441 @smallexample
9442 @group
9443 with GUI, Comm;
9444 procedure App_Main is
9445    ...
9446 begin
9447    ...
9448 end App_Main;
9449 @end group
9450 @end smallexample
9452 @noindent
9453 Here is a project file, @file{app_proj.gpr}, that achieves the desired
9454 effect:
9456 @smallexample
9457 @group
9458 with "/gui/gui_proj", "/comm/comm_proj";
9459 project App_Proj is
9460    for Main use ("app_main");
9461 end App_Proj;
9462 @end group
9463 @end smallexample
9465 @noindent
9466 Building an executable is achieved through the command:
9467 @smallexample
9468 gnatmake -P/app/app_proj
9469 @end smallexample
9470 @noindent
9471 which will generate the @code{app_main} executable in the directory where
9472 @file{app_proj.gpr} resides.
9474 If an imported project file uses the standard extension (@code{gpr}) then
9475 (as illustrated above) the @code{with} clause can omit the extension.
9477 Our example specified an absolute path for each imported project file.
9478 Alternatively, you can omit the directory if either
9479 @itemize @bullet
9480 @item
9481 The imported project file is in the same directory as the importing project
9482 file, or
9483 @item
9484 You have defined an environment variable @code{ADA_PROJECT_PATH} that
9485 includes the directory containing the needed project file.
9486 @end itemize
9488 @noindent
9489 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{/gui} and
9490 @file{/comm}, then our project file @file{app_proj.gpr} could be written as
9491 follows:
9493 @smallexample
9494 @group
9495 with "gui_proj", "comm_proj";
9496 project App_Proj is
9497    for Main use ("app_main");
9498 end App_Proj;
9499 @end group
9500 @end smallexample
9502 @noindent
9503 Importing other projects raises the possibility of ambiguities.  For
9504 example, the same unit might be present in different imported projects, or
9505 it might be present in both the importing project and an imported project.
9506 Both of these conditions are errors.  Note that in the current version of
9507 the Project Manager, it is illegal to have an ambiguous unit even if the
9508 unit is never referenced by the importing project.  This restriction may be
9509 relaxed in a future release.
9511 @node Extending a Project
9512 @subsection Extending a Project
9514 @noindent
9515 A common situation in large software systems is to have multiple
9516 implementations for a common interface; in Ada terms, multiple versions of a
9517 package body for the same specification.  For example, one implementation
9518 might be safe for use in tasking programs, while another might only be used
9519 in sequential applications.  This can be modeled in GNAT using the concept
9520 of @emph{project extension}.  If one project (the "child") @emph{extends}
9521 another project (the "parent") then by default all source files of the
9522 parent project are inherited by the child, but the child project can
9523 override any of the parent's source files with new versions, and can also
9524 add new files.  This facility is the project analog of extension in
9525 Object-Oriented Programming.  Project hierarchies are permitted (a child
9526 project may be the parent of yet another project), and a project that
9527 inherits one project can also import other projects.
9529 As an example, suppose that directory @file{/seq} contains the project file
9530 @file{seq_proj.gpr} and the source files @file{pack.ads}, @file{pack.adb},
9531 and @file{proc.adb}:
9533 @smallexample
9534 @group
9535 /seq
9536   pack.ads
9537   pack.adb
9538   proc.adb
9539   seq_proj.gpr
9540 @end group
9541 @end smallexample
9543 @noindent
9544 Note that the project file can simply be empty (that is, no attribute or
9545 package is defined):
9547 @smallexample
9548 @group
9549 project Seq_Proj is
9550 end Seq_Proj;
9551 @end group
9552 @end smallexample
9554 @noindent
9555 implying that its source files are all the Ada source files in the project
9556 directory.
9558 Suppose we want to supply an alternate version of @file{pack.adb}, in
9559 directory @file{/tasking}, but use the existing versions of @file{pack.ads}
9560 and @file{proc.adb}.  We can define a project @code{Tasking_Proj} that
9561 inherits @code{Seq_Proj}:
9563 @smallexample
9564 @group
9565 /tasking
9566   pack.adb
9567   tasking_proj.gpr
9568 @end group
9570 @group
9571 project Tasking_Proj extends "/seq/seq_proj" is
9572 end Tasking_Proj;
9573 @end group
9574 @end smallexample
9576 @noindent
9577 The version of @file{pack.adb} used in a build depends on which project file
9578 is specified.
9580 Note that we could have designed this using project import rather than
9581 project inheritance; a @code{base} project would contain the sources for
9582 @file{pack.ads} and @file{proc.adb}, a sequential project would import
9583 @code{base} and add @file{pack.adb}, and likewise a tasking project would
9584 import @code{base} and add a different version of @file{pack.adb}.  The
9585 choice depends on whether other sources in the original project need to be
9586 overridden.  If they do, then project extension is necessary, otherwise,
9587 importing is sufficient.
9590 @c ***********************
9591 @c * Project File Syntax *
9592 @c ***********************
9594 @node Project File Syntax
9595 @section Project File Syntax
9597 @menu
9598 * Basic Syntax::
9599 * Packages::
9600 * Expressions::
9601 * String Types::
9602 * Variables::
9603 * Attributes::
9604 * Associative Array Attributes::
9605 * case Constructions::
9606 @end menu
9608 @noindent
9609 This section describes the structure of project files.
9611 A project may be an @emph{independent project}, entirely defined by a single
9612 project file. Any Ada source file in an independent project depends only
9613 on the predefined library and other Ada source files in the same project.
9615 @noindent
9616 A project may also @dfn{depend on} other projects, in either or both of the following ways:
9617 @itemize @bullet
9618 @item It may import any number of projects
9619 @item It may extend at most one other project
9620 @end itemize
9622 @noindent
9623 The dependence relation is a directed acyclic graph (the subgraph reflecting
9624 the "extends" relation is a tree).
9626 A project's @dfn{immediate sources} are the source files directly defined by
9627 that project, either implicitly by residing in the project file's directory,
9628 or explicitly through any of the source-related attributes described below.
9629 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
9630 of @var{proj} together with the immediate sources (unless overridden) of any
9631 project on which @var{proj} depends (either directly or indirectly).
9633 @node Basic Syntax
9634 @subsection Basic Syntax
9636 @noindent
9637 As seen in the earlier examples, project files have an Ada-like syntax.
9638 The minimal project file is:
9639 @smallexample
9640 @group
9641 project Empty is
9643 end Empty;
9644 @end group
9645 @end smallexample
9647 @noindent
9648 The identifier @code{Empty} is the name of the project.
9649 This project name must be present after the reserved
9650 word @code{end} at the end of the project file, followed by a semi-colon.
9652 Any name in a project file, such as the project name or a variable name,
9653 has the same syntax as an Ada identifier.
9655 The reserved words of project files are the Ada reserved words plus
9656 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
9657 reserved words currently used in project file syntax are:
9659 @itemize @bullet
9660 @item
9661 @code{case}
9662 @item
9663 @code{end}
9664 @item
9665 @code{for}
9666 @item
9667 @code{is}
9668 @item
9669 @code{others}
9670 @item
9671 @code{package}
9672 @item
9673 @code{renames}
9674 @item
9675 @code{type}
9676 @item
9677 @code{use}
9678 @item
9679 @code{when}
9680 @item
9681 @code{with}
9682 @end itemize
9684 @noindent
9685 Comments in project files have the same syntax as in Ada, two consecutives
9686 hyphens through the end of the line.
9688 @node Packages
9689 @subsection Packages
9691 @noindent
9692 A project file may contain @emph{packages}. The name of a package must be one
9693 of the identifiers (case insensitive) from a predefined list, and a package
9694 with a given name may only appear once in a project file. The predefined list
9695 includes the following packages:
9697 @itemize @bullet
9698 @item
9699 @code{Naming}
9700 @item
9701 @code{Builder}
9702 @item
9703 @code{Compiler}
9704 @item
9705 @code{Binder}
9706 @item
9707 @code{Linker}
9708 @item
9709 @code{Finder}
9710 @item
9711 @code{Cross_Reference}
9712 @item
9713 @code{gnatls}
9714 @end itemize
9716 @noindent
9717 (The complete list of the package names and their attributes can be found
9718 in file @file{prj-attr.adb}).
9720 @noindent
9721 In its simplest form, a package may be empty:
9723 @smallexample
9724 @group
9725 project Simple is
9726   package Builder is
9727   end Builder;
9728 end Simple;
9729 @end group
9730 @end smallexample
9732 @noindent
9733 A package may contain @emph{attribute declarations},
9734 @emph{variable declarations} and @emph{case constructions}, as will be
9735 described below.
9737 When there is ambiguity between a project name and a package name,
9738 the name always designates the project. To avoid possible confusion, it is
9739 always a good idea to avoid naming a project with one of the
9740 names allowed for packages or any name that starts with @code{gnat}.
9743 @node Expressions
9744 @subsection Expressions
9746 @noindent
9747 An @emph{expression} is either a @emph{string expression} or a
9748 @emph{string list expression}.
9750 A @emph{string expression} is either a @emph{simple string expression} or a
9751 @emph{compound string expression}.
9753 A @emph{simple string expression} is one of the following:
9754 @itemize @bullet
9755 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
9756 @item A string-valued variable reference (see @ref{Variables})
9757 @item A string-valued attribute reference (see @ref{Attributes})
9758 @item An external reference (see @ref{External References in Project Files})
9759 @end itemize
9761 @noindent
9762 A @emph{compound string expression} is a concatenation of string expressions,
9763 using @code{"&"}
9764 @smallexample
9765        Path & "/" & File_Name & ".ads"
9766 @end smallexample
9768 @noindent
9769 A @emph{string list expression} is either a
9770 @emph{simple string list expression} or a
9771 @emph{compound string list expression}.
9773 A @emph{simple string list expression} is one of the following:
9774 @itemize @bullet
9775 @item A parenthesized list of zero or more string expressions, separated by commas
9776 @smallexample
9777    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
9778    Empty_List := ();
9779 @end smallexample
9780 @item A string list-valued variable reference
9781 @item A string list-valued attribute reference
9782 @end itemize
9784 @noindent
9785 A @emph{compound string list expression} is the concatenation (using
9786 @code{"&"}) of a simple string list expression and an expression.  Note that
9787 each term in a compound string list expression, except the first, may be
9788 either a string expression or a string list expression.
9790 @smallexample
9791 @group
9792    File_Name_List := () & File_Name; --  One string in this list
9793    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
9794    --  Two strings
9795    Big_List := File_Name_List & Extended_File_Name_List;
9796    --  Concatenation of two string lists: three strings
9797    Illegal_List := "gnat.adc" & Extended_File_Name_List;
9798    --  Illegal: must start with a string list
9799 @end group
9800 @end smallexample
9803 @node String Types
9804 @subsection String Types
9806 @noindent
9807 The value of a variable may be restricted to a list of string literals.
9808 The restricted list of string literals is given in a
9809 @emph{string type declaration}.
9811 Here is an example of a string type declaration:
9813 @smallexample
9814    type OS is ("NT, "nt", "Unix", "Linux", "other OS");
9815 @end smallexample
9817 @noindent
9818 Variables of a string type are called @emph{typed variables}; all other
9819 variables are called @emph{untyped variables}. Typed variables are
9820 particularly useful in @code{case} constructions
9821 (see @ref{case Constructions}).
9823 A string type declaration starts with the reserved word @code{type}, followed
9824 by the name of the string type (case-insensitive), followed by the reserved
9825 word @code{is}, followed by a parenthesized list of one or more string literals
9826 separated by commas, followed by a semicolon.
9828 The string literals in the list are case sensitive and must all be different.
9829 They may include any graphic characters allowed in Ada, including spaces.
9831 A string type may only be declared at the project level, not inside a package.
9833 A string type may be referenced by its name if it has been declared in the same
9834 project file, or by its project name, followed by a dot,
9835 followed by the string type name.
9838 @node Variables
9839 @subsection Variables
9841 @noindent
9842 A variable may be declared at the project file level, or in a package.
9843 Here are some examples of variable declarations:
9845 @smallexample
9846 @group
9847    This_OS : OS := external ("OS"); --  a typed variable declaration
9848    That_OS := "Linux";              --  an untyped variable declaration
9849 @end group
9850 @end smallexample
9852 @noindent
9853 A @emph{typed variable declaration} includes the variable name, followed by a colon,
9854 followed by the name of a string type, followed by @code{:=}, followed by
9855 a simple string expression.
9857 An @emph{untyped variable declaration} includes the variable name,
9858 followed by @code{:=}, followed by an expression.  Note that, despite the
9859 terminology, this form of "declaration" resembles more an assignment
9860 than a declaration in Ada.  It is a declaration in several senses:
9861 @itemize @bullet
9862 @item
9863 The variable name does not need to be defined previously
9864 @item
9865 The declaration establishes the @emph{kind} (string versus string list) of the
9866 variable, and later declarations of the same variable need to be consistent
9867 with this
9868 @end itemize
9870 @noindent
9871 A string variable declaration (typed or untyped) declares a variable
9872 whose value is a string. This variable may be used as a string expression.
9873 @smallexample
9874    File_Name       := "readme.txt";
9875    Saved_File_Name := File_Name & ".saved";
9876 @end smallexample
9878 @noindent
9879 A string list variable declaration declares a variable whose value is a list
9880 of strings. The list may contain any number (zero or more) of strings.
9882 @smallexample
9883    Empty_List := ();
9884    List_With_One_Element := ("-gnaty");
9885    List_With_Two_Elements := List_With_One_Element & "-gnatg";
9886    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
9887                  "pack2.ada", "util_.ada", "util.ada");
9888 @end smallexample
9890 @noindent
9891 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.
9893 The same untyped variable may be declared several times.
9894 In this case, the new value replaces the old one,
9895 and any subsequent reference to the variable uses the new value.
9896 However, as noted above, if a variable has been declared as a string, all subsequent
9897 declarations must give it a string value. Similarly, if a variable has
9898 been declared as a string list, all subsequent declarations
9899 must give it a string list value.
9901 A @emph{variable reference} may take several forms:
9903 @itemize @bullet
9904 @item The simple variable name, for a variable in the current package (if any) or in the current project
9905 @item A context name, followed by a dot, followed by the variable name.
9906 @end itemize
9908 @noindent
9909 A @emph{context} may be one of the following:
9911 @itemize @bullet
9912 @item The name of an existing package in the current project
9913 @item The name of an imported project of the current project
9914 @item The name of an ancestor project (i.e., a project extended by the current project, either directly or indirectly)
9915 @item An imported/parent project name, followed by a dot, followed by a package name
9916 @end itemize
9918 @noindent
9919 A variable reference may be used in an expression.
9922 @node Attributes
9923 @subsection Attributes
9925 @noindent
9926 A project (and its packages) may have @emph{attributes} that define the project's properties.
9927 Some attributes have values that are strings;
9928 others have values that are string lists.
9930 There are two categories of attributes: @emph{simple attributes} and @emph{associative arrays}
9931 (see @ref{Associative Array Attributes}).
9933 The names of the attributes are restricted; there is a list of project
9934 attributes, and a list of package attributes for each package.
9935 The names are not case sensitive.
9937 The project attributes are as follows (all are simple attributes):
9939 @multitable @columnfractions .4 .3
9940 @item @emph{Attribute Name}
9941 @tab @emph{Value}
9942 @item @code{Source_Files}
9943 @tab string list
9944 @item @code{Source_Dirs}
9945 @tab string list
9946 @item @code{Source_List_File}
9947 @tab string
9948 @item @code{Object_Dir}
9949 @tab string
9950 @item @code{Exec_Dir}
9951 @tab string
9952 @item @code{Main}
9953 @tab string list
9954 @item @code{Languages}
9955 @tab string list
9956 @item @code{Library_Dir}
9957 @tab string
9958 @item @code{Library_Name}
9959 @tab string
9960 @item @code{Library_Kind}
9961 @tab string
9962 @item @code{Library_Elaboration}
9963 @tab string
9964 @item @code{Library_Version}
9965 @tab string
9966 @end multitable
9968 @noindent
9969 The attributes for package @code{Naming} are as follows
9970 (see @ref{Naming Schemes}):
9972 @multitable @columnfractions .4 .2 .2 .2
9973 @item Attribute Name @tab Category @tab Index @tab Value
9974 @item @code{Specification_Suffix}
9975 @tab associative array
9976 @tab language name
9977 @tab string
9978 @item @code{Implementation_Suffix}
9979 @tab associative array
9980 @tab language name
9981 @tab string
9982 @item @code{Separate_Suffix}
9983 @tab simple attribute
9984 @tab n/a
9985 @tab string
9986 @item @code{Casing}
9987 @tab simple attribute
9988 @tab n/a
9989 @tab string
9990 @item @code{Dot_Replacement}
9991 @tab simple attribute
9992 @tab n/a
9993 @tab string
9994 @item @code{Specification}
9995 @tab associative array
9996 @tab Ada unit name
9997 @tab string
9998 @item @code{Implementation}
9999 @tab associative array
10000 @tab Ada unit name
10001 @tab string
10002 @item @code{Specification_Exceptions}
10003 @tab associative array
10004 @tab language name
10005 @tab string list
10006 @item @code{Implementation_Exceptions}
10007 @tab associative array
10008 @tab language name
10009 @tab string list
10010 @end multitable
10012 @noindent
10013 The attributes for package @code{Builder}, @code{Compiler}, @code{Binder},
10014 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
10015 are as follows (see @ref{Switches and Project Files}).
10017 @multitable @columnfractions .4 .2 .2 .2
10018 @item Attribute Name @tab Category @tab Index @tab Value
10019 @item @code{Default_Switches}
10020 @tab associative array
10021 @tab language name
10022 @tab string list
10023 @item @code{Switches}
10024 @tab associative array
10025 @tab file name
10026 @tab string list
10027 @end multitable
10029 @noindent
10030 In addition, package @code{Builder} has a single string attribute
10031 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
10032 string attribute @code{Global_Configuration_Pragmas}.
10034 @noindent
10035 The attribute for package @code{Glide} are not documented: they are for
10036 internal use only.
10038 @noindent
10039 Each simple attribute has a default value: the empty string (for string-valued
10040 attributes) and the empty list (for string list-valued attributes).
10042 Similar to variable declarations, an attribute declaration defines a new value
10043 for an attribute.
10045 Examples of simple attribute declarations:
10047 @smallexample
10048    for Object_Dir use "objects";
10049    for Source_Dirs use ("units", "test/drivers");
10050 @end smallexample
10052 @noindent
10053 A @dfn{simple attribute declaration} starts with the reserved word @code{for},
10054 followed by the name of the attribute, followed by the reserved word
10055 @code{use}, followed by an expression (whose kind depends on the attribute),
10056 followed by a semicolon.
10058 Attributes may be referenced in expressions.
10059 The general form for such a reference is @code{<entity>'<attribute>}:
10060 the entity for which the attribute is defined,
10061 followed by an apostrophe, followed by the name of the attribute.
10062 For associative array attributes, a litteral string between parentheses
10063 need to be supplied as index.
10065 Examples are:
10067 @smallexample
10068   project'Object_Dir
10069   Naming'Dot_Replacement
10070   Imported_Project'Source_Dirs
10071   Imported_Project.Naming'Casing
10072   Builder'Default_Switches("Ada")
10073 @end smallexample
10075 @noindent
10076 The entity may be:
10077 @itemize @bullet
10078 @item @code{project} for an attribute of the current project
10079 @item The name of an existing package of the current project
10080 @item The name of an imported project
10081 @item The name of a parent project (extended by the current project)
10082 @item An imported/parent project name, followed by a dot,
10083       followed by a package name
10084 @end itemize
10086 @noindent
10087 Example:
10088 @smallexample
10089 @group
10090    project Prj is
10091      for Source_Dirs use project'Source_Dirs & "units";
10092      for Source_Dirs use project'Source_Dirs & "test/drivers"
10093    end Prj;
10094 @end group
10095 @end smallexample
10097 @noindent
10098 In the first attribute declaration, initially the attribute @code{Source_Dirs}
10099 has the default value: an empty string list. After this declaration,
10100 @code{Source_Dirs} is a string list of one element: "units".
10101 After the second attribute declaration @code{Source_Dirs} is a string list of
10102 two elements: "units" and "test/drivers".
10104 Note: this example is for illustration only. In practice,
10105 the project file would contain only one attribute declaration:
10107 @smallexample
10108    for Source_Dirs use ("units", "test/drivers");
10109 @end smallexample
10112 @node Associative Array Attributes
10113 @subsection Associative Array Attributes
10115 @noindent
10116 Some attributes are defined as @emph{associative arrays}. An associative
10117 array may be regarded as a function that takes a string as a parameter
10118 and delivers a string or string list value as its result.
10120 Here are some examples of associative array attribute declarations:
10122 @smallexample
10123    for Implementation ("main") use "Main.ada";
10124    for Switches ("main.ada") use ("-v", "-gnatv");
10125    for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g";
10126 @end smallexample
10128 @noindent
10129 Like untyped variables and simple attributes, associative array attributes may be declared several times. Each declaration supplies a new value for the
10130 attribute, replacing the previous setting.
10133 @node case Constructions
10134 @subsection @code{case} Constructions
10136 @noindent
10137 A @code{case} construction is used in a project file to effect conditional
10138 behavior.
10139 Here is a typical example:
10141 @smallexample
10142 @group
10143 project MyProj is
10144    type OS_Type is ("Linux", "Unix", "NT", "VMS");
10146    OS : OS_Type := external ("OS", "Linux");
10147 @end group
10149 @group
10150    package Compiler is
10151      case OS is
10152        when "Linux" | "Unix" =>
10153          for Default_Switches ("Ada") use ("-gnath");
10154        when "NT" =>
10155          for Default_Switches ("Ada") use ("-gnatP");
10156        when others =>
10157      end case;
10158    end Compiler;
10159 end MyProj;
10160 @end group
10161 @end smallexample
10163 @noindent
10164 The syntax of a @code{case} construction is based on the Ada case statement
10165 (although there is no @code{null} construction for empty alternatives).
10167 Following the reserved word @code{case} there is the case variable (a typed
10168 string variable), the reserved word @code{is}, and then a sequence of one or
10169 more alternatives.
10170 Each alternative comprises the reserved word @code{when}, either a list of
10171 literal strings separated by the @code{"|"} character or the reserved word
10172 @code{others},  and the @code{"=>"} token.
10173 Each literal string must belong to the string type that is the type of the
10174 case variable.
10175 An @code{others} alternative, if present, must occur last.
10176 The @code{end case;} sequence terminates the case construction.
10178 After each @code{=>}, there are zero or more constructions.  The only
10179 constructions allowed in a case construction are other case constructions and
10180 attribute declarations. String type declarations, variable declarations and
10181 package declarations are not allowed.
10183 The value of the case variable is often given by an external reference
10184 (see @ref{External References in Project Files}).
10187 @c ****************************************
10188 @c * Objects and Sources in Project Files *
10189 @c ****************************************
10191 @node Objects and Sources in Project Files
10192 @section Objects and Sources in Project Files
10194 @menu
10195 * Object Directory::
10196 * Exec Directory::
10197 * Source Directories::
10198 * Source File Names::
10199 @end menu
10201 @noindent
10202 Each project has exactly one object directory and one or more source
10203 directories. The source directories must contain at least one source file,
10204 unless  the project file explicitly specifies that no source files are present
10205 (see @ref{Source File Names}).
10208 @node Object Directory
10209 @subsection Object Directory
10211 @noindent
10212 The object directory for a project is the directory containing the compiler's
10213 output (such as @file{ALI} files and object files) for the project's immediate
10214 sources. Note that for inherited sources (when extending a parent project) the
10215 parent project's object directory is used.
10217 The object directory is given by the value of the attribute @code{Object_Dir}
10218 in the project file.
10220 @smallexample
10221    for Object_Dir use "objects";
10222 @end smallexample
10224 @noindent
10225 The attribute @var{Object_Dir} has a string value, the path name of the object
10226 directory. The path name may be absolute or relative to the directory of the
10227 project file. This directory must already exist, and be readable and writable.
10229 By default, when the attribute @code{Object_Dir} is not given an explicit value
10230 or when its value is the empty string, the object directory is the same as the
10231 directory containing the project file.
10234 @node Exec Directory
10235 @subsection Exec Directory
10237 @noindent
10238 The exec directory for a project is the directory containing the executables
10239 for the project's main subprograms.
10241 The exec directory is given by the value of the attribute @code{Exec_Dir}
10242 in the project file.
10244 @smallexample
10245    for Exec_Dir use "executables";
10246 @end smallexample
10248 @noindent
10249 The attribute @var{Exec_Dir} has a string value, the path name of the exec
10250 directory. The path name may be absolute or relative to the directory of the
10251 project file. This directory must already exist, and be writable.
10253 By default, when the attribute @code{Exec_Dir} is not given an explicit value
10254 or when its value is the empty string, the exec directory is the same as the
10255 object directory of the project file.
10258 @node Source Directories
10259 @subsection Source Directories
10261 @noindent
10262 The source directories of a project are specified by the project file
10263 attribute @code{Source_Dirs}.
10265 This attribute's value is a string list. If the attribute is not given an
10266 explicit value, then there is only one source directory, the one where the
10267 project file resides.
10269 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
10270 as in
10272 @smallexample
10273     for Source_Dirs use ();
10274 @end smallexample
10276 @noindent
10277 indicates that the project contains no source files.
10279 Otherwise, each string in the string list designates one or more
10280 source directories.
10282 @smallexample
10283    for Source_Dirs use ("sources", "test/drivers");
10284 @end smallexample
10286 @noindent
10287 If a string in the list ends with @code{"/**"},  then the directory whose path
10288 name precedes the two asterisks, as well as all its subdirectories
10289 (recursively), are source directories.
10291 @smallexample
10292    for Source_Dirs use ("/system/sources/**");
10293 @end smallexample
10295 @noindent
10296 Here the directory @code{/system/sources} and all of its subdirectories
10297 (recursively) are source directories.
10299 To specify that the source directories are the directory of the project file
10300 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
10301 @smallexample
10302    for Source_Dirs use ("./**");
10303 @end smallexample
10305 @noindent
10306 Each of the source directories must exist and be readable.
10309 @node Source File Names
10310 @subsection Source File Names
10312 @noindent
10313 In a project that contains source files, their names may be specified by the
10314 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
10315 (a string). Source file names never include any directory information.
10317 If the attribute @code{Source_Files} is given an explicit value, then each
10318 element of the list is a source file name.
10320 @smallexample
10321    for Source_Files use ("main.adb");
10322    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
10323 @end smallexample
10325 @noindent
10326 If the attribute @code{Source_Files} is not given an explicit value,
10327 but the attribute @code{Source_List_File} is given a string value,
10328 then the source file names are contained in the text file whose path name
10329 (absolute or relative to the directory of the project file) is the
10330 value of the attribute @code{Source_List_File}.
10332 Each line in the file that is not empty or is not a comment
10333 contains a source file name. A comment line starts with two hyphens.
10335 @smallexample
10336    for Source_List_File use "source_list.txt";
10337 @end smallexample
10339 @noindent
10340 By default, if neither the attribute @code{Source_Files} nor the attribute
10341 @code{Source_List_File} is given an explicit value, then each file in the
10342 source directories that conforms to the project's naming scheme
10343 (see @ref{Naming Schemes}) is an immediate source of the project.
10345 A warning is issued if both attributes @code{Source_Files} and
10346 @code{Source_List_File} are given explicit values. In this case, the attribute
10347 @code{Source_Files} prevails.
10349 Each source file name must be the name of one and only one existing source file
10350 in one of the source directories.
10352 A @code{Source_Files} attribute defined with an empty list as its value
10353 indicates that there are no source files in the project.
10355 Except for projects that are clearly specified as containing no Ada source
10356 files (@code{Source_Dirs} or @code{Source_Files} specified as an empty list,
10357 or @code{Languages} specified without @code{"Ada"} in the list)
10358 @smallexample
10359    for Source_Dirs use ();
10360    for Source_Files use ();
10361    for Languages use ("C", "C++");
10362 @end smallexample
10364 @noindent
10365 a project must contain at least one immediate source.
10367 Projects with no source files are useful as template packages
10368 (see @ref{Packages in Project Files}) for other projects; in particular to
10369 define a package @code{Naming} (see @ref{Naming Schemes}).
10372 @c ****************************
10373 @c * Importing Projects *
10374 @c ****************************
10376 @node  Importing Projects
10377 @section Importing Projects
10379 @noindent
10380 An immediate source of a project P may depend on source files that
10381 are neither immediate sources of P nor in the predefined library.
10382 To get this effect, P must @emph{import} the projects that contain the needed
10383 source files.
10385 @smallexample
10386 @group
10387   with "project1", "utilities.gpr";
10388   with "/namings/apex.gpr";
10389   project Main is
10390     ...
10391 @end group
10392 @end smallexample
10394 @noindent
10395 As can be seen in this example, the syntax for importing projects is similar
10396 to the syntax for importing compilation units in Ada. However, project files
10397 use literal strings instead of names, and the @code{with} clause identifies
10398 project files rather than packages.
10400 Each literal string is the file name or path name (absolute or relative) of a
10401 project file. If a string is simply a file name, with no path, then its
10402 location is determined by the @emph{project path}:
10404 @itemize @bullet
10405 @item
10406 If the environment variable @env{ADA_PROJECT_PATH} exists, then the project
10407 path includes all the directories in this environment variable, plus the
10408 directory of the project file.
10410 @item
10411 If the environment variable @env{ADA_PROJECT_PATH} does not exist,
10412 then the project path contains only one directory, namely the one where
10413 the project file is located.
10414 @end itemize
10416 @noindent
10417 If a relative pathname is used as in
10419 @smallexample
10420   with "tests/proj";
10421 @end smallexample
10423 @noindent
10424 then the path is relative to the directory where the importing project file is
10425 located. Any symbolic link will be fully resolved in the directory
10426 of the importing project file before the imported project file is looked up.
10428 When the @code{with}'ed project file name does not have an extension,
10429 the default is @file{.gpr}. If a file with this extension is not found, then
10430 the file name as specified in the @code{with} clause (no extension) will be
10431 used. In the above example, if a file @code{project1.gpr} is found, then it
10432 will be used; otherwise, if a file @code{project1} exists then it will be used;
10433 if neither file exists, this is an error.
10435 A warning is issued if the name of the project file does not match the
10436 name of the project; this check is case insensitive.
10438 Any source file that is an immediate source of the imported project can be
10439 used by the immediate sources of the importing project, and recursively. Thus
10440 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
10441 sources of @code{A} may depend on the immediate sources of @code{C}, even if
10442 @code{A} does not import @code{C} explicitly. However, this is not recommended,
10443 because if and when @code{B} ceases to import @code{C}, some sources in
10444 @code{A} will no longer compile.
10446 A side effect of this capability is that cyclic dependences are not permitted:
10447 if @code{A} imports @code{B} (directly or indirectly) then @code{B} is not
10448 allowed to import @code{A}.
10451 @c *********************
10452 @c * Project Extension *
10453 @c *********************
10455 @node Project Extension
10456 @section Project Extension
10458 @noindent
10459 During development of a large system, it is sometimes necessary to use
10460 modified versions of some of the source files without changing the original
10461 sources. This can be achieved through a facility known as
10462 @emph{project extension}.
10464 @smallexample
10465    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
10466 @end smallexample
10468 @noindent
10469 The project file for the project being extended (the @emph{parent}) is
10470 identified by the literal string that follows the reserved word @code{extends},
10471 which itself follows the name of the extending project (the @emph{child}).
10473 By default, a child project inherits all the sources of its parent.
10474 However, inherited sources can be overridden: a unit with the same name as one
10475 in the parent will hide the original unit.
10476 Inherited sources are considered to be sources (but not immediate sources)
10477 of the child project; see @ref{Project File Syntax}.
10479 An inherited source file retains any switches specified in the parent project.
10481 For example if the project @code{Utilities} contains the specification and the
10482 body of an Ada package @code{Util_IO}, then the project
10483 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
10484 The original body of @code{Util_IO} will not be considered in program builds.
10485 However, the package specification will still be found in the project
10486 @code{Utilities}.
10488 A child project can have only one parent but it may import any number of other
10489 projects.
10491 A project is not allowed to import directly or indirectly at the same time a
10492 child project and any of its ancestors.
10495 @c ****************************************
10496 @c * External References in Project Files *
10497 @c ****************************************
10499 @node  External References in Project Files
10500 @section External References in Project Files
10502 @noindent
10503 A project file may contain references to external variables; such references
10504 are called @emph{external references}.
10506 An external variable is either defined as part of the environment (an
10507 environment variable in Unix, for example) or else specified on the command
10508 line via the @option{-X@emph{vbl}=@emph{value}} switch. If both, then the
10509 command line value is used.
10511 An external reference is denoted by the built-in function
10512 @code{external}, which returns a string value.  This function has two forms:
10513 @itemize @bullet
10514 @item @code{external (external_variable_name)}
10515 @item @code{external (external_variable_name, default_value)}
10516 @end itemize
10518 @noindent
10519 Each parameter must be a string literal.  For example:
10521 @smallexample
10522    external ("USER")
10523    external ("OS", "Linux")
10524 @end smallexample
10526 @noindent
10527 In the form with one parameter, the function returns the value of
10528 the external variable given as parameter. If this name is not present in the
10529 environment, then the returned value is an empty string.
10531 In the form with two string parameters, the second parameter is
10532 the value returned when the variable given as the first parameter is not
10533 present in the environment. In the example above, if @code{"OS"} is not
10534 the name of an environment variable and is not passed on the command line,
10535 then the returned value will be @code{"Linux"}.
10537 An external reference may be part of a string expression or of a string
10538 list expression, to define variables or attributes.
10540 @smallexample
10541 @group
10542    type Mode_Type is ("Debug", "Release");
10543    Mode : Mode_Type := external ("MODE");
10544    case Mode is
10545      when "Debug" =>
10546         ...
10547 @end group
10548 @end smallexample
10551 @c *****************************
10552 @c * Packages in Project Files *
10553 @c *****************************
10555 @node  Packages in Project Files
10556 @section Packages in Project Files
10558 @noindent
10559 The @emph{package} is the project file feature that defines the settings for
10560 project-aware tools.
10561 For each such tool you can declare a corresponding package; the names for these
10562 packages are preset (see @ref{Packages}) but are not case sensitive.
10563 A package may contain variable declarations, attribute declarations, and case
10564 constructions.
10566 @smallexample
10567 @group
10568    project Proj is
10569       package Builder is  -- used by gnatmake
10570          for Default_Switches ("Ada") use ("-v", "-g");
10571       end Builder;
10572    end Proj;
10573 @end group
10574 @end smallexample
10576 @noindent
10577 A package declaration starts with the reserved word @code{package},
10578 followed by the package name (case insensitive), followed by the reserved word
10579 @code{is}. It ends with the reserved word @code{end}, followed by the package
10580 name, finally followed by a semi-colon.
10582 Most of the packages have an attribute @code{Default_Switches}.
10583 This attribute is an associative array, and its value is a string list.
10584 The index of the associative array is the name of a programming language (case
10585 insensitive). This attribute indicates the switch or switches to be used
10586 with the corresponding tool.
10588 Some packages also have another attribute, @code{Switches}, an associative
10589 array whose value is a string list. The index is the name of a source file.
10590 This attribute indicates the switch or switches to be used by the corresponding
10591 tool when dealing with this specific file.
10593 Further information on these switch-related attributes is found in
10594 @ref{Switches and Project Files}.
10596 A package may be declared as a @emph{renaming} of another package; e.g., from
10597 the project file for an imported project.
10599 @smallexample
10600 @group
10601   with "/global/apex.gpr";
10602   project Example is
10603     package Naming renames Apex.Naming;
10604     ...
10605   end Example;
10606 @end group
10607 @end smallexample
10609 @noindent
10610 Packages that are renamed in other project files often come from project files
10611 that have no sources: they are just used as templates. Any modification in the
10612 template will be reflected automatically in all the project files that rename
10613 a package from the template.
10615 In addition to the tool-oriented packages, you can also declare a package
10616 named @code{Naming} to establish specialized source file naming conventions
10617 (see @ref{Naming Schemes}).
10620 @c ************************************
10621 @c * Variables from Imported Projects *
10622 @c ************************************
10624 @node Variables from Imported Projects
10625 @section Variables from Imported Projects
10627 @noindent
10628 An attribute or variable defined in an imported or parent project can
10629 be used in expressions in the importing / extending project.
10630 Such an attribute or variable is prefixed with the name of the project
10631 and (if relevant) the name of package where it is defined.
10633 @smallexample
10634 @group
10635   with "imported";
10636   project Main extends "base" is
10637      Var1 := Imported.Var;
10638      Var2 := Base.Var & ".new";
10639 @end group
10641 @group
10642      package Builder is
10643         for Default_Switches ("Ada") use Imported.Builder.Ada_Switches &
10644                          "-gnatg" & "-v";
10645      end Builder;
10646 @end group
10648 @group
10649      package Compiler is
10650         for Default_Switches ("Ada") use Base.Compiler.Ada_Switches;
10651      end Compiler;
10652   end Main;
10653 @end group
10654 @end smallexample
10656 @noindent
10657 In this example:
10659 @itemize @bullet
10660 @item
10661 @code{Var1} is a copy of the variable @code{Var} defined in the project file
10662 @file{"imported.gpr"}
10663 @item
10664 the value of @code{Var2} is a copy of the value of variable @code{Var}
10665 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
10666 @item
10667 attribute @code{Default_Switches ("Ada")} in package @code{Builder}
10668 is a string list that includes in its value a copy of variable
10669 @code{Ada_Switches} defined in the @code{Builder} package in project file
10670 @file{imported.gpr} plus two new elements: @option{"-gnatg"} and @option{"-v"};
10671 @item
10672 attribute @code{Default_Switches ("Ada")} in package @code{Compiler}
10673 is a copy of the variable @code{Ada_Switches} defined in the @code{Compiler}
10674 package in project file @file{base.gpr}, the project being extended.
10675 @end itemize
10678 @c ******************
10679 @c * Naming Schemes *
10680 @c ******************
10682 @node  Naming Schemes
10683 @section Naming Schemes
10685 @noindent
10686 Sometimes an Ada software system is ported from a foreign compilation
10687 environment to GNAT, with file names that do not use the default GNAT
10688 conventions. Instead of changing all the file names (which for a variety of
10689 reasons might not be possible), you can define the relevant file naming scheme
10690 in the @code{Naming} package in your project file.  For example, the following
10691 package models the Apex file naming rules:
10693 @smallexample
10694 @group
10695   package Naming is
10696     for Casing                        use "lowercase";
10697     for Dot_Replacement               use ".";
10698     for Specification_Suffix ("Ada")  use ".1.ada";
10699     for Implementation_Suffix ("Ada") use ".2.ada";
10700   end Naming;
10701 @end group
10702 @end smallexample
10704 @noindent
10705 You can define the following attributes in package @code{Naming}:
10707 @table @code
10709 @item @var{Casing}
10710 This must be a string with one of the three values @code{"lowercase"},
10711 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
10713 @noindent
10714 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
10716 @item @var{Dot_Replacement}
10717 This must be a string whose value satisfies the following conditions:
10719 @itemize @bullet
10720 @item It must not be empty
10721 @item It cannot start or end with an alphanumeric character
10722 @item It cannot be a single underscore
10723 @item It cannot start with an underscore followed by an alphanumeric
10724 @item It cannot contain a dot @code{'.'} except if it the entire string is @code{"."}
10725 @end itemize
10727 @noindent
10728 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
10730 @item @var{Specification_Suffix}
10731 This is an associative array (indexed by the programming language name, case
10732 insensitive) whose value is a string that must satisfy the following
10733 conditions:
10735 @itemize @bullet
10736 @item It must not be empty
10737 @item It cannot start with an alphanumeric character
10738 @item It cannot start with an underscore followed by an alphanumeric character
10739 @end itemize
10740 @noindent
10741 If @code{Specification_Suffix ("Ada")} is not specified, then the default is
10742 @code{".ads"}.
10744 @item @var{Implementation_Suffix}
10745 This is an associative array (indexed by the programming language name, case
10746 insensitive) whose value is a string that must satisfy the following
10747 conditions:
10749 @itemize @bullet
10750 @item It must not be empty
10751 @item It cannot start with an alphanumeric character
10752 @item It cannot start with an underscore followed by an alphanumeric character
10753 @item It cannot be a suffix of @code{Specification_Suffix}
10754 @end itemize
10755 @noindent
10756 If @code{Implementation_Suffix ("Ada")} is not specified, then the default is
10757 @code{".adb"}.
10759 @item @var{Separate_Suffix}
10760 This must be a string whose value satisfies the same conditions as
10761 @code{Implementation_Suffix}.
10763 @noindent
10764 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
10765 value as @code{Implementation_Suffix ("Ada")}.
10767 @item @var{Specification}
10768 @noindent
10769 You can use the @code{Specification} attribute, an associative array, to define
10770 the source file name for an individual Ada compilation unit's spec. The array
10771 index must be a string literal that identifies the Ada unit (case insensitive).
10772 The value of this attribute must be a string that identifies the file that
10773 contains this unit's spec (case sensitive or insensitive depending on the
10774 operating system).
10776 @smallexample
10777    for Specification ("MyPack.MyChild") use "mypack.mychild.spec";
10778 @end smallexample
10780 @item @var{Implementation}
10782 You can use the @code{Implementation} attribute, an associative array, to
10783 define the source file name for an individual Ada compilation unit's body
10784 (possibly a subunit).  The array index must be a string literal that identifies
10785 the Ada unit (case insensitive).  The value of this attribute must be a string
10786 that identifies the file that contains this unit's body or subunit (case
10787 sensitive or insensitive depending on the operating system).
10789 @smallexample
10790    for Implementation ("MyPack.MyChild") use "mypack.mychild.body";
10791 @end smallexample
10792 @end table
10795 @c ********************
10796 @c * Library Projects *
10797 @c ********************
10799 @node Library Projects
10800 @section Library Projects
10802 @noindent
10803 @emph{Library projects} are projects whose object code is placed in a library.
10804 (Note that this facility is not yet supported on all platforms)
10806 To create a library project, you need to define in its project file
10807 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
10808 Additionally, you may define the library-related attributes
10809 @code{Library_Kind}, @code{Library_Version} and @code{Library_Elaboration}.
10811 The @code{Library_Name} attribute has a string value that must start with a
10812 letter and include only letters and digits.
10814 The @code{Library_Dir} attribute has a string value that designates the path
10815 (absolute or relative) of the directory where the library will reside.
10816 It must designate an existing directory, and this directory needs to be
10817 different from the project's object directory. It also needs to be writable.
10819 If both @code{Library_Name} and @code{Library_Dir} are specified and
10820 are legal, then the project file defines a library project.  The optional
10821 library-related attributes are checked only for such project files.
10823 The @code{Library_Kind} attribute has a string value that must be one of the
10824 following (case insensitive): @code{"static"}, @code{"dynamic"} or
10825 @code{"relocatable"}. If this attribute is not specified, the library is a
10826 static library. Otherwise, the library may be dynamic or relocatable.
10827 Depending on the operating system, there may or may not be a distinction
10828 between dynamic and relocatable libraries. For example, on Unix there is no
10829 such distinction.
10831 The @code{Library_Version} attribute has a string value whose interpretation
10832 is platform dependent. On Unix, it is used only for dynamic/relocatable
10833 libraries as the internal name of the library (the @code{"soname"}). If the
10834 library file name (built from the @code{Library_Name}) is different from the
10835 @code{Library_Version}, then the library file will be a symbolic link to the
10836 actual file whose name will be @code{Library_Version}.
10838 Example (on Unix):
10840 @smallexample
10841 @group
10842 project Plib is
10844    Version := "1";
10846    for Library_Dir use "lib_dir";
10847    for Library_Name use "dummy";
10848    for Library_Kind use "relocatable";
10849    for Library_Version use "libdummy.so." & Version;
10851 end Plib;
10852 @end group
10853 @end smallexample
10855 @noindent
10856 Directory @file{lib_dir} will contain the internal library file whose name
10857 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
10858 @file{libdummy.so.1}.
10860 When @command{gnatmake} detects that a project file (not the main project file)
10861 is a library project file, it will check all immediate sources of the project
10862 and rebuild the library if any of the sources have been recompiled.
10863 All @file{ALI} files will also be copied from the object directory to the
10864 library directory. To build executables, @command{gnatmake} will use the
10865 library rather than the individual object files.
10868 @c *************************************
10869 @c * Switches Related to Project Files *
10870 @c *************************************
10871 @node Switches Related to Project Files
10872 @section Switches Related to Project Files
10874 @noindent
10875 The following switches are used by GNAT tools that support project files:
10877 @table @code
10879 @item @option{-P@var{project}}
10880 Indicates the name of a project file. This project file will be parsed with
10881 the verbosity indicated by @option{-vP@emph{x}}, if any, and using the external
10882 references indicated by @option{-X} switches, if any.
10884 @noindent
10885 There must be only one @option{-P} switch on the command line.
10887 @noindent
10888 Since the Project Manager parses the project file only after all the switches
10889 on the command line are checked, the order of the switches @option{-P},
10890 @option{-Vp@emph{x}} or @option{-X} is not significant.
10892 @item @option{-X@var{name=value}}
10893 Indicates that external variable @var{name} has the value @var{value}.
10894 The Project Manager will use this value for occurrences of
10895 @code{external(name)} when parsing the project file.
10897 @noindent
10898 If @var{name} or @var{value} includes a space, then @var{name=value} should be
10899 put between quotes.
10900 @smallexample
10901   -XOS=NT
10902   -X"user=John Doe"
10903 @end smallexample
10905 @noindent
10906 Several @option{-X} switches can be used simultaneously.
10907 If several @option{-X} switches specify the same @var{name}, only the last one
10908 is used.
10910 @noindent
10911 An external variable specified with a @option{-X} switch takes precedence
10912 over the value of the same name in the environment.
10914 @item @option{-vP@emph{x}}
10915 Indicates the verbosity of the parsing of GNAT project files.
10916 @option{-vP0} means Default (no output for syntactically correct project
10917 files);
10918 @option{-vP1} means Medium;
10919 @option{-vP2} means High.
10920 @noindent
10921 The default is Default.
10922 @noindent
10923 If several @option{-vP@emph{x}} switches are present, only the last one is
10924 used.
10926 @end table
10929 @c **********************************
10930 @c * Tools Supporting Project Files *
10931 @c **********************************
10933 @node  Tools Supporting Project Files
10934 @section Tools Supporting Project Files
10936 @menu
10937 * gnatmake and Project Files::
10938 * The GNAT Driver and Project Files::
10939 @ifclear vms
10940 * Glide and Project Files::
10941 @end ifclear
10942 @end menu
10944 @node gnatmake and Project Files
10945 @subsection gnatmake and Project Files
10947 @noindent
10948 This section covers two topics related to @command{gnatmake} and project files:
10949 defining switches for @command{gnatmake} and for the tools that it invokes;
10950 and the use of the @code{Main} attribute.
10952 @menu
10953 * Switches and Project Files::
10954 * Project Files and Main Subprograms::
10955 @end menu
10957 @node Switches and Project Files
10958 @subsubsection Switches and Project Files
10960 @noindent
10961 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
10962 @code{Linker}, you can specify a @code{Default_Switches} attribute, a
10963 @code{Switches} attribute, or both; as their names imply, these switch-related
10964 attributes affect which switches are used for which files when
10965 @command{gnatmake} is invoked.  As will be explained below, these
10966 package-contributed switches precede the switches passed on the
10967 @command{gnatmake} command line.
10969 The @code{Default_Switches} attribute is an associative array indexed by
10970 language name (case insensitive) and returning a string list.  For example:
10972 @smallexample
10973 @group
10974 package Compiler is
10975   for Default_Switches ("Ada") use ("-gnaty", "-v");
10976 end Compiler;
10977 @end group
10978 @end smallexample
10980 @noindent
10981 The @code{Switches} attribute is also an associative array, indexed by a file
10982 name (which may or may not be case sensitive, depending on the operating
10983 system) and returning a string list.  For example:
10985 @smallexample
10986 @group
10987 package Builder is
10988    for Switches ("main1.adb") use ("-O2");
10989    for Switches ("main2.adb") use ("-g");
10990 end Builder;
10991 @end group
10992 @end smallexample
10994 @noindent
10995 For the @code{Builder} package, the file names should designate source files
10996 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
10997 file names should designate @file{ALI} or source files for main subprograms.
10998 In each case just the file name (without explicit extension) is acceptable.
11000 For each tool used in a program build (@command{gnatmake}, the compiler, the
11001 binder, and the linker), its corresponding package @dfn{contributes} a set of
11002 switches for each file on which the tool is invoked, based on the
11003 switch-related attributes defined in the package. In particular, the switches
11004 that each of these packages contributes for a given file @var{f} comprise:
11006 @itemize @bullet
11007 @item
11008 the value of attribute @code{Switches (@var{f})}, if it is specified in the
11009 package for the given file,
11010 @item
11011 otherwise, the value of @code{Default_Switches ("Ada")}, if it is specified in
11012 the package.
11013 @end itemize
11015 @noindent
11016 If neither of these attributes is defined in the package, then the package does
11017 not contribute any switches for the given file.
11019 When @command{gnatmake} is invoked on a file, the switches comprise two sets,
11020 in the following order: those contributed for the file by the @code{Builder}
11021 package; and the switches passed on the command line.
11023 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
11024 the switches passed to the tool comprise three sets, in the following order:
11026 @enumerate
11027 @item
11028 the applicable switches contributed for the file by the @code{Builder} package
11029 in the project file supplied on the command line;
11031 @item
11032 those contributed for the file by the package (in the relevant project file --
11033 see below) corresponding to the tool; and
11035 @item
11036 the applicable switches passed on the command line.
11037 @end enumerate
11039 @noindent
11040 The term @emph{applicable switches} reflects the fact that @command{gnatmake}
11041 switches may or may not be passed to individual tools, depending on the
11042 individual switch.
11044 @command{gnatmake} may invoke the compiler on source files from different
11045 projects. The Project Manager will use the appropriate project file to
11046 determine the @code{Compiler} package for each source file being compiled.
11047 Likewise for the @code{Binder} and @code{Linker} packages.
11049 As an example, consider the following package in a project file:
11051 @smallexample
11052 @group
11053 project Proj1 is
11054    package Compiler is
11055       for Default_Switches ("Ada") use ("-g");
11056       for Switches ("a.adb") use ("-O1");
11057       for Switches ("b.adb") use ("-O2", "-gnaty");
11058    end Compiler;
11059 end Proj1;
11060 @end group
11061 @end smallexample
11063 @noindent
11064 If @command{gnatmake} is invoked with this project file, and it needs to
11065 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
11066 @file{a.adb} will be compiled with the switch @option{-O1}, @file{b.adb}
11067 with switches @option{-O2} and @option{-gnaty}, and @file{c.adb} with
11068 @option{-g}.
11070 Another example illustrates the ordering of the switches contributed by
11071 different packages:
11073 @smallexample
11074 @group
11075 project Proj2 is
11076    package Builder is
11077       for Switches ("main.adb") use ("-g", "-O1", "-f");
11078    end Builder;
11079 @end group
11081 @group
11082    package Compiler is
11083       for Switches ("main.adb") use ("-O2");
11084    end Compiler;
11085 end Proj2;
11086 @end group
11087 @end smallexample
11089 @noindent
11090 If you issue the command:
11092 @smallexample
11093     gnatmake -PProj2 -O0 main
11094 @end smallexample
11096 @noindent
11097 then the compiler will be invoked on @file{main.adb} with the following sequence of switches
11099 @smallexample
11100    -g -O1 -O2 -O0
11101 @end smallexample
11103 with the last @option{-O} switch having precedence over the earlier ones;
11104 several other switches (such as @option{-c}) are added implicitly.
11106 The switches @option{-g} and @option{-O1} are contributed by package
11107 @code{Builder},  @option{-O2} is contributed by the package @code{Compiler}
11108 and @option{-O0} comes from the command line.
11110 The @option{-g} switch will also be passed in the invocation of
11111 @command{gnatlink.}
11113 A final example illustrates switch contributions from packages in different
11114 project files:
11116 @smallexample
11117 @group
11118 project Proj3 is
11119    for Source_Files use ("pack.ads", "pack.adb");
11120    package Compiler is
11121       for Default_Switches ("Ada") use ("-gnata");
11122    end Compiler;
11123 end Proj3;
11124 @end group
11126 @group
11127 with "Proj3";
11128 project Proj4 is
11129    for Source_Files use ("foo_main.adb", "bar_main.adb");
11130    package Builder is
11131       for Switches ("foo_main.adb") use ("-s", "-g");
11132    end Builder;
11133 end Proj4;
11134 @end group
11136 @group
11137 -- Ada source file:
11138 with Pack;
11139 procedure Foo_Main is
11140    ...
11141 end Foo_Main;
11142 @end group
11143 @end smallexample
11145 If the command is
11146 @smallexample
11147 gnatmake -PProj4 foo_main.adb -cargs -gnato
11148 @end smallexample
11150 @noindent
11151 then the switches passed to the compiler for @file{foo_main.adb} are
11152 @option{-g} (contributed by the package @code{Proj4.Builder}) and
11153 @option{-gnato} (passed on the command line).
11154 When the imported package @code{Pack} is compiled, the switches used are
11155 @option{-g} from @code{Proj4.Builder}, @option{-gnata} (contributed from
11156 package @code{Proj3.Compiler}, and @option{-gnato} from the command line.
11159 @node Project Files and Main Subprograms
11160 @subsubsection Project Files and Main Subprograms
11162 @noindent
11163 When using a project file, you can invoke @command{gnatmake}
11164 with several main subprograms, by specifying their source files on the command
11165 line.  Each of these needs to be an immediate source file of the project.
11167 @smallexample
11168     gnatmake -Pprj main1 main2 main3
11169 @end smallexample
11171 @noindent
11172 When using a project file, you can also invoke @command{gnatmake} without
11173 explicitly specifying any main, and the effect depends on whether you have
11174 defined the @code{Main} attribute.  This attribute has a string list value,
11175 where each element in the list is the name of a source file (the file
11176 extension is optional) containing a main subprogram.
11178 If the @code{Main} attribute is defined in a project file as a non-empty
11179 string list and the switch @option{-u} is not used on the command line, then
11180 invoking @command{gnatmake} with this project file but without any main on the
11181 command line is equivalent to invoking @command{gnatmake} with all the file
11182 names in the @code{Main} attribute on the command line.
11184 Example:
11185 @smallexample
11186 @group
11187    project Prj is
11188       for Main use ("main1", "main2", "main3");
11189    end Prj;
11190 @end group
11191 @end smallexample
11193 @noindent
11194 With this project file, @code{"gnatmake -Pprj"} is equivalent to
11195 @code{"gnatmake -Pprj main1 main2 main3"}.
11197 When the project attribute @code{Main} is not specified, or is specified
11198 as an empty string list, or when the switch @option{-u} is used on the command
11199 line, then invoking @command{gnatmake} with no main on the command line will
11200 result in all immediate sources of the project file being checked, and
11201 potentially recompiled. Depending on the presence of the switch @option{-u},
11202 sources from other project files on which the immediate sources of the main
11203 project file depend are also checked and potentially recompiled. In other
11204 words, the @option{-u} switch is applied to all of the immediate sources of themain project file.
11207 @node The GNAT Driver and Project Files
11208 @subsection The GNAT Driver and Project Files
11210 @noindent
11211 A number of GNAT tools, other than @command{gnatmake} are project-aware:
11212 @command{gnatbind}, @command{gnatfind}, @command{gnatlink}, @command{gnatls}
11213 and @command{gnatxref}. However, none of these tools can be invoked directly
11214 with a project file switch (@code{-P}). They need to be invoke through the
11215 @command{gnat} driver.
11217 The @command{gnat} driver is a front-end that accepts a number of commands and
11218 call the corresponding tool. It has been designed initially for VMS to convert
11219 VMS style qualifiers to Unix style switches, but it is now available to all
11220 the GNAT supported platforms.
11222 On non VMS platforms, the @command{gnat} driver accepts the following commands
11223 (case insensitive):
11225 @itemize @bullet
11226 @item
11227 BIND to invoke @command{gnatbind}
11228 @item
11229 CHOP to invoke @command{gnatchop}
11230 @item
11231 COMP or COMPILE to invoke the compiler
11232 @item
11233 ELIM to invoke @command{gnatelim}
11234 @item
11235 FIND to invoke @command{gnatfind}
11236 @item
11237 KR or KRUNCH to invoke @command{gnatkr}
11238 @item
11239 LINK to invoke @command{gnatlink}
11240 @item
11241 LS or LIST to invoke @command{gnatls}
11242 @item
11243 MAKE to invoke @command{gnatmake}
11244 @item
11245 NAME to invoke @command{gnatname}
11246 @item
11247 PREP or PREPROCESS to invoke @command{gnatprep}
11248 @item
11249 PSTA or STANDARD to invoke @command{gnatpsta}
11250 @item
11251 STUB to invoke @command{gnatstub}
11252 @item
11253 XREF to invoke @command{gnatxref}
11254 @end itemize
11256 @noindent
11257 Note that the compiler is invoked using the command @command{gnatmake -f -u}.
11259 @noindent
11260 Following the command, you may put switches and arguments for the invoked
11261 tool.
11263 @smallexample
11264   gnat bind -C main.ali
11265   gnat ls -a main
11266   gnat chop foo.txt
11267 @end smallexample
11269 @noindent
11270 In addition, for command BIND, FIND, LS or LIST, LINK and XREF, the project
11271 file related switches (@code{-P}, @code{-X} and @code{-vPx}) may be used in
11272 addition to the switches of the invoking tool.
11274 @noindent
11275 For each of these command, there is possibly a package in the main project that
11276 corresponds to the invoked tool.
11278 @itemize @bullet
11279 @item
11280 package @code{Binder} for command BIND (invoking @code{gnatbind})
11282 @item
11283 package @code{Finder} for command FIND (invoking @code{gnatfind})
11285 @item
11286 package @code{Gnatls} for command LS or LIST (invoking @code{gnatls})
11288 @item
11289 package @code{Linker} for command LINK (invoking @code{gnatlink})
11291 @item
11292 package @code{Cross_Reference} for command XREF (invoking @code{gnatlink})
11294 @end itemize
11296 @noindent
11297 Package @code{Gnatls} has a unique attribute @code{Switches}, a simple variable
11298 with a string list value. It contains switches for the invocation of
11299 @code{gnatls}.
11301 @smallexample
11302 @group
11303 project Proj1 is
11304    package gnatls is
11305       for Switches use ("-a", "-v");
11306    end gnatls;
11307 end Proj1;
11308 @end group
11309 @end smallexample
11311 @noindent
11312 All other packages contains a switch @code{Default_Switches}, an associative
11313 array, indexed by the programming language (case insensitive) and having a
11314 string list value. @code{Default_Switches ("Ada")} contains the switches for
11315 the invocation of the tool corresponding to the package.
11317 @smallexample
11318 @group
11319 project Proj is
11321    for Source_Dirs use ("./**");
11323    package gnatls is
11324       for Switches use ("-a", "-v");
11325    end gnatls;
11326 @end group
11327 @group
11329    package Binder is
11330       for Default_Switches ("Ada") use ("-C", "-e");
11331    end Binder;
11332 @end group
11333 @group
11335    package Linker is
11336       for Default_Switches ("Ada") use ("-C");
11337    end Linker;
11338 @end group
11339 @group
11341    package Finder is
11342       for Default_Switches ("Ada") use ("-a", "-f");
11343    end Finder;
11344 @end group
11345 @group
11347    package Cross_Reference is
11348       for Default_Switches ("Ada") use ("-a", "-f", "-d", "-u");
11349    end Cross_Reference;
11350 end Proj;
11351 @end group
11352 @end smallexample
11354 @noindent
11355 With the above project file, commands such as
11357 @smallexample
11358    gnat ls -Pproj main
11359    gnat xref -Pproj main
11360    gnat bind -Pproj main.ali
11361 @end smallexample
11363 @noindent
11364 will set up the environment properly and invoke the tool with the switches
11365 found in the package corresponding to the tool.
11368 @ifclear vms
11369 @node Glide and Project Files
11370 @subsection Glide and Project Files
11372 @noindent
11373 Glide will automatically recognize the @file{.gpr} extension for
11374 project files, and will
11375 convert them to its own internal format automatically. However, it
11376 doesn't provide a syntax-oriented editor for modifying these
11377 files.
11378 The project file will be loaded as text when you select the menu item
11379 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
11380 You can edit this text and save the @file{gpr} file;
11381 when you next select this project file in Glide it
11382 will be automatically reloaded.
11384 @ifset vxworks
11385 Glide uses the @code{gnatlist} attribute in the @code{Ide} package, whose value
11386 is something like @code{powerpc-wrs-vxworks-gnatls}, to compute the
11387 cross-prefix.  From this information the correct location for the
11388 GNAT runtime, and thus also the correct cross-references, can be
11389 determined.
11390 @end ifset
11391 @end ifclear
11394 @node An Extended Example
11395 @section An Extended Example
11397 @noindent
11398 Suppose that we have two programs, @var{prog1} and @var{prog2}, with the sources
11399 in the respective directories. We would like to build them with a single
11400 @command{gnatmake} command, and we would like to place their object files into
11401 @file{.build} subdirectories of the source directories. Furthermore, we would
11402 like to have to have two separate subdirectories in @file{.build}  --
11403 @file{release} and @file{debug} -- which will contain the object files compiled with
11404 different set of compilation flags.
11406 In other words, we have the following structure:
11408 @smallexample
11409 @group
11410    main
11411      |- prog1
11412      |    |- .build
11413      |         | debug
11414      |         | release
11415      |- prog2
11416           |- .build
11417                | debug
11418                | release
11419 @end group
11420 @end smallexample
11422 @noindent
11423 Here are the project files that we need to create in a directory @file{main}
11424 to maintain this structure:
11426 @enumerate
11428 @item We create a @code{Common} project with a package @code{Compiler} that
11429 specifies the compilation switches:
11431 @smallexample
11432 File "common.gpr":
11433 @group
11434 @b{project} Common @b{is}
11436    @b{for} Source_Dirs @b{use} (); -- No source files
11437 @end group
11439 @group
11440    @b{type} Build_Type @b{is} ("release", "debug");
11441    Build : Build_Type := External ("BUILD", "debug");
11442 @end group
11443 @group
11444    @b{package} Compiler @b{is}
11445       @b{case} Build @b{is}
11446          @b{when} "release" =>
11447            @b{for} Default_Switches ("Ada") @b{use} ("-O2");
11448          @b{when} "debug"   =>
11449            @b{for} Default_Switches ("Ada") @b{use} ("-g");
11450       @b{end case};
11451    @b{end} Compiler;
11453 @b{end} Common;
11454 @end group
11455 @end smallexample
11457 @item We create separate projects for the two programs:
11459 @smallexample
11460 @group
11461 File "prog1.gpr":
11463 @b{with} "common";
11464 @b{project} Prog1 @b{is}
11466     @b{for} Source_Dirs @b{use} ("prog1");
11467     @b{for} Object_Dir  @b{use} "prog1/.build/" & Common.Build;
11469     @b{package} Compiler @b{renames} Common.Compiler;
11471 @b{end} Prog1;
11472 @end group
11473 @end smallexample
11475 @smallexample
11476 @group
11477 File "prog2.gpr":
11479 @b{with} "common";
11480 @b{project} Prog2 @b{is}
11482     @b{for} Source_Dirs @b{use} ("prog2");
11483     @b{for} Object_Dir  @b{use} "prog2/.build/" & Common.Build;
11485     @b{package} Compiler @b{renames} Common.Compiler;
11487 @end group
11488 @b{end} Prog2;
11489 @end smallexample
11491 @item We create a wrapping project @var{Main}:
11493 @smallexample
11494 @group
11495 File "main.gpr":
11497 @b{with} "common";
11498 @b{with} "prog1";
11499 @b{with} "prog2";
11500 @b{project} Main @b{is}
11502    @b{package} Compiler @b{renames} Common.Compiler;
11504 @b{end} Main;
11505 @end group
11506 @end smallexample
11508 @item Finally we need to create a dummy procedure that @code{with}s (either
11509 explicitly or implicitly) all the sources of our two programs.
11511 @end enumerate
11513 @noindent
11514 Now we can build the programs using the command
11516 @smallexample
11517    gnatmake -Pmain dummy
11518 @end smallexample
11520 @noindent
11521 for the Debug mode, or
11523 @smallexample
11524    gnatmake -Pmain -XBUILD=release
11525 @end smallexample
11527 @noindent
11528 for the Release mode.
11531 @c ********************************
11532 @c * Project File Complete Syntax *
11533 @c ********************************
11535 @node Project File Complete Syntax
11536 @section Project File Complete Syntax
11538 @smallexample
11539 project ::=
11540   context_clause project_declaration
11542 context_clause ::=
11543   @{with_clause@}
11545 with_clause ::=
11546   @b{with} literal_string @{ , literal_string @} ;
11548 project_declaration ::=
11549   @b{project} <project_>simple_name [ @b{extends} literal_string ] @b{is}
11550     @{declarative_item@}
11551   @b{end} <project_>simple_name;
11553 declarative_item ::=
11554   package_declaration |
11555   typed_string_declaration |
11556   other_declarative_item
11558 package_declaration ::=
11559   @b{package} <package_>simple_name package_completion
11561 package_completion ::=
11562   package_body | package_renaming
11564 package body ::=
11565   @b{is}
11566     @{other_declarative_item@}
11567   @b{end} <package_>simple_name ;
11569 package_renaming ::==
11570   @b{renames} <project_>simple_name.<package_>simple_name ;
11572 typed_string_declaration ::=
11573   @b{type} <typed_string_>_simple_name @b{is}
11574    ( literal_string @{, literal_string@} );
11576 other_declarative_item ::=
11577   attribute_declaration |
11578   typed_variable_declaration |
11579   variable_declaration |
11580   case_construction
11582 attribute_declaration ::=
11583   @b{for} attribute @b{use} expression ;
11585 attribute ::=
11586   <simple_attribute_>simple_name |
11587   <associative_array_attribute_>simple_name ( literal_string )
11589 typed_variable_declaration ::=
11590   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
11592 variable_declaration ::=
11593   <variable_>simple_name := expression;
11595 expression ::=
11596   term @{& term@}
11598 term ::=
11599   literal_string |
11600   string_list |
11601   <variable_>name |
11602   external_value |
11603   attribute_reference
11605 literal_string ::=
11606   (same as Ada)
11608 string_list ::=
11609   ( <string_>expression @{ , <string_>expression @} )
11611 external_value ::=
11612   @b{external} ( literal_string [, literal_string] )
11614 attribute_reference ::=
11615   attribute_parent ' <simple_attribute_>simple_name [ ( literal_string ) ]
11617 attribute_parent ::=
11618   @b{project} |
11619   <project_or_package>simple_name |
11620   <project_>simple_name . <package_>simple_name
11622 case_construction ::=
11623   @b{case} <typed_variable_>name @b{is}
11624     @{case_item@}
11625   @b{end case} ;
11627 case_item ::=
11628   @b{when} discrete_choice_list => @{case_construction | attribute_declaration@}
11630 discrete_choice_list ::=
11631   literal_string @{| literal_string@}
11633 name ::=
11634   simple_name @{. simple_name@}
11636 simple_name ::=
11637   identifier (same as Ada)
11639 @end smallexample
11642 @node Elaboration Order Handling in GNAT
11643 @chapter Elaboration Order Handling in GNAT
11644 @cindex Order of elaboration
11645 @cindex Elaboration control
11647 @menu
11648 * Elaboration Code in Ada 95::
11649 * Checking the Elaboration Order in Ada 95::
11650 * Controlling the Elaboration Order in Ada 95::
11651 * Controlling Elaboration in GNAT - Internal Calls::
11652 * Controlling Elaboration in GNAT - External Calls::
11653 * Default Behavior in GNAT - Ensuring Safety::
11654 * Elaboration Issues for Library Tasks::
11655 * Mixing Elaboration Models::
11656 * What to Do If the Default Elaboration Behavior Fails::
11657 * Elaboration for Access-to-Subprogram Values::
11658 * Summary of Procedures for Elaboration Control::
11659 * Other Elaboration Order Considerations::
11660 @end menu
11662 @noindent
11663 This chapter describes the handling of elaboration code in Ada 95 and
11664 in GNAT, and discusses how the order of elaboration of program units can
11665 be controlled in GNAT, either automatically or with explicit programming
11666 features.
11668 @node Elaboration Code in Ada 95
11669 @section Elaboration Code in Ada 95
11671 @noindent
11672 Ada 95 provides rather general mechanisms for executing code at elaboration
11673 time, that is to say before the main program starts executing. Such code arises
11674 in three contexts:
11676 @table @asis
11677 @item Initializers for variables.
11678 Variables declared at the library level, in package specs or bodies, can
11679 require initialization that is performed at elaboration time, as in:
11680 @smallexample
11681 @cartouche
11682 Sqrt_Half : Float := Sqrt (0.5);
11683 @end cartouche
11684 @end smallexample
11686 @item Package initialization code
11687 Code in a @code{BEGIN-END} section at the outer level of a package body is
11688 executed as part of the package body elaboration code.
11690 @item Library level task allocators
11691 Tasks that are declared using task allocators at the library level
11692 start executing immediately and hence can execute at elaboration time.
11693 @end table
11695 @noindent
11696 Subprogram calls are possible in any of these contexts, which means that
11697 any arbitrary part of the program may be executed as part of the elaboration
11698 code. It is even possible to write a program which does all its work at
11699 elaboration time, with a null main program, although stylistically this
11700 would usually be considered an inappropriate way to structure
11701 a program.
11703 An important concern arises in the context of elaboration code:
11704 we have to be sure that it is executed in an appropriate order. What we
11705 have is a series of elaboration code sections, potentially one section
11706 for each unit in the program. It is important that these execute
11707 in the correct order. Correctness here means that, taking the above
11708 example of the declaration of @code{Sqrt_Half},
11709 if some other piece of
11710 elaboration code references @code{Sqrt_Half},
11711 then it must run after the
11712 section of elaboration code that contains the declaration of
11713 @code{Sqrt_Half}.
11715 There would never be any order of elaboration problem if we made a rule
11716 that whenever you @code{with} a unit, you must elaborate both the spec and body
11717 of that unit before elaborating the unit doing the @code{with}'ing:
11719 @smallexample
11720 @group
11721 @cartouche
11722 @b{with} Unit_1;
11723 @b{package} Unit_2 @b{is} ...
11724 @end cartouche
11725 @end group
11726 @end smallexample
11728 @noindent
11729 would require that both the body and spec of @code{Unit_1} be elaborated
11730 before the spec of @code{Unit_2}. However, a rule like that would be far too
11731 restrictive. In particular, it would make it impossible to have routines
11732 in separate packages that were mutually recursive.
11734 You might think that a clever enough compiler could look at the actual
11735 elaboration code and determine an appropriate correct order of elaboration,
11736 but in the general case, this is not possible. Consider the following
11737 example.
11739 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
11740 that references
11741 the variable @code{Sqrt_1}, which is declared in the elaboration code
11742 of the body of @code{Unit_1}:
11744 @smallexample
11745 @cartouche
11746 Sqrt_1 : Float := Sqrt (0.1);
11747 @end cartouche
11748 @end smallexample
11750 @noindent
11751 The elaboration code of the body of @code{Unit_1} also contains:
11753 @smallexample
11754 @group
11755 @cartouche
11756 @b{if} expression_1 = 1 @b{then}
11757    Q := Unit_2.Func_2;
11758 @b{end if};
11759 @end cartouche
11760 @end group
11761 @end smallexample
11763 @noindent
11764 @code{Unit_2} is exactly parallel,
11765 it has a procedure @code{Func_2} that references
11766 the variable @code{Sqrt_2}, which is declared in the elaboration code of
11767 the body @code{Unit_2}:
11769 @smallexample
11770 @cartouche
11771 Sqrt_2 : Float := Sqrt (0.1);
11772 @end cartouche
11773 @end smallexample
11775 @noindent
11776 The elaboration code of the body of @code{Unit_2} also contains:
11778 @smallexample
11779 @group
11780 @cartouche
11781 @b{if} expression_2 = 2 @b{then}
11782    Q := Unit_1.Func_1;
11783 @b{end if};
11784 @end cartouche
11785 @end group
11786 @end smallexample
11788 @noindent
11789 Now the question is, which of the following orders of elaboration is
11790 acceptable:
11792 @smallexample
11793 @group
11794 Spec of Unit_1
11795 Spec of Unit_2
11796 Body of Unit_1
11797 Body of Unit_2
11798 @end group
11799 @end smallexample
11801 @noindent
11804 @smallexample
11805 @group
11806 Spec of Unit_2
11807 Spec of Unit_1
11808 Body of Unit_2
11809 Body of Unit_1
11810 @end group
11811 @end smallexample
11813 @noindent
11814 If you carefully analyze the flow here, you will see that you cannot tell
11815 at compile time the answer to this question.
11816 If @code{expression_1} is not equal to 1,
11817 and @code{expression_2} is not equal to 2,
11818 then either order is acceptable, because neither of the function calls is
11819 executed. If both tests evaluate to true, then neither order is acceptable
11820 and in fact there is no correct order.
11822 If one of the two expressions is true, and the other is false, then one
11823 of the above orders is correct, and the other is incorrect. For example,
11824 if @code{expression_1} = 1 and @code{expression_2} /= 2,
11825 then the call to @code{Func_2}
11826 will occur, but not the call to @code{Func_1.}
11827 This means that it is essential
11828 to elaborate the body of @code{Unit_1} before
11829 the body of @code{Unit_2}, so the first
11830 order of elaboration is correct and the second is wrong.
11832 By making @code{expression_1} and @code{expression_2}
11833 depend on input data, or perhaps
11834 the time of day, we can make it impossible for the compiler or binder
11835 to figure out which of these expressions will be true, and hence it
11836 is impossible to guarantee a safe order of elaboration at run time.
11838 @node Checking the Elaboration Order in Ada 95
11839 @section Checking the Elaboration Order in Ada 95
11841 @noindent
11842 In some languages that involve the same kind of elaboration problems,
11843 e.g. Java and C++, the programmer is expected to worry about these
11844 ordering problems himself, and it is common to
11845 write a program in which an incorrect elaboration order  gives
11846 surprising results, because it references variables before they
11847 are initialized.
11848 Ada 95 is designed to be a safe language, and a programmer-beware approach is
11849 clearly not sufficient. Consequently, the language provides three lines
11850 of defense:
11852 @table @asis
11853 @item Standard rules
11854 Some standard rules restrict the possible choice of elaboration
11855 order. In particular, if you @code{with} a unit, then its spec is always
11856 elaborated before the unit doing the @code{with}. Similarly, a parent
11857 spec is always elaborated before the child spec, and finally
11858 a spec is always elaborated before its corresponding body.
11860 @item Dynamic elaboration checks
11861 @cindex Elaboration checks
11862 @cindex Checks, elaboration
11863 Dynamic checks are made at run time, so that if some entity is accessed
11864 before it is elaborated (typically  by means of a subprogram call)
11865 then the exception (@code{Program_Error}) is raised.
11867 @item Elaboration control
11868 Facilities are provided for the programmer to specify the desired order
11869 of elaboration.
11870 @end table
11872 Let's look at these facilities in more detail. First, the rules for
11873 dynamic checking. One possible rule would be simply to say that the
11874 exception is raised if you access a variable which has not yet been
11875 elaborated. The trouble with this approach is that it could require
11876 expensive checks on every variable reference. Instead Ada 95 has two
11877 rules which are a little more restrictive, but easier to check, and
11878 easier to state:
11880 @table @asis
11881 @item Restrictions on calls
11882 A subprogram can only be called at elaboration time if its body
11883 has been elaborated. The rules for elaboration given above guarantee
11884 that the spec of the subprogram has been elaborated before the
11885 call, but not the body. If this rule is violated, then the
11886 exception @code{Program_Error} is raised.
11888 @item Restrictions on instantiations
11889 A generic unit can only be instantiated if the body of the generic
11890 unit has been elaborated. Again, the rules for elaboration given above
11891 guarantee that the spec of the generic unit has been elaborated
11892 before the instantiation, but not the body. If this rule is
11893 violated, then the exception @code{Program_Error} is raised.
11894 @end table
11896 @noindent
11897 The idea is that if the body has been elaborated, then any variables
11898 it references must have been elaborated; by checking for the body being
11899 elaborated we guarantee that none of its references causes any
11900 trouble. As we noted above, this is a little too restrictive, because a
11901 subprogram that has no non-local references in its body may in fact be safe
11902 to call. However, it really would be unsafe to rely on this, because
11903 it would mean that the caller was aware of details of the implementation
11904 in the body. This goes against the basic tenets of Ada.
11906 A plausible implementation can be described as follows.
11907 A Boolean variable is associated with each subprogram
11908 and each generic unit. This variable is initialized to False, and is set to
11909 True at the point body is elaborated. Every call or instantiation checks the
11910 variable, and raises @code{Program_Error} if the variable is False.
11912 Note that one might think that it would be good enough to have one Boolean
11913 variable for each package, but that would not deal with cases of trying
11914 to call a body in the same package as the call
11915 that has not been elaborated yet.
11916 Of course a compiler may be able to do enough analysis to optimize away
11917 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
11918 does such optimizations, but still the easiest conceptual model is to
11919 think of there being one variable per subprogram.
11921 @node Controlling the Elaboration Order in Ada 95
11922 @section Controlling the Elaboration Order in Ada 95
11924 @noindent
11925 In the previous section we discussed the rules in Ada 95 which ensure
11926 that @code{Program_Error} is raised if an incorrect elaboration order is
11927 chosen. This prevents erroneous executions, but we need mechanisms to
11928 specify a correct execution and avoid the exception altogether.
11929 To achieve this, Ada 95 provides a number of features for controlling
11930 the order of elaboration. We discuss these features in this section.
11932 First, there are several ways of indicating to the compiler that a given
11933 unit has no elaboration problems:
11935 @table @asis
11936 @item packages that do not require a body
11937 In Ada 95, a library package that does not require a body does not permit
11938 a body. This means that if we have a such a package, as in:
11940 @smallexample
11941 @group
11942 @cartouche
11943 @b{package} Definitions @b{is}
11944    @b{generic}
11945       @b{type} m @b{is new} integer;
11946    @b{package} Subp @b{is}
11947       @b{type} a @b{is array} (1 .. 10) @b{of} m;
11948       @b{type} b @b{is array} (1 .. 20) @b{of} m;
11949    @b{end} Subp;
11950 @b{end} Definitions;
11951 @end cartouche
11952 @end group
11953 @end smallexample
11955 @noindent
11956 A package that @code{with}'s @code{Definitions} may safely instantiate
11957 @code{Definitions.Subp} because the compiler can determine that there
11958 definitely is no package body to worry about in this case
11960 @item pragma Pure
11961 @cindex pragma Pure
11962 @findex Pure
11963 Places sufficient restrictions on a unit to guarantee that
11964 no call to any subprogram in the unit can result in an
11965 elaboration problem. This means that the compiler does not need
11966 to worry about the point of elaboration of such units, and in
11967 particular, does not need to check any calls to any subprograms
11968 in this unit.
11970 @item pragma Preelaborate
11971 @findex Preelaborate
11972 @cindex pragma Preelaborate
11973 This pragma places slightly less stringent restrictions on a unit than
11974 does pragma Pure,
11975 but these restrictions are still sufficient to ensure that there
11976 are no elaboration problems with any calls to the unit.
11978 @item pragma Elaborate_Body
11979 @findex Elaborate_Body
11980 @cindex pragma Elaborate_Body
11981 This pragma requires that the body of a unit be elaborated immediately
11982 after its spec. Suppose a unit @code{A} has such a pragma,
11983 and unit @code{B} does
11984 a @code{with} of unit @code{A}. Recall that the standard rules require
11985 the spec of unit @code{A}
11986 to be elaborated before the @code{with}'ing unit; given the pragma in
11987 @code{A}, we also know that the body of @code{A}
11988 will be elaborated before @code{B}, so
11989 that calls to @code{A} are safe and do not need a check.
11990 @end table
11992 @noindent
11993 Note that,
11994 unlike pragma @code{Pure} and pragma @code{Preelaborate},
11995 the use of
11996 @code{Elaborate_Body} does not guarantee that the program is
11997 free of elaboration problems, because it may not be possible
11998 to satisfy the requested elaboration order.
11999 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
12000 If a programmer
12001 marks @code{Unit_1} as @code{Elaborate_Body},
12002 and not @code{Unit_2,} then the order of
12003 elaboration will be:
12005 @smallexample
12006 @group
12007 Spec of Unit_2
12008 Spec of Unit_1
12009 Body of Unit_1
12010 Body of Unit_2
12011 @end group
12012 @end smallexample
12014 @noindent
12015 Now that means that the call to @code{Func_1} in @code{Unit_2}
12016 need not be checked,
12017 it must be safe. But the call to @code{Func_2} in
12018 @code{Unit_1} may still fail if
12019 @code{Expression_1} is equal to 1,
12020 and the programmer must still take
12021 responsibility for this not being the case.
12023 If all units carry a pragma @code{Elaborate_Body}, then all problems are
12024 eliminated, except for calls entirely within a body, which are
12025 in any case fully under programmer control. However, using the pragma
12026 everywhere is not always possible.
12027 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
12028 we marked both of them as having pragma @code{Elaborate_Body}, then
12029 clearly there would be no possible elaboration order.
12031 The above pragmas allow a server to guarantee safe use by clients, and
12032 clearly this is the preferable approach. Consequently a good rule in
12033 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
12034 and if this is not possible,
12035 mark them as @code{Elaborate_Body} if possible.
12036 As we have seen, there are situations where neither of these
12037 three pragmas can be used.
12038 So we also provide methods for clients to control the
12039 order of elaboration of the servers on which they depend:
12041 @table @asis
12042 @item pragma Elaborate (unit)
12043 @findex Elaborate
12044 @cindex pragma Elaborate
12045 This pragma is placed in the context clause, after a @code{with} clause,
12046 and it requires that the body of the named unit be elaborated before
12047 the unit in which the pragma occurs. The idea is to use this pragma
12048 if the current unit calls at elaboration time, directly or indirectly,
12049 some subprogram in the named unit.
12051 @item pragma Elaborate_All (unit)
12052 @findex Elaborate_All
12053 @cindex pragma Elaborate_All
12054 This is a stronger version of the Elaborate pragma. Consider the
12055 following example:
12057 @smallexample
12058 Unit A @code{with}'s unit B and calls B.Func in elab code
12059 Unit B @code{with}'s unit C, and B.Func calls C.Func
12060 @end smallexample
12062 @noindent
12063 Now if we put a pragma @code{Elaborate (B)}
12064 in unit @code{A}, this ensures that the
12065 body of @code{B} is elaborated before the call, but not the
12066 body of @code{C}, so
12067 the call to @code{C.Func} could still cause @code{Program_Error} to
12068 be raised.
12070 The effect of a pragma @code{Elaborate_All} is stronger, it requires
12071 not only that the body of the named unit be elaborated before the
12072 unit doing the @code{with}, but also the bodies of all units that the
12073 named unit uses, following @code{with} links transitively. For example,
12074 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
12075 then it requires
12076 not only that the body of @code{B} be elaborated before @code{A},
12077 but also the
12078 body of @code{C}, because @code{B} @code{with}'s @code{C}.
12079 @end table
12081 @noindent
12082 We are now in a position to give a usage rule in Ada 95 for avoiding
12083 elaboration problems, at least if dynamic dispatching and access to
12084 subprogram values are not used. We will handle these cases separately
12085 later.
12087 The rule is simple. If a unit has elaboration code that can directly or
12088 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
12089 a generic unit in a @code{with}'ed unit,
12090 then if the @code{with}'ed unit does not have
12091 pragma @code{Pure} or @code{Preelaborate}, then the client should have
12092 a pragma @code{Elaborate_All}
12093 for the @code{with}'ed unit. By following this rule a client is
12094 assured that calls can be made without risk of an exception.
12095 If this rule is not followed, then a program may be in one of four
12096 states:
12098 @table @asis
12099 @item No order exists
12100 No order of elaboration exists which follows the rules, taking into
12101 account any @code{Elaborate}, @code{Elaborate_All},
12102 or @code{Elaborate_Body} pragmas. In
12103 this case, an Ada 95 compiler must diagnose the situation at bind
12104 time, and refuse to build an executable program.
12106 @item One or more orders exist, all incorrect
12107 One or more acceptable elaboration orders exists, and all of them
12108 generate an elaboration order problem. In this case, the binder
12109 can build an executable program, but @code{Program_Error} will be raised
12110 when the program is run.
12112 @item Several orders exist, some right, some incorrect
12113 One or more acceptable elaboration orders exists, and some of them
12114 work, and some do not. The programmer has not controlled
12115 the order of elaboration, so the binder may or may not pick one of
12116 the correct orders, and the program may or may not raise an
12117 exception when it is run. This is the worst case, because it means
12118 that the program may fail when moved to another compiler, or even
12119 another version of the same compiler.
12121 @item One or more orders exists, all correct
12122 One ore more acceptable elaboration orders exist, and all of them
12123 work. In this case the program runs successfully. This state of
12124 affairs can be guaranteed by following the rule we gave above, but
12125 may be true even if the rule is not followed.
12126 @end table
12128 @noindent
12129 Note that one additional advantage of following our Elaborate_All rule
12130 is that the program continues to stay in the ideal (all orders OK) state
12131 even if maintenance
12132 changes some bodies of some subprograms. Conversely, if a program that does
12133 not follow this rule happens to be safe at some point, this state of affairs
12134 may deteriorate silently as a result of maintenance changes.
12136 You may have noticed that the above discussion did not mention
12137 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
12138 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
12139 code in the body makes calls to some other unit, so it is still necessary
12140 to use @code{Elaborate_All} on such units.
12142 @node Controlling Elaboration in GNAT - Internal Calls
12143 @section Controlling Elaboration in GNAT - Internal Calls
12145 @noindent
12146 In the case of internal calls, i.e. calls within a single package, the
12147 programmer has full control over the order of elaboration, and it is up
12148 to the programmer to elaborate declarations in an appropriate order. For
12149 example writing:
12151 @smallexample
12152 @group
12153 @cartouche
12154 @b{function} One @b{return} Float;
12156 Q : Float := One;
12158 @b{function} One @b{return} Float @b{is}
12159 @b{begin}
12160      return 1.0;
12161 @b{end} One;
12162 @end cartouche
12163 @end group
12164 @end smallexample
12166 @noindent
12167 will obviously raise @code{Program_Error} at run time, because function
12168 One will be called before its body is elaborated. In this case GNAT will
12169 generate a warning that the call will raise @code{Program_Error}:
12171 @smallexample
12172 @group
12173 @cartouche
12174  1. procedure y is
12175  2.    function One return Float;
12176  3.
12177  4.    Q : Float := One;
12178                     |
12179     >>> warning: cannot call "One" before body is elaborated
12180     >>> warning: Program_Error will be raised at run time
12182  5.
12183  6.    function One return Float is
12184  7.    begin
12185  8.         return 1.0;
12186  9.    end One;
12188 11. begin
12189 12.    null;
12190 13. end;
12191 @end cartouche
12192 @end group
12193 @end smallexample
12195 @noindent
12196 Note that in this particular case, it is likely that the call is safe, because
12197 the function @code{One} does not access any global variables.
12198 Nevertheless in Ada 95, we do not want the validity of the check to depend on
12199 the contents of the body (think about the separate compilation case), so this
12200 is still wrong, as we discussed in the previous sections.
12202 The error is easily corrected by rearranging the declarations so that the
12203 body of One appears before the declaration containing the call
12204 (note that in Ada 95,
12205 declarations can appear in any order, so there is no restriction that
12206 would prevent this reordering, and if we write:
12208 @smallexample
12209 @group
12210 @cartouche
12211 @b{function} One @b{return} Float;
12213 @b{function} One @b{return} Float @b{is}
12214 @b{begin}
12215      return 1.0;
12216 @b{end} One;
12218 Q : Float := One;
12219 @end cartouche
12220 @end group
12221 @end smallexample
12223 @noindent
12224 then all is well, no warning is generated, and no
12225 @code{Program_Error} exception
12226 will be raised.
12227 Things are more complicated when a chain of subprograms is executed:
12229 @smallexample
12230 @group
12231 @cartouche
12232 @b{function} A @b{return} Integer;
12233 @b{function} B @b{return} Integer;
12234 @b{function} C @b{return} Integer;
12236 @b{function} B @b{return} Integer @b{is begin return} A; @b{end};
12237 @b{function} C @b{return} Integer @b{is begin return} B; @b{end};
12239 X : Integer := C;
12241 @b{function} A @b{return} Integer @b{is begin return} 1; @b{end};
12242 @end cartouche
12243 @end group
12244 @end smallexample
12246 @noindent
12247 Now the call to @code{C}
12248 at elaboration time in the declaration of @code{X} is correct, because
12249 the body of @code{C} is already elaborated,
12250 and the call to @code{B} within the body of
12251 @code{C} is correct, but the call
12252 to @code{A} within the body of @code{B} is incorrect, because the body
12253 of @code{A} has not been elaborated, so @code{Program_Error}
12254 will be raised on the call to @code{A}.
12255 In this case GNAT will generate a
12256 warning that @code{Program_Error} may be
12257 raised at the point of the call. Let's look at the warning:
12259 @smallexample
12260 @group
12261 @cartouche
12262  1. procedure x is
12263  2.    function A return Integer;
12264  3.    function B return Integer;
12265  4.    function C return Integer;
12266  5.
12267  6.    function B return Integer is begin return A; end;
12268                                                     |
12269     >>> warning: call to "A" before body is elaborated may
12270                  raise Program_Error
12271     >>> warning: "B" called at line 7
12272     >>> warning: "C" called at line 9
12274  7.    function C return Integer is begin return B; end;
12275  8.
12276  9.    X : Integer := C;
12278 11.    function A return Integer is begin return 1; end;
12280 13. begin
12281 14.    null;
12282 15. end;
12283 @end cartouche
12284 @end group
12285 @end smallexample
12287 @noindent
12288 Note that the message here says "may raise", instead of the direct case,
12289 where the message says "will be raised". That's because whether
12290 @code{A} is
12291 actually called depends in general on run-time flow of control.
12292 For example, if the body of @code{B} said
12294 @smallexample
12295 @group
12296 @cartouche
12297 @b{function} B @b{return} Integer @b{is}
12298 @b{begin}
12299    @b{if} some-condition-depending-on-input-data @b{then}
12300       @b{return} A;
12301    @b{else}
12302       @b{return} 1;
12303    @b{end if};
12304 @b{end} B;
12305 @end cartouche
12306 @end group
12307 @end smallexample
12309 @noindent
12310 then we could not know until run time whether the incorrect call to A would
12311 actually occur, so @code{Program_Error} might
12312 or might not be raised. It is possible for a compiler to
12313 do a better job of analyzing bodies, to
12314 determine whether or not @code{Program_Error}
12315 might be raised, but it certainly
12316 couldn't do a perfect job (that would require solving the halting problem
12317 and is provably impossible), and because this is a warning anyway, it does
12318 not seem worth the effort to do the analysis. Cases in which it
12319 would be relevant are rare.
12321 In practice, warnings of either of the forms given
12322 above will usually correspond to
12323 real errors, and should be examined carefully and eliminated.
12324 In the rare case where a warning is bogus, it can be suppressed by any of
12325 the following methods:
12327 @itemize @bullet
12328 @item
12329 Compile with the @option{-gnatws} switch set
12331 @item
12332 Suppress @code{Elaboration_Checks} for the called subprogram
12334 @item
12335 Use pragma @code{Warnings_Off} to turn warnings off for the call
12336 @end itemize
12338 @noindent
12339 For the internal elaboration check case,
12340 GNAT by default generates the
12341 necessary run-time checks to ensure
12342 that @code{Program_Error} is raised if any
12343 call fails an elaboration check. Of course this can only happen if a
12344 warning has been issued as described above. The use of pragma
12345 @code{Suppress (Elaboration_Checks)} may (but is not guaranteed to) suppress
12346 some of these checks, meaning that it may be possible (but is not
12347 guaranteed) for a program to be able to call a subprogram whose body
12348 is not yet elaborated, without raising a @code{Program_Error} exception.
12350 @node Controlling Elaboration in GNAT - External Calls
12351 @section Controlling Elaboration in GNAT - External Calls
12353 @noindent
12354 The previous section discussed the case in which the execution of a
12355 particular thread of elaboration code occurred entirely within a
12356 single unit. This is the easy case to handle, because a programmer
12357 has direct and total control over the order of elaboration, and
12358 furthermore, checks need only be generated in cases which are rare
12359 and which the compiler can easily detect.
12360 The situation is more complex when separate compilation is taken into account.
12361 Consider the following:
12363 @smallexample
12364 @cartouche
12365 @group
12366 @b{package} Math @b{is}
12367    @b{function} Sqrt (Arg : Float) @b{return} Float;
12368 @b{end} Math;
12370 @b{package body} Math @b{is}
12371    @b{function} Sqrt (Arg : Float) @b{return} Float @b{is}
12372    @b{begin}
12373          ...
12374    @b{end} Sqrt;
12375 @b{end} Math;
12376 @end group
12377 @group
12378 @b{with} Math;
12379 @b{package} Stuff @b{is}
12380    X : Float := Math.Sqrt (0.5);
12381 @b{end} Stuff;
12383 @b{with} Stuff;
12384 @b{procedure} Main @b{is}
12385 @b{begin}
12386    ...
12387 @b{end} Main;
12388 @end group
12389 @end cartouche
12390 @end smallexample
12392 @noindent
12393 where @code{Main} is the main program. When this program is executed, the
12394 elaboration code must first be executed, and one of the jobs of the
12395 binder is to determine the order in which the units of a program are
12396 to be elaborated. In this case we have four units: the spec and body
12397 of @code{Math},
12398 the spec of @code{Stuff} and the body of @code{Main}).
12399 In what order should the four separate sections of elaboration code
12400 be executed?
12402 There are some restrictions in the order of elaboration that the binder
12403 can choose. In particular, if unit U has a @code{with}
12404 for a package @code{X}, then you
12405 are assured that the spec of @code{X}
12406 is elaborated before U , but you are
12407 not assured that the body of @code{X}
12408 is elaborated before U.
12409 This means that in the above case, the binder is allowed to choose the
12410 order:
12412 @smallexample
12413 spec of Math
12414 spec of Stuff
12415 body of Math
12416 body of Main
12417 @end smallexample
12419 @noindent
12420 but that's not good, because now the call to @code{Math.Sqrt}
12421 that happens during
12422 the elaboration of the @code{Stuff}
12423 spec happens before the body of @code{Math.Sqrt} is
12424 elaborated, and hence causes @code{Program_Error} exception to be raised.
12425 At first glance, one might say that the binder is misbehaving, because
12426 obviously you want to elaborate the body of something you @code{with}
12427 first, but
12428 that is not a general rule that can be followed in all cases. Consider
12430 @smallexample
12431 @group
12432 @cartouche
12433 @b{package} X @b{is} ...
12435 @b{package} Y @b{is} ...
12437 @b{with} X;
12438 @b{package body} Y @b{is} ...
12440 @b{with} Y;
12441 @b{package body} X @b{is} ...
12442 @end cartouche
12443 @end group
12444 @end smallexample
12446 @noindent
12447 This is a common arrangement, and, apart from the order of elaboration
12448 problems that might arise in connection with elaboration code, this works fine.
12449 A rule that says that you must first elaborate the body of anything you
12450 @code{with} cannot work in this case:
12451 the body of @code{X} @code{with}'s @code{Y},
12452 which means you would have to
12453 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
12454 which means
12455 you have to elaborate the body of @code{X} first, but ... and we have a
12456 loop that cannot be broken.
12458 It is true that the binder can in many cases guess an order of elaboration
12459 that is unlikely to cause a @code{Program_Error}
12460 exception to be raised, and it tries to do so (in the
12461 above example of @code{Math/Stuff/Spec}, the GNAT binder will
12462 by default
12463 elaborate the body of @code{Math} right after its spec, so all will be well).
12465 However, a program that blindly relies on the binder to be helpful can
12466 get into trouble, as we discussed in the previous sections, so
12467 GNAT
12468 provides a number of facilities for assisting the programmer in
12469 developing programs that are robust with respect to elaboration order.
12471 @node Default Behavior in GNAT - Ensuring Safety
12472 @section Default Behavior in GNAT - Ensuring Safety
12474 @noindent
12475 The default behavior in GNAT ensures elaboration safety. In its
12476 default mode GNAT implements the
12477 rule we previously described as the right approach. Let's restate it:
12479 @itemize
12480 @item
12481 @emph{If a unit has elaboration code that can directly or indirectly make a
12482 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
12483 in a @code{with}'ed unit, then if the @code{with}'ed unit
12484 does not have pragma @code{Pure} or
12485 @code{Preelaborate}, then the client should have an
12486 @code{Elaborate_All} for the @code{with}'ed unit.}
12487 @end itemize
12489 @noindent
12490 By following this rule a client
12491 is assured that calls and instantiations can be made without risk of an exception.
12493 In this mode GNAT traces all calls that are potentially made from
12494 elaboration code, and puts in any missing implicit @code{Elaborate_All}
12495 pragmas.
12496 The advantage of this approach is that no elaboration problems
12497 are possible if the binder can find an elaboration order that is
12498 consistent with these implicit @code{Elaborate_All} pragmas. The
12499 disadvantage of this approach is that no such order may exist.
12501 If the binder does not generate any diagnostics, then it means that it
12502 has found an elaboration order that is guaranteed to be safe. However,
12503 the binder may still be relying on implicitly generated
12504 @code{Elaborate_All} pragmas so portability to other compilers than
12505 GNAT is not guaranteed.
12507 If it is important to guarantee portability, then the compilations should
12508 use the
12509 @option{-gnatwl}
12510 (warn on elaboration problems) switch. This will cause warning messages
12511 to be generated indicating the missing @code{Elaborate_All} pragmas.
12512 Consider the following source program:
12514 @smallexample
12515 @group
12516 @cartouche
12517 @b{with} k;
12518 @b{package} j @b{is}
12519   m : integer := k.r;
12520 @b{end};
12521 @end cartouche
12522 @end group
12523 @end smallexample
12525 @noindent
12526 where it is clear that there
12527 should be a pragma @code{Elaborate_All}
12528 for unit @code{k}. An implicit pragma will be generated, and it is
12529 likely that the binder will be able to honor it. However,
12530 it is safer to include the pragma explicitly in the source. If this
12531 unit is compiled with the
12532 @option{-gnatwl}
12533 switch, then the compiler outputs a warning:
12535 @smallexample
12536 @group
12537 @cartouche
12538 1. with k;
12539 2. package j is
12540 3.   m : integer := k.r;
12541                      |
12542    >>> warning: call to "r" may raise Program_Error
12543    >>> warning: missing pragma Elaborate_All for "k"
12545 4. end;
12546 @end cartouche
12547 @end group
12548 @end smallexample
12550 @noindent
12551 and these warnings can be used as a guide for supplying manually
12552 the missing pragmas.
12554 This default mode is more restrictive than the Ada Reference
12555 Manual, and it is possible to construct programs which will compile
12556 using the dynamic model described there, but will run into a
12557 circularity using the safer static model we have described.
12559 Of course any Ada compiler must be able to operate in a mode
12560 consistent with the requirements of the Ada Reference Manual,
12561 and in particular must have the capability of implementing the
12562 standard dynamic model of elaboration with run-time checks.
12564 In GNAT, this standard mode can be achieved either by the use of
12565 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
12566 command, or by the use of the configuration pragma:
12568 @smallexample
12569 pragma Elaboration_Checks (RM);
12570 @end smallexample
12572 @noindent
12573 Either approach will cause the unit affected to be compiled using the
12574 standard dynamic run-time elaboration checks described in the Ada
12575 Reference Manual. The static model is generally preferable, since it
12576 is clearly safer to rely on compile and link time checks rather than
12577 run-time checks. However, in the case of legacy code, it may be
12578 difficult to meet the requirements of the static model. This
12579 issue is further discussed in
12580 @ref{What to Do If the Default Elaboration Behavior Fails}.
12582 Note that the static model provides a strict subset of the allowed
12583 behavior and programs of the Ada Reference Manual, so if you do
12584 adhere to the static model and no circularities exist,
12585 then you are assured that your program will
12586 work using the dynamic model.
12588 @node Elaboration Issues for Library Tasks
12589 @section Elaboration Issues for Library Tasks
12590 @cindex Library tasks, elaboration issues
12591 @cindex Elaboration of library tasks
12593 @noindent
12594 In this section we examine special elaboration issues that arise for
12595 programs that declare library level tasks.
12597 Generally the model of execution of an Ada program is that all units are
12598 elaborated, and then execution of the program starts. However, the
12599 declaration of library tasks definitely does not fit this model. The
12600 reason for this is that library tasks start as soon as they are declared
12601 (more precisely, as soon as the statement part of the enclosing package
12602 body is reached), that is to say before elaboration
12603 of the program is complete. This means that if such a task calls a
12604 subprogram, or an entry in another task, the callee may or may not be
12605 elaborated yet, and in the standard
12606 Reference Manual model of dynamic elaboration checks, you can even
12607 get timing dependent Program_Error exceptions, since there can be
12608 a race between the elaboration code and the task code.
12610 The static model of elaboration in GNAT seeks to avoid all such
12611 dynamic behavior, by being conservative, and the conservative
12612 approach in this particular case is to assume that all the code
12613 in a task body is potentially executed at elaboration time if
12614 a task is declared at the library level.
12616 This can definitely result in unexpected circularities. Consider
12617 the following example
12619 @smallexample
12620 package Decls is
12621   task Lib_Task is
12622      entry Start;
12623   end Lib_Task;
12625   type My_Int is new Integer;
12627   function Ident (M : My_Int) return My_Int;
12628 end Decls;
12630 with Utils;
12631 package body Decls is
12632   task body Lib_Task is
12633   begin
12634      accept Start;
12635      Utils.Put_Val (2);
12636   end Lib_Task;
12638   function Ident (M : My_Int) return My_Int is
12639   begin
12640      return M;
12641   end Ident;
12642 end Decls;
12644 with Decls;
12645 package Utils is
12646   procedure Put_Val (Arg : Decls.My_Int);
12647 end Utils;
12649 with Text_IO;
12650 package body Utils is
12651   procedure Put_Val (Arg : Decls.My_Int) is
12652   begin
12653      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
12654   end Put_Val;
12655 end Utils;
12657 with Decls;
12658 procedure Main is
12659 begin
12660    Decls.Lib_Task.Start;
12661 end;
12662 @end smallexample
12664 @noindent
12665 If the above example is compiled in the default static elaboration
12666 mode, then a circularity occurs. The circularity comes from the call
12667 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
12668 this call occurs in elaboration code, we need an implicit pragma
12669 @code{Elaborate_All} for @code{Utils}. This means that not only must
12670 the spec and body of @code{Utils} be elaborated before the body
12671 of @code{Decls}, but also the spec and body of any unit that is
12672 @code{with'ed} by the body of @code{Utils} must also be elaborated before
12673 the body of @code{Decls}. This is the transitive implication of
12674 pragma @code{Elaborate_All} and it makes sense, because in general
12675 the body of @code{Put_Val} might have a call to something in a
12676 @code{with'ed} unit.
12678 In this case, the body of Utils (actually its spec) @code{with's}
12679 @code{Decls}. Unfortunately this means that the body of @code{Decls}
12680 must be elaborated before itself, in case there is a call from the
12681 body of @code{Utils}.
12683 Here is the exact chain of events we are worrying about:
12685 @enumerate
12686 @item
12687 In the body of @code{Decls} a call is made from within the body of a library
12688 task to a subprogram in the package @code{Utils}. Since this call may
12689 occur at elaboration time (given that the task is activated at elaboration
12690 time), we have to assume the worst, i.e. that the
12691 call does happen at elaboration time.
12693 @item
12694 This means that the body and spec of @code{Util} must be elaborated before
12695 the body of @code{Decls} so that this call does not cause an access before
12696 elaboration.
12698 @item
12699 Within the body of @code{Util}, specifically within the body of
12700 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
12701 by this package.
12703 @item
12704 One such @code{with}'ed package is package @code{Decls}, so there
12705 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
12706 In fact there is such a call in this example, but we would have to
12707 assume that there was such a call even if it were not there, since
12708 we are not supposed to write the body of @code{Decls} knowing what
12709 is in the body of @code{Utils}; certainly in the case of the
12710 static elaboration model, the compiler does not know what is in
12711 other bodies and must assume the worst.
12713 @item
12714 This means that the spec and body of @code{Decls} must also be
12715 elaborated before we elaborate the unit containing the call, but
12716 that unit is @code{Decls}! This means that the body of @code{Decls}
12717 must be elaborated before itself, and that's a circularity.
12718 @end enumerate
12720 @noindent
12721 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
12722 the body of @code{Decls} you will get a true Ada Reference Manual
12723 circularity that makes the program illegal.
12725 In practice, we have found that problems with the static model of
12726 elaboration in existing code often arise from library tasks, so
12727 we must address this particular situation.
12729 Note that if we compile and run the program above, using the dynamic model of
12730 elaboration (that is to say use the @option{-gnatE} switch),
12731 then it compiles, binds,
12732 links, and runs, printing the expected result of 2. Therefore in some sense
12733 the circularity here is only apparent, and we need to capture
12734 the properties of this program that  distinguish it from other library-level
12735 tasks that have real elaboration problems.
12737 We have four possible answers to this question:
12739 @itemize @bullet
12741 @item
12742 Use the dynamic model of elaboration.
12744 If we use the @option{-gnatE} switch, then as noted above, the program works.
12745 Why is this? If we examine the task body, it is apparent that the task cannot
12746 proceed past the
12747 @code{accept} statement until after elaboration has been completed, because
12748 the corresponding entry call comes from the main program, not earlier.
12749 This is why the dynamic model works here. But that's really giving
12750 up on a precise analysis, and we prefer to take this approach only if we cannot
12751 solve the
12752 problem in any other manner. So let us examine two ways to reorganize
12753 the program to avoid the potential elaboration problem.
12755 @item
12756 Split library tasks into separate packages.
12758 Write separate packages, so that library tasks are isolated from
12759 other declarations as much as possible. Let us look at a variation on
12760 the above program.
12762 @smallexample
12763 package Decls1 is
12764   task Lib_Task is
12765      entry Start;
12766   end Lib_Task;
12767 end Decls1;
12769 with Utils;
12770 package body Decls1 is
12771   task body Lib_Task is
12772   begin
12773      accept Start;
12774      Utils.Put_Val (2);
12775   end Lib_Task;
12776 end Decls1;
12778 package Decls2 is
12779   type My_Int is new Integer;
12780   function Ident (M : My_Int) return My_Int;
12781 end Decls2;
12783 with Utils;
12784 package body Decls2 is
12785   function Ident (M : My_Int) return My_Int is
12786   begin
12787      return M;
12788   end Ident;
12789 end Decls2;
12791 with Decls2;
12792 package Utils is
12793   procedure Put_Val (Arg : Decls2.My_Int);
12794 end Utils;
12796 with Text_IO;
12797 package body Utils is
12798   procedure Put_Val (Arg : Decls2.My_Int) is
12799   begin
12800      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
12801   end Put_Val;
12802 end Utils;
12804 with Decls1;
12805 procedure Main is
12806 begin
12807    Decls1.Lib_Task.Start;
12808 end;
12809 @end smallexample
12811 @noindent
12812 All we have done is to split @code{Decls} into two packages, one
12813 containing the library task, and one containing everything else. Now
12814 there is no cycle, and the program compiles, binds, links and executes
12815 using the default static model of elaboration.
12817 @item
12818 Declare separate task types.
12820 A significant part of the problem arises because of the use of the
12821 single task declaration form. This means that the elaboration of
12822 the task type, and the elaboration of the task itself (i.e. the
12823 creation of the task) happen at the same time. A good rule
12824 of style in Ada 95 is to always create explicit task types. By
12825 following the additional step of placing task objects in separate
12826 packages from the task type declaration, many elaboration problems
12827 are avoided. Here is another modified example of the example program:
12829 @smallexample
12830 package Decls is
12831   task type Lib_Task_Type is
12832      entry Start;
12833   end Lib_Task_Type;
12835   type My_Int is new Integer;
12837   function Ident (M : My_Int) return My_Int;
12838 end Decls;
12840 with Utils;
12841 package body Decls is
12842   task body Lib_Task_Type is
12843   begin
12844      accept Start;
12845      Utils.Put_Val (2);
12846   end Lib_Task_Type;
12848   function Ident (M : My_Int) return My_Int is
12849   begin
12850      return M;
12851   end Ident;
12852 end Decls;
12854 with Decls;
12855 package Utils is
12856   procedure Put_Val (Arg : Decls.My_Int);
12857 end Utils;
12859 with Text_IO;
12860 package body Utils is
12861   procedure Put_Val (Arg : Decls.My_Int) is
12862   begin
12863      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
12864   end Put_Val;
12865 end Utils;
12867 with Decls;
12868 package Declst is
12869    Lib_Task : Decls.Lib_Task_Type;
12870 end Declst;
12872 with Declst;
12873 procedure Main is
12874 begin
12875    Declst.Lib_Task.Start;
12876 end;
12877 @end smallexample
12879 @noindent
12880 What we have done here is to replace the @code{task} declaration in
12881 package @code{Decls} with a @code{task type} declaration. Then we
12882 introduce a separate package @code{Declst} to contain the actual
12883 task object. This separates the elaboration issues for
12884 the @code{task type}
12885 declaration, which causes no trouble, from the elaboration issues
12886 of the task object, which is also unproblematic, since it is now independent
12887 of the elaboration of  @code{Utils}.
12888 This separation of concerns also corresponds to
12889 a generally sound engineering principle of separating declarations
12890 from instances. This version of the program also compiles, binds, links,
12891 and executes, generating the expected output.
12893 @item
12894 Use No_Entry_Calls_In_Elaboration_Code restriction.
12895 @cindex No_Entry_Calls_In_Elaboration_Code
12897 The previous two approaches described how a program can be restructured
12898 to avoid the special problems caused by library task bodies. in practice,
12899 however, such restructuring may be difficult to apply to existing legacy code,
12900 so we must consider solutions that do not require massive rewriting.
12902 Let us consider more carefully why our original sample program works
12903 under the dynamic model of elaboration. The reason is that the code
12904 in the task body blocks immediately on the @code{accept}
12905 statement. Now of course there is nothing to prohibit elaboration
12906 code from making entry calls (for example from another library level task),
12907 so we cannot tell in isolation that
12908 the task will not execute the accept statement  during elaboration.
12910 However, in practice it is very unusual to see elaboration code
12911 make any entry calls, and the pattern of tasks starting
12912 at elaboration time and then immediately blocking on @code{accept} or
12913 @code{select} statements is very common. What this means is that
12914 the compiler is being too pessimistic when it analyzes the
12915 whole package body as though it might be executed at elaboration
12916 time.
12918 If we know that the elaboration code contains no entry calls, (a very safe
12919 assumption most of the time, that could almost be made the default
12920 behavior), then we can compile all units of the program under control
12921 of the following configuration pragma:
12923 @smallexample
12924 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
12925 @end smallexample
12927 @noindent
12928 This pragma can be placed in the @file{gnat.adc} file in the usual
12929 manner. If we take our original unmodified program and compile it
12930 in the presence of a @file{gnat.adc} containing the above pragma,
12931 then once again, we can compile, bind, link, and execute, obtaining
12932 the expected result. In the presence of this pragma, the compiler does
12933 not trace calls in a task body, that appear after the first @code{accept}
12934 or @code{select} statement, and therefore does not report a potential
12935 circularity in the original program.
12937 The compiler will check to the extent it can that the above
12938 restriction is not violated, but it is not always possible to do a
12939 complete check at compile time, so it is important to use this
12940 pragma only if the stated restriction is in fact met, that is to say
12941 no task receives an entry call before elaboration of all units is completed.
12943 @end itemize
12945 @node Mixing Elaboration Models
12946 @section Mixing Elaboration Models
12947 @noindent
12948 So far, we have assumed that the entire program is either compiled
12949 using the dynamic model or static model, ensuring consistency. It
12950 is possible to mix the two models, but rules have to be followed
12951 if this mixing is done to ensure that elaboration checks are not
12952 omitted.
12954 The basic rule is that @emph{a unit compiled with the static model cannot
12955 be @code{with'ed} by a unit compiled with the dynamic model}. The
12956 reason for this is that in the static model, a unit assumes that
12957 its clients guarantee to use (the equivalent of) pragma
12958 @code{Elaborate_All} so that no elaboration checks are required
12959 in inner subprograms, and this assumption is violated if the
12960 client is compiled with dynamic checks.
12962 The precise rule is as follows. A unit that is compiled with dynamic
12963 checks can only @code{with} a unit that meets at least one of the
12964 following criteria:
12966 @itemize @bullet
12968 @item
12969 The @code{with'ed} unit is itself compiled with dynamic elaboration
12970 checks (that is with the @option{-gnatE} switch.
12972 @item
12973 The @code{with'ed} unit is an internal GNAT implementation unit from
12974 the System, Interfaces, Ada, or GNAT hierarchies.
12976 @item
12977 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
12979 @item
12980 The @code{with'ing} unit (that is the client) has an explicit pragma
12981 @code{Elaborate_All} for the @code{with'ed} unit.
12983 @end itemize
12985 @noindent
12986 If this rule is violated, that is if a unit with dynamic elaboration
12987 checks @code{with's} a unit that does not meet one of the above four
12988 criteria, then the binder (@code{gnatbind}) will issue a warning
12989 similar to that in the following example:
12991 @smallexample
12992 warning: "x.ads" has dynamic elaboration checks and with's
12993 warning:   "y.ads" which has static elaboration checks
12994 @end smallexample
12996 @noindent
12997 These warnings indicate that the rule has been violated, and that as a result
12998 elaboration checks may be missed in the resulting executable file.
12999 This warning may be suppressed using the @code{-ws} binder switch
13000 in the usual manner.
13002 One useful application of this mixing rule is in the case of a subsystem
13003 which does not itself @code{with} units from the remainder of the
13004 application. In this case, the entire subsystem can be compiled with
13005 dynamic checks to resolve a circularity in the subsystem, while
13006 allowing the main application that uses this subsystem to be compiled
13007 using the more reliable default static model.
13009 @node What to Do If the Default Elaboration Behavior Fails
13010 @section What to Do If the Default Elaboration Behavior Fails
13012 @noindent
13013 If the binder cannot find an acceptable order, it outputs detailed
13014 diagnostics. For example:
13015 @smallexample
13016 @group
13017 @iftex
13018 @leftskip=0cm
13019 @end iftex
13020 error: elaboration circularity detected
13021 info:   "proc (body)" must be elaborated before "pack (body)"
13022 info:     reason: Elaborate_All probably needed in unit "pack (body)"
13023 info:     recompile "pack (body)" with -gnatwl
13024 info:                             for full details
13025 info:       "proc (body)"
13026 info:         is needed by its spec:
13027 info:       "proc (spec)"
13028 info:         which is withed by:
13029 info:       "pack (body)"
13030 info:  "pack (body)" must be elaborated before "proc (body)"
13031 info:     reason: pragma Elaborate in unit "proc (body)"
13032 @end group
13034 @end smallexample
13036 @noindent
13037 In this case we have a cycle that the binder cannot break. On the one
13038 hand, there is an explicit pragma Elaborate in @code{proc} for
13039 @code{pack}. This means that the body of @code{pack} must be elaborated
13040 before the body of @code{proc}. On the other hand, there is elaboration
13041 code in @code{pack} that calls a subprogram in @code{proc}. This means
13042 that for maximum safety, there should really be a pragma
13043 Elaborate_All in @code{pack} for @code{proc} which would require that
13044 the body of @code{proc} be elaborated before the body of
13045 @code{pack}. Clearly both requirements cannot be satisfied.
13046 Faced with a circularity of this kind, you have three different options.
13048 @table @asis
13049 @item Fix the program
13050 The most desirable option from the point of view of long-term maintenance
13051 is to rearrange the program so that the elaboration problems are avoided.
13052 One useful technique is to place the elaboration code into separate
13053 child packages. Another is to move some of the initialization code to
13054 explicitly called subprograms, where the program controls the order
13055 of initialization explicitly. Although this is the most desirable option,
13056 it may be impractical and involve too much modification, especially in
13057 the case of complex legacy code.
13059 @item Perform dynamic checks
13060 If the compilations are done using the
13061 @option{-gnatE}
13062 (dynamic elaboration check) switch, then GNAT behaves in
13063 a quite different manner. Dynamic checks are generated for all calls
13064 that could possibly result in raising an exception. With this switch,
13065 the compiler does not generate implicit @code{Elaborate_All} pragmas.
13066 The behavior then is exactly as specified in the Ada 95 Reference Manual.
13067 The binder will generate an executable program that may or may not
13068 raise @code{Program_Error}, and then it is the programmer's job to ensure
13069 that it does not raise an exception. Note that it is important to
13070 compile all units with the switch, it cannot be used selectively.
13072 @item Suppress checks
13073 The drawback of dynamic checks is that they generate a
13074 significant overhead at run time, both in space and time. If you
13075 are absolutely sure that your program cannot raise any elaboration
13076 exceptions, and you still want to use the dynamic elaboration model,
13077 then you can use the configuration pragma
13078 @code{Suppress (Elaboration_Checks)} to suppress all such checks. For
13079 example this pragma could be placed in the @file{gnat.adc} file.
13081 @item Suppress checks selectively
13082 When you know that certain calls in elaboration code cannot possibly
13083 lead to an elaboration error, and the binder nevertheless generates warnings
13084 on those calls and inserts Elaborate_All pragmas that lead to elaboration
13085 circularities, it is possible to remove those warnings locally and obtain
13086 a program that will bind. Clearly this can be unsafe, and it is the
13087 responsibility of the programmer to make sure that the resulting program has
13088 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
13089 be used with different granularity to suppress warnings and break
13090 elaboration circularities:
13092 @itemize @bullet
13093 @item
13094 Place the pragma that names the called subprogram in the declarative part
13095 that contains the call.
13097 @item
13098 Place the pragma in the declarative part, without naming an entity. This
13099 disables warnings on all calls in the corresponding  declarative region.
13101 @item
13102 Place the pragma in the package spec that declares the called subprogram,
13103 and name the subprogram. This disables warnings on all elaboration calls to
13104 that subprogram.
13106 @item
13107 Place the pragma in the package spec that declares the called subprogram,
13108 without naming any entity. This disables warnings on all elaboration calls to
13109 all subprograms declared in this spec.
13110 @end itemize
13112 @noindent
13113 These four cases are listed in order of decreasing safety, and therefore
13114 require increasing programmer care in their application. Consider the
13115 following program:
13116 @smallexample
13118 package Pack1 is
13119   function F1 return Integer;
13120   X1 : Integer;
13121 end Pack1;
13123 package Pack2 is
13124   function F2 return Integer;
13125   function Pure (x : integer) return integer;
13126   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
13127   --  pragma Suppress (Elaboration_Check);              -- (4)
13128 end Pack2;
13130 with Pack2;
13131 package body Pack1 is
13132   function F1 return Integer is
13133   begin
13134     return 100;
13135   end F1;
13136   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
13137 begin
13138   declare
13139     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
13140     --  pragma Suppress(Elaboration_Check);             -- (2)
13141   begin
13142     X1 := Pack2.F2 + 1;                --  Elab. call (2)
13143   end;
13144 end Pack1;
13146 with Pack1;
13147 package body Pack2 is
13148   function F2 return Integer is
13149   begin
13150      return Pack1.F1;
13151   end F2;
13152   function Pure (x : integer) return integer is
13153   begin
13154      return x ** 3 - 3 * x;
13155   end;
13156 end Pack2;
13158 with Pack1, Ada.Text_IO;
13159 procedure Proc3 is
13160 begin
13161   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
13162 end Proc3;
13163 @end smallexample
13164 In the absence of any pragmas, an attempt to bind this program produces
13165 the following diagnostics:
13166 @smallexample
13167 @group
13168 @iftex
13169 @leftskip=.5cm
13170 @end iftex
13171 error: elaboration circularity detected
13172 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
13173 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
13174 info:       recompile "pack1 (body)" with -gnatwl for full details
13175 info:          "pack1 (body)"
13176 info:             must be elaborated along with its spec:
13177 info:          "pack1 (spec)"
13178 info:             which is withed by:
13179 info:          "pack2 (body)"
13180 info:             which must be elaborated along with its spec:
13181 info:          "pack2 (spec)"
13182 info:             which is withed by:
13183 info:          "pack1 (body)"
13184 @end group
13185 @end smallexample
13186 The sources of the circularity are the two calls to @code{Pack2.Pure} and
13187 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
13188 F2 is safe, even though F2 calls F1, because the call appears after the
13189 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
13190 remove the warning on the call. It is also possible to use pragma (2)
13191 because there are no other potentially unsafe calls in the block.
13193 @noindent
13194 The call to @code{Pure} is safe because this function does not depend on the
13195 state of @code{Pack2}. Therefore any call to this function is safe, and it
13196 is correct to place pragma (3) in the corresponding package spec.
13198 @noindent
13199 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
13200 warnings on all calls to functions declared therein. Note that this is not
13201 necessarily safe, and requires more detailed examination of the subprogram
13202 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
13203 be already elaborated.
13204 @end table
13206 @noindent
13207 It is hard to generalize on which of these four approaches should be
13208 taken. Obviously if it is possible to fix the program so that the default
13209 treatment works, this is preferable, but this may not always be practical.
13210 It is certainly simple enough to use
13211 @option{-gnatE}
13212 but the danger in this case is that, even if the GNAT binder
13213 finds a correct elaboration order, it may not always do so,
13214 and certainly a binder from another Ada compiler might not. A
13215 combination of testing and analysis (for which the warnings generated
13216 with the
13217 @option{-gnatwl}
13218 switch can be useful) must be used to ensure that the program is free
13219 of errors. One switch that is useful in this testing is the
13220 @code{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
13221 switch for
13222 @code{gnatbind}.
13223 Normally the binder tries to find an order that has the best chance of
13224 of avoiding elaboration problems. With this switch, the binder
13225 plays a devil's advocate role, and tries to choose the order that
13226 has the best chance of failing. If your program works even with this
13227 switch, then it has a better chance of being error free, but this is still
13228 not a guarantee.
13230 For an example of this approach in action, consider the C-tests (executable
13231 tests) from the ACVC suite. If these are compiled and run with the default
13232 treatment, then all but one of them succeed without generating any error
13233 diagnostics from the binder. However, there is one test that fails, and
13234 this is not surprising, because the whole point of this test is to ensure
13235 that the compiler can handle cases where it is impossible to determine
13236 a correct order statically, and it checks that an exception is indeed
13237 raised at run time.
13239 This one test must be compiled and run using the
13240 @option{-gnatE}
13241 switch, and then it passes. Alternatively, the entire suite can
13242 be run using this switch. It is never wrong to run with the dynamic
13243 elaboration switch if your code is correct, and we assume that the
13244 C-tests are indeed correct (it is less efficient, but efficiency is
13245 not a factor in running the ACVC tests.)
13247 @node Elaboration for Access-to-Subprogram Values
13248 @section Elaboration for Access-to-Subprogram Values
13249 @cindex Access-to-subprogram
13251 @noindent
13252 The introduction of access-to-subprogram types in Ada 95 complicates
13253 the handling of elaboration. The trouble is that it becomes
13254 impossible to tell at compile time which procedure
13255 is being called. This means that it is not possible for the binder
13256 to analyze the elaboration requirements in this case.
13258 If at the point at which the access value is created
13259 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
13260 the body of the subprogram is
13261 known to have been elaborated, then the access value is safe, and its use
13262 does not require a check. This may be achieved by appropriate arrangement
13263 of the order of declarations if the subprogram is in the current unit,
13264 or, if the subprogram is in another unit, by using pragma
13265 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
13266 on the referenced unit.
13268 If the referenced body is not known to have been elaborated at the point
13269 the access value is created, then any use of the access value must do a
13270 dynamic check, and this dynamic check will fail and raise a
13271 @code{Program_Error} exception if the body has not been elaborated yet.
13272 GNAT will generate the necessary checks, and in addition, if the
13273 @option{-gnatwl}
13274 switch is set, will generate warnings that such checks are required.
13276 The use of dynamic dispatching for tagged types similarly generates
13277 a requirement for dynamic checks, and premature calls to any primitive
13278 operation of a tagged type before the body of the operation has been elaborated,
13279 will result in the raising of @code{Program_Error}.
13281 @node Summary of Procedures for Elaboration Control
13282 @section Summary of Procedures for Elaboration Control
13283 @cindex Elaboration control
13285 @noindent
13286 First, compile your program with the default options, using none of
13287 the special elaboration control switches. If the binder successfully
13288 binds your program, then you can be confident that, apart from issues
13289 raised by the use of access-to-subprogram types and dynamic dispatching,
13290 the program is free of elaboration errors. If it is important that the
13291 program be portable, then use the
13292 @option{-gnatwl}
13293 switch to generate warnings about missing @code{Elaborate_All}
13294 pragmas, and supply the missing pragmas.
13296 If the program fails to bind using the default static elaboration
13297 handling, then you can fix the program to eliminate the binder
13298 message, or recompile the entire program with the
13299 @option{-gnatE} switch to generate dynamic elaboration checks,
13300 and, if you are sure there really are no elaboration problems,
13301 use a global pragma @code{Suppress (Elaboration_Checks)}.
13303 @node Other Elaboration Order Considerations
13304 @section Other Elaboration Order Considerations
13305 @noindent
13306 This section has been entirely concerned with the issue of finding a valid
13307 elaboration order, as defined by the Ada Reference Manual. In a case
13308 where several elaboration orders are valid, the task is to find one
13309 of the possible valid elaboration orders (and the static model in GNAT
13310 will ensure that this is achieved).
13312 The purpose of the elaboration rules in the Ada Reference Manual is to
13313 make sure that no entity is accessed before it has been elaborated. For
13314 a subprogram, this means that the spec and body must have been elaborated
13315 before the subprogram is called. For an object, this means that the object
13316 must have been elaborated before its value is read or written. A violation
13317 of either of these two requirements is an access before elaboration order,
13318 and this section has been all about avoiding such errors.
13320 In the case where more than one order of elaboration is possible, in the
13321 sense that access before elaboration errors are avoided, then any one of
13322 the orders is "correct" in the sense that it meets the requirements of
13323 the Ada Reference Manual, and no such error occurs.
13325 However, it may be the case for a given program, that there are
13326 constraints on the order of elaboration that come not from consideration
13327 of avoiding elaboration errors, but rather from extra-lingual logic
13328 requirements. Consider this example:
13330 @smallexample
13331 with Init_Constants;
13332 package Constants is
13333    X : Integer := 0;
13334    Y : Integer := 0;
13335 end Constants;
13337 package Init_Constants is
13338    procedure Calc;
13339 end Init_Constants;
13341 with Constants;
13342 package body Init_Constants is
13343    procedure Calc is begin null; end;
13344 begin
13345    Constants.X := 3;
13346    Constants.Y := 4;
13347 end Init_Constants;
13349 with Constants;
13350 package Calc is
13351    Z : Integer := Constants.X + Constants.Y;
13352 end Calc;
13354 with Calc;
13355 with Text_IO; use Text_IO;
13356 procedure Main is
13357 begin
13358    Put_Line (Calc.Z'Img);
13359 end Main;
13360 @end smallexample
13362 @noindent
13363 In this example, there is more than one valid order of elaboration. For
13364 example both the following are correct orders:
13366 @smallexample
13367 Init_Constants spec
13368 Constants spec
13369 Calc spec
13370 Main body
13371 Init_Constants body
13373   and
13375 Init_Constants spec
13376 Init_Constants body
13377 Constants spec
13378 Calc spec
13379 Main body
13380 @end smallexample
13382 @noindent
13383 There is no language rule to prefer one or the other, both are correct
13384 from an order of elaboration point of view. But the programmatic effects
13385 of the two orders are very different. In the first, the elaboration routine
13386 of @code{Calc} initializes @code{Z} to zero, and then the main program
13387 runs with this value of zero. But in the second order, the elaboration
13388 routine of @code{Calc} runs after the body of Init_Constants has set
13389 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
13390 runs.
13392 One could perhaps by applying pretty clever non-artificial intelligence
13393 to the situation guess that it is more likely that the second order of
13394 elaboration is the one desired, but there is no formal linguistic reason
13395 to prefer one over the other. In fact in this particular case, GNAT will
13396 prefer the second order, because of the rule that bodies are elaborated
13397 as soon as possible, but it's just luck that this is what was wanted
13398 (if indeed the second order was preferred).
13400 If the program cares about the order of elaboration routines in a case like
13401 this, it is important to specify the order required. In this particular
13402 case, that could have been achieved by adding to the spec of Calc:
13404 @smallexample
13405 pragma Elaborate_All (Constants);
13406 @end smallexample
13408 @noindent
13409 which requires that the body (if any) and spec of @code{Constants},
13410 as well as the body and spec of any unit @code{with}'ed by
13411 @code{Constants} be elaborated before @code{Calc} is elaborated.
13413 Clearly no automatic method can always guess which alternative you require,
13414 and if you are working with legacy code that had constraints of this kind
13415 which were not properly specified by adding @code{Elaborate} or
13416 @code{Elaborate_All} pragmas, then indeed it is possible that two different
13417 compilers can choose different orders.
13419 The @code{gnatbind}
13420 @code{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
13421 out problems. This switch causes bodies to be elaborated as late as possible
13422 instead of as early as possible. In the example above, it would have forced
13423 the choice of the first elaboration order. If you get different results
13424 when using this switch, and particularly if one set of results is right,
13425 and one is wrong as far as you are concerned, it shows that you have some
13426 missing @code{Elaborate} pragmas. For the example above, we have the
13427 following output:
13429 @smallexample
13430 gnatmake -f -q main
13431 main
13433 gnatmake -f -q main -bargs -p
13434 main
13436 @end smallexample
13438 @noindent
13439 It is of course quite unlikely that both these results are correct, so
13440 it is up to you in a case like this to investigate the source of the
13441 difference, by looking at the two elaboration orders that are chosen,
13442 and figuring out which is correct, and then adding the necessary
13443 @code{Elaborate_All} pragmas to ensure the desired order.
13445 @node The Cross-Referencing Tools gnatxref and gnatfind
13446 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13447 @findex gnatxref
13448 @findex gnatfind
13450 @noindent
13451 The compiler generates cross-referencing information (unless
13452 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13453 This information indicates where in the source each entity is declared and
13454 referenced. Note that entities in package Standard are not included, but
13455 entities in all other predefined units are included in the output.
13457 Before using any of these two tools, you need to compile successfully your
13458 application, so that GNAT gets a chance to generate the cross-referencing
13459 information.
13461 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13462 information to provide the user with the capability to easily locate the
13463 declaration and references to an entity. These tools are quite similar,
13464 the difference being that @code{gnatfind} is intended for locating
13465 definitions and/or references to a specified entity or entities, whereas
13466 @code{gnatxref} is oriented to generating a full report of all
13467 cross-references.
13469 To use these tools, you must not compile your application using the
13470 @option{-gnatx} switch on the @file{gnatmake} command line (@inforef{The
13471 GNAT Make Program gnatmake,,gnat_ug}). Otherwise, cross-referencing
13472 information will not be generated.
13474 @menu
13475 * gnatxref Switches::
13476 * gnatfind Switches::
13477 * Project Files for gnatxref and gnatfind::
13478 * Regular Expressions in gnatfind and gnatxref::
13479 * Examples of gnatxref Usage::
13480 * Examples of gnatfind Usage::
13481 @end menu
13483 @node gnatxref Switches
13484 @section @code{gnatxref} Switches
13486 @noindent
13487 The command lines for @code{gnatxref} is:
13488 @smallexample
13489 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13490 @end smallexample
13492 @noindent
13493 where
13495 @table @code
13496 @item sourcefile1, sourcefile2
13497 identifies the source files for which a report is to be generated. The
13498 'with'ed units will be processed too. You must provide at least one file.
13500 These file names are considered to be regular expressions, so for instance
13501 specifying 'source*.adb' is the same as giving every file in the current
13502 directory whose name starts with 'source' and whose extension is 'adb'.
13504 @end table
13506 @noindent
13507 The switches can be :
13508 @table @code
13509 @item ^-a^/ALL_FILES^
13510 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13511 the read-only files found in the library search path. Otherwise, these files
13512 will be ignored. This option can be used to protect Gnat sources or your own
13513 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13514 much faster, and their output much smaller.
13516 @item -aIDIR
13517 When looking for source files also look in directory DIR. The order in which
13518 source file search is undertaken is the same as for @file{gnatmake}.
13520 @item -aODIR
13521 When searching for library and object files, look in directory
13522 DIR. The order in which library files are searched is the same as for
13523 @file{gnatmake}.
13525 @item -nostdinc
13526 Do not look for sources in the system default directory.
13528 @item -nostdlib
13529 Do not look for library files in the system default directory.
13531 @item --RTS=@var{rts-path}
13532 @cindex @code{--RTS} (@code{gnatxref})
13533 Specifies the default location of the runtime library. Same meaning as the
13534 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13536 @item -d
13537 If this switch is set @code{gnatxref} will output the parent type
13538 reference for each matching derived types.
13540 @item ^-f^/FULL_PATHNAME^
13541 If this switch is set, the output file names will be preceded by their
13542 directory (if the file was found in the search path). If this switch is
13543 not set, the directory will not be printed.
13545 @item ^-g^/IGNORE_LOCALS^
13546 If this switch is set, information is output only for library-level
13547 entities, ignoring local entities. The use of this switch may accelerate
13548 @code{gnatfind} and @code{gnatxref}.
13550 @item -IDIR
13551 Equivalent to @samp{-aODIR -aIDIR}.
13553 @item -pFILE
13554 Specify a project file to use @xref{Project Files}.
13555 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13556 project file in the current directory.
13558 If a project file is either specified or found by the tools, then the content
13559 of the source directory and object directory lines are added as if they
13560 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13561 and @samp{^-aO^OBJECT_SEARCH^}.
13562 @item ^-u^/UNUSED^
13563 Output only unused symbols. This may be really useful if you give your
13564 main compilation unit on the command line, as @code{gnatxref} will then
13565 display every unused entity and 'with'ed package.
13567 @ifclear vms
13568 @item -v
13569 Instead of producing the default output, @code{gnatxref} will generate a
13570 @file{tags} file that can be used by vi. For examples how to use this
13571 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
13572 to the standard output, thus you will have to redirect it to a file.
13573 @end ifclear
13575 @end table
13577 All these switches may be in any order on the command line, and may even
13578 appear after the file names. They need not be separated by spaces, thus
13579 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13580 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13582 @node gnatfind Switches
13583 @section @code{gnatfind} Switches
13585 @noindent
13586 The command line for @code{gnatfind} is:
13588 @smallexample
13589 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
13590       [file1 file2 ...]
13591 @end smallexample
13593 @noindent
13594 where
13596 @table @code
13597 @item pattern
13598 An entity will be output only if it matches the regular expression found
13599 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
13601 Omitting the pattern is equivalent to specifying @samp{*}, which
13602 will match any entity. Note that if you do not provide a pattern, you
13603 have to provide both a sourcefile and a line.
13605 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13606 for matching purposes. At the current time there is no support for
13607 8-bit codes other than Latin-1, or for wide characters in identifiers.
13609 @item sourcefile
13610 @code{gnatfind} will look for references, bodies or declarations
13611 of symbols referenced in @file{sourcefile}, at line @samp{line}
13612 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
13613 for syntax examples.
13615 @item line
13616 is a decimal integer identifying the line number containing
13617 the reference to the entity (or entities) to be located.
13619 @item column
13620 is a decimal integer identifying the exact location on the
13621 line of the first character of the identifier for the
13622 entity reference. Columns are numbered from 1.
13624 @item file1 file2 ...
13625 The search will be restricted to these files. If none are given, then
13626 the search will be done for every library file in the search path.
13627 These file must appear only after the pattern or sourcefile.
13629 These file names are considered to be regular expressions, so for instance
13630 specifying 'source*.adb' is the same as giving every file in the current
13631 directory whose name starts with 'source' and whose extension is 'adb'.
13633 Not that if you specify at least one file in this part, @code{gnatfind} may
13634 sometimes not be able to find the body of the subprograms...
13636 @end table
13638 At least one of 'sourcefile' or 'pattern' has to be present on
13639 the command line.
13641 The following switches are available:
13642 @table @code
13644 @item ^-a^/ALL_FILES^
13645 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13646 the read-only files found in the library search path. Otherwise, these files
13647 will be ignored. This option can be used to protect Gnat sources or your own
13648 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13649 much faster, and their output much smaller.
13651 @item -aIDIR
13652 When looking for source files also look in directory DIR. The order in which
13653 source file search is undertaken is the same as for @file{gnatmake}.
13655 @item -aODIR
13656 When searching for library and object files, look in directory
13657 DIR. The order in which library files are searched is the same as for
13658 @file{gnatmake}.
13660 @item -nostdinc
13661 Do not look for sources in the system default directory.
13663 @item -nostdlib
13664 Do not look for library files in the system default directory.
13666 @item --RTS=@var{rts-path}
13667 @cindex @code{--RTS} (@code{gnatfind})
13668 Specifies the default location of the runtime library. Same meaning as the
13669 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13671 @item -d
13672 If this switch is set, then @code{gnatfind} will output the parent type
13673 reference for each matching derived types.
13675 @item ^-e^/EXPRESSIONS^
13676 By default, @code{gnatfind} accept the simple regular expression set for
13677 @samp{pattern}. If this switch is set, then the pattern will be
13678 considered as full Unix-style regular expression.
13680 @item ^-f^/FULL_PATHNAME^
13681 If this switch is set, the output file names will be preceded by their
13682 directory (if the file was found in the search path). If this switch is
13683 not set, the directory will not be printed.
13685 @item ^-g^/IGNORE_LOCALS^
13686 If this switch is set, information is output only for library-level
13687 entities, ignoring local entities. The use of this switch may accelerate
13688 @code{gnatfind} and @code{gnatxref}.
13690 @item -IDIR
13691 Equivalent to @samp{-aODIR -aIDIR}.
13693 @item -pFILE
13694 Specify a project file (@pxref{Project Files}) to use.
13695 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13696 project file in the current directory.
13698 If a project file is either specified or found by the tools, then the content
13699 of the source directory and object directory lines are added as if they
13700 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13701 @samp{^-aO^/OBJECT_SEARCH^}.
13703 @item ^-r^/REFERENCES^
13704 By default, @code{gnatfind} will output only the information about the
13705 declaration, body or type completion of the entities. If this switch is
13706 set, the @code{gnatfind} will locate every reference to the entities in
13707 the files specified on the command line (or in every file in the search
13708 path if no file is given on the command line).
13710 @item ^-s^/PRINT_LINES^
13711 If this switch is set, then @code{gnatfind} will output the content
13712 of the Ada source file lines were the entity was found.
13714 @item -t
13715 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13716 the specified type. It act like -d option but recursively from parent
13717 type to parent type. When this switch is set it is not possible to
13718 specify more than one file.
13720 @end table
13722 All these switches may be in any order on the command line, and may even
13723 appear after the file names. They need not be separated by spaces, thus
13724 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13725 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13727 As stated previously, gnatfind will search in every directory in the
13728 search path. You can force it to look only in the current directory if
13729 you specify @code{*} at the end of the command line.
13732 @node Project Files for gnatxref and gnatfind
13733 @section Project Files for @command{gnatxref} and @command{gnatfind}
13735 @noindent
13736 Project files allow a programmer to specify how to compile its
13737 application, where to find sources,... These files are used primarily by
13738 the Glide Ada mode, but they can also be used by the two tools
13739 @code{gnatxref} and @code{gnatfind}.
13741 A project file name must end with @file{.adp}. If a single one is
13742 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13743 extract the information from it. If multiple project files are found, none of
13744 them is read, and you have to use the @samp{-p} switch to specify the one
13745 you want to use.
13747 The following lines can be included, even though most of them have default
13748 values which can be used in most cases.
13749 The lines can be entered in any order in the file.
13750 Except for @samp{src_dir} and @samp{obj_dir}, you can only have one instance of
13751 each line. If you have multiple instances, only the last one is taken into
13752 account.
13754 @table @code
13755 @item src_dir=DIR         [default: "^./^[]^"]
13756 specifies a directory where to look for source files. Multiple src_dir lines
13757 can be specified and they will be searched in the order they
13758 are specified.
13760 @item obj_dir=DIR         [default: "^./^[]^"]
13761 specifies a directory where to look for object and library files. Multiple
13762 obj_dir lines can be specified and they will be searched in the order they
13763 are specified
13765 @item comp_opt=SWITCHES   [default: ""]
13766 creates a variable which can be referred to subsequently by using
13767 the @samp{$@{comp_opt@}} notation. This is intended to store the default
13768 switches given to @file{gnatmake} and @file{gcc}.
13770 @item bind_opt=SWITCHES   [default: ""]
13771 creates a variable which can be referred to subsequently by using
13772 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13773 switches given to @file{gnatbind}.
13775 @item link_opt=SWITCHES   [default: ""]
13776 creates a variable which can be referred to subsequently by using
13777 the @samp{$@{link_opt@}} notation. This is intended to store the default
13778 switches given to @file{gnatlink}.
13780 @item main=EXECUTABLE     [default: ""]
13781 specifies the name of the executable for the application. This variable can
13782 be referred to in the following lines by using the @samp{$@{main@}} notation.
13784 @ifset vms
13785 @item comp_cmd=COMMAND    [default: "GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"]
13786 @end ifset
13787 @ifclear vms
13788 @item comp_cmd=COMMAND    [default: "gcc -c -I$@{src_dir@} -g -gnatq"]
13789 @end ifclear
13790 specifies the command used to compile a single file in the application.
13792 @ifset vms
13793 @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@}"]
13794 @end ifset
13795 @ifclear vms
13796 @item make_cmd=COMMAND    [default: "gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"]
13797 @end ifclear
13798 specifies the command used to recompile the whole application.
13800 @item run_cmd=COMMAND     [default: "$@{main@}"]
13801 specifies the command used to run the application.
13803 @item debug_cmd=COMMAND   [default: "gdb $@{main@}"]
13804 specifies the command used to debug the application
13806 @end table
13808 @code{gnatxref} and @code{gnatfind} only take into account the @samp{src_dir}
13809 and @samp{obj_dir} lines, and ignore the others.
13811 @node Regular Expressions in gnatfind and gnatxref
13812 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
13814 @noindent
13815 As specified in the section about @code{gnatfind}, the pattern can be a
13816 regular expression. Actually, there are to set of regular expressions
13817 which are recognized by the program :
13819 @table @code
13820 @item globbing patterns
13821 These are the most usual regular expression. They are the same that you
13822 generally used in a Unix shell command line, or in a DOS session.
13824 Here is a more formal grammar :
13825 @smallexample
13826 @group
13827 @iftex
13828 @leftskip=.5cm
13829 @end iftex
13830 regexp ::= term
13831 term   ::= elmt            -- matches elmt
13832 term   ::= elmt elmt       -- concatenation (elmt then elmt)
13833 term   ::= *               -- any string of 0 or more characters
13834 term   ::= ?               -- matches any character
13835 term   ::= [char @{char@}] -- matches any character listed
13836 term   ::= [char - char]   -- matches any character in range
13837 @end group
13838 @end smallexample
13840 @item full regular expression
13841 The second set of regular expressions is much more powerful. This is the
13842 type of regular expressions recognized by utilities such a @file{grep}.
13844 The following is the form of a regular expression, expressed in Ada
13845 reference manual style BNF is as follows
13847 @smallexample
13848 @iftex
13849 @leftskip=.5cm
13850 @end iftex
13851 @group
13852 regexp ::= term @{| term@} -- alternation (term or term ...)
13854 term ::= item @{item@}     -- concatenation (item then item)
13856 item ::= elmt              -- match elmt
13857 item ::= elmt *            -- zero or more elmt's
13858 item ::= elmt +            -- one or more elmt's
13859 item ::= elmt ?            -- matches elmt or nothing
13860 @end group
13861 @group
13862 elmt ::= nschar            -- matches given character
13863 elmt ::= [nschar @{nschar@}]   -- matches any character listed
13864 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13865 elmt ::= [char - char]     -- matches chars in given range
13866 elmt ::= \ char            -- matches given character
13867 elmt ::= .                 -- matches any single character
13868 elmt ::= ( regexp )        -- parens used for grouping
13870 char ::= any character, including special characters
13871 nschar ::= any character except ()[].*+?^^^
13872 @end group
13873 @end smallexample
13875 Following are a few examples :
13877 @table @samp
13878 @item abcde|fghi
13879 will match any of the two strings 'abcde' and 'fghi'.
13881 @item abc*d
13882 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
13884 @item [a-z]+
13885 will match any string which has only lowercase characters in it (and at
13886 least one character
13888 @end table
13889 @end table
13891 @node Examples of gnatxref Usage
13892 @section Examples of @code{gnatxref} Usage
13894 @subsection General Usage
13896 @noindent
13897 For the following examples, we will consider the following units :
13899 @smallexample
13900 @group
13901 @cartouche
13902 main.ads:
13903 1: @b{with} Bar;
13904 2: @b{package} Main @b{is}
13905 3:     @b{procedure} Foo (B : @b{in} Integer);
13906 4:     C : Integer;
13907 5: @b{private}
13908 6:     D : Integer;
13909 7: @b{end} Main;
13911 main.adb:
13912 1: @b{package body} Main @b{is}
13913 2:     @b{procedure} Foo (B : @b{in} Integer) @b{is}
13914 3:     @b{begin}
13915 4:        C := B;
13916 5:        D := B;
13917 6:        Bar.Print (B);
13918 7:        Bar.Print (C);
13919 8:     @b{end} Foo;
13920 9: @b{end} Main;
13922 bar.ads:
13923 1: @b{package} Bar @b{is}
13924 2:     @b{procedure} Print (B : Integer);
13925 3: @b{end} bar;
13926 @end cartouche
13927 @end group
13928 @end smallexample
13930 @table @code
13932 @noindent
13933 The first thing to do is to recompile your application (for instance, in
13934 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13935 the cross-referencing information.
13936 You can then issue any of the following commands:
13938 @item gnatxref main.adb
13939 @code{gnatxref} generates cross-reference information for main.adb
13940 and every unit 'with'ed by main.adb.
13942 The output would be:
13943 @smallexample
13944 @iftex
13945 @leftskip=0cm
13946 @end iftex
13947 B                                                      Type: Integer
13948   Decl: bar.ads           2:22
13949 B                                                      Type: Integer
13950   Decl: main.ads          3:20
13951   Body: main.adb          2:20
13952   Ref:  main.adb          4:13     5:13     6:19
13953 Bar                                                    Type: Unit
13954   Decl: bar.ads           1:9
13955   Ref:  main.adb          6:8      7:8
13956        main.ads           1:6
13957 C                                                      Type: Integer
13958   Decl: main.ads          4:5
13959   Modi: main.adb          4:8
13960   Ref:  main.adb          7:19
13961 D                                                      Type: Integer
13962   Decl: main.ads          6:5
13963   Modi: main.adb          5:8
13964 Foo                                                    Type: Unit
13965   Decl: main.ads          3:15
13966   Body: main.adb          2:15
13967 Main                                                    Type: Unit
13968   Decl: main.ads          2:9
13969   Body: main.adb          1:14
13970 Print                                                   Type: Unit
13971   Decl: bar.ads           2:15
13972   Ref:  main.adb          6:12     7:12
13973 @end smallexample
13975 @noindent
13976 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13977 its body is in main.adb, line 1, column 14 and is not referenced any where.
13979 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13980 it referenced in main.adb, line 6 column 12 and line 7 column 12.
13982 @item gnatxref package1.adb package2.ads
13983 @code{gnatxref} will generates cross-reference information for
13984 package1.adb, package2.ads and any other package 'with'ed by any
13985 of these.
13987 @end table
13989 @ifclear vms
13990 @subsection Using gnatxref with vi
13992 @code{gnatxref} can generate a tags file output, which can be used
13993 directly from @file{vi}. Note that the standard version of @file{vi}
13994 will not work properly with overloaded symbols. Consider using another
13995 free implementation of @file{vi}, such as @file{vim}.
13997 @smallexample
13998 $ gnatxref -v gnatfind.adb > tags
13999 @end smallexample
14001 @noindent
14002 will generate the tags file for @code{gnatfind} itself (if the sources
14003 are in the search path!).
14005 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14006 (replacing @i{entity} by whatever you are looking for), and vi will
14007 display a new file with the corresponding declaration of entity.
14008 @end ifclear
14010 @node Examples of gnatfind Usage
14011 @section Examples of @code{gnatfind} Usage
14013 @table @code
14015 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14016 Find declarations for all entities xyz referenced at least once in
14017 main.adb. The references are search in every library file in the search
14018 path.
14020 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14021 switch is set)
14023 The output will look like:
14024 @smallexample
14025 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14026 ^directory/^[directory]^main.adb:24:10: xyz <= body
14027 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14028 @end smallexample
14030 @noindent
14031 that is to say, one of the entities xyz found in main.adb is declared at
14032 line 12 of main.ads (and its body is in main.adb), and another one is
14033 declared at line 45 of foo.ads
14035 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14036 This is the same command as the previous one, instead @code{gnatfind} will
14037 display the content of the Ada source file lines.
14039 The output will look like:
14041 @smallexample
14042 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14043    procedure xyz;
14044 ^directory/^[directory]^main.adb:24:10: xyz <= body
14045    procedure xyz is
14046 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14047    xyz : Integer;
14048 @end smallexample
14050 @noindent
14051 This can make it easier to find exactly the location your are looking
14052 for.
14054 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14055 Find references to all entities containing an x that are
14056 referenced on line 123 of main.ads.
14057 The references will be searched only in main.adb and foo.adb.
14059 @item gnatfind main.ads:123
14060 Find declarations and bodies for all entities that are referenced on
14061 line 123 of main.ads.
14063 This is the same as @code{gnatfind "*":main.adb:123}.
14065 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14066 Find the declaration for the entity referenced at column 45 in
14067 line 123 of file main.adb in directory mydir. Note that it
14068 is usual to omit the identifier name when the column is given,
14069 since the column position identifies a unique reference.
14071 The column has to be the beginning of the identifier, and should not
14072 point to any character in the middle of the identifier.
14074 @end table
14076 @node File Name Krunching Using gnatkr
14077 @chapter File Name Krunching Using @code{gnatkr}
14078 @findex gnatkr
14080 @noindent
14081 This chapter discusses the method used by the compiler to shorten
14082 the default file names chosen for Ada units so that they do not
14083 exceed the maximum length permitted. It also describes the
14084 @code{gnatkr} utility that can be used to determine the result of
14085 applying this shortening.
14086 @menu
14087 * About gnatkr::
14088 * Using gnatkr::
14089 * Krunching Method::
14090 * Examples of gnatkr Usage::
14091 @end menu
14093 @node About gnatkr
14094 @section About @code{gnatkr}
14096 @noindent
14097 The default file naming rule in GNAT
14098 is that the file name must be derived from
14099 the unit name. The exact default rule is as follows:
14100 @itemize @bullet
14101 @item
14102 Take the unit name and replace all dots by hyphens.
14103 @item
14104 If such a replacement occurs in the
14105 second character position of a name, and the first character is
14106 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
14107 ^~ (tilde)^$ (dollar sign)^
14108 instead of a minus.
14109 @end itemize
14110 The reason for this exception is to avoid clashes
14111 with the standard names for children of System, Ada, Interfaces,
14112 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
14113 respectively.
14115 The @code{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14116 switch of the compiler activates a "krunching"
14117 circuit that limits file names to nn characters (where nn is a decimal
14118 integer). For example, using OpenVMS,
14119 where the maximum file name length is
14120 39, the value of nn is usually set to 39, but if you want to generate
14121 a set of files that would be usable if ported to a system with some
14122 different maximum file length, then a different value can be specified.
14123 The default value of 39 for OpenVMS need not be specified.
14125 The @code{gnatkr} utility can be used to determine the krunched name for
14126 a given file, when krunched to a specified maximum length.
14128 @node Using gnatkr
14129 @section Using @code{gnatkr}
14131 @noindent
14132 The @code{gnatkr} command has the form
14134 @ifclear vms
14135 @smallexample
14136 $ gnatkr @var{name} [@var{length}]
14137 @end smallexample
14138 @end ifclear
14140 @ifset vms
14141 @smallexample
14142 $ gnatkr @var{name} /COUNT=nn
14143 @end smallexample
14144 @end ifset
14146 @noindent
14147 @var{name} can be an Ada name with dots or the GNAT name of the unit,
14148 where the dots representing child units or subunit are replaced by
14149 hyphens. The only confusion arises if a name ends in @code{.ads} or
14150 @code{.adb}. @code{gnatkr} takes this to be an extension if there are
14151 no other dots in the name^ and the whole name is in lowercase^^.
14153 @var{length} represents the length of the krunched name. The default
14154 when no argument is given is ^8^39^ characters. A length of zero stands for
14155 unlimited, in other words do not chop except for system files which are
14156 always ^8^39^.
14158 @noindent
14159 The output is the krunched name. The output has an extension only if the
14160 original argument was a file name with an extension.
14162 @node Krunching Method
14163 @section Krunching Method
14165 @noindent
14166 The initial file name is determined by the name of the unit that the file
14167 contains. The name is formed by taking the full expanded name of the
14168 unit and replacing the separating dots with hyphens and
14169 using ^lowercase^uppercase^
14170 for all letters, except that a hyphen in the second character position is
14171 replaced by a ^tilde^dollar sign^ if the first character is
14172 ^a, i, g, or s^A, I, G, or S^.
14173 The extension is @code{.ads} for a
14174 specification and @code{.adb} for a body.
14175 Krunching does not affect the extension, but the file name is shortened to
14176 the specified length by following these rules:
14178 @itemize @bullet
14179 @item
14180 The name is divided into segments separated by hyphens, tildes or
14181 underscores and all hyphens, tildes, and underscores are
14182 eliminated. If this leaves the name short enough, we are done.
14184 @item
14185 If the name is too long, the longest segment is located (left-most if there are two
14186 of equal length), and shortened by dropping its last character. This is
14187 repeated until the name is short enough.
14189 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
14190 to fit the name into 8 characters as required by some operating systems.
14192 @smallexample
14193 our-strings-wide_fixed 22
14194 our strings wide fixed 19
14195 our string  wide fixed 18
14196 our strin   wide fixed 17
14197 our stri    wide fixed 16
14198 our stri    wide fixe  15
14199 our str     wide fixe  14
14200 our str     wid  fixe  13
14201 our str     wid  fix   12
14202 ou  str     wid  fix   11
14203 ou  st      wid  fix   10
14204 ou  st      wi   fix   9
14205 ou  st      wi   fi    8
14206 Final file name: oustwifi.adb
14207 @end smallexample
14209 @item
14210 The file names for all predefined units are always krunched to eight
14211 characters. The krunching of these predefined units uses the following
14212 special prefix replacements:
14214 @table @file
14215 @item ada-
14216 replaced by @file{^a^A^-}
14218 @item gnat-
14219 replaced by @file{^g^G^-}
14221 @item interfaces-
14222 replaced by @file{^i^I^-}
14224 @item system-
14225 replaced by @file{^s^S^-}
14226 @end table
14228 These system files have a hyphen in the second character position. That
14229 is why normal user files replace such a character with a
14230 ^tilde^dollar sign^, to
14231 avoid confusion with system file names.
14233 As an example of this special rule, consider
14234 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
14236 @smallexample
14237 ada-strings-wide_fixed 22
14238 a-  strings wide fixed 18
14239 a-  string  wide fixed 17
14240 a-  strin   wide fixed 16
14241 a-  stri    wide fixed 15
14242 a-  stri    wide fixe  14
14243 a-  str     wide fixe  13
14244 a-  str     wid  fixe  12
14245 a-  str     wid  fix   11
14246 a-  st      wid  fix   10
14247 a-  st      wi   fix   9
14248 a-  st      wi   fi    8
14249 Final file name: a-stwifi.adb
14250 @end smallexample
14251 @end itemize
14253 Of course no file shortening algorithm can guarantee uniqueness over all
14254 possible unit names, and if file name krunching is used then it is your
14255 responsibility to ensure that no name clashes occur. The utility
14256 program @code{gnatkr} is supplied for conveniently determining the
14257 krunched name of a file.
14259 @node Examples of gnatkr Usage
14260 @section Examples of @code{gnatkr} Usage
14262 @smallexample
14263 @iftex
14264 @leftskip=0cm
14265 @end iftex
14266 @ifclear vms
14267 $ gnatkr very_long_unit_name.ads      --> velounna.ads
14268 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
14269 $ gnatkr Grandparent.Parent.Child     --> grparchi
14270 @end ifclear
14271 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
14272 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
14273 @end smallexample
14275 @node Preprocessing Using gnatprep
14276 @chapter Preprocessing Using @code{gnatprep}
14277 @findex gnatprep
14279 @noindent
14280 The @code{gnatprep} utility provides
14281 a simple preprocessing capability for Ada programs.
14282 It is designed for use with GNAT, but is not dependent on any special
14283 features of GNAT.
14285 @menu
14286 * Using gnatprep::
14287 * Switches for gnatprep::
14288 * Form of Definitions File::
14289 * Form of Input Text for gnatprep::
14290 @end menu
14292 @node Using gnatprep
14293 @section Using @code{gnatprep}
14295 @noindent
14296 To call @code{gnatprep} use
14298 @smallexample
14299 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
14300 @end smallexample
14302 @noindent
14303 where
14304 @table @code
14305 @item infile
14306 is the full name of the input file, which is an Ada source
14307 file containing preprocessor directives.
14309 @item outfile
14310 is the full name of the output file, which is an Ada source
14311 in standard Ada form. When used with GNAT, this file name will
14312 normally have an ads or adb suffix.
14314 @item deffile
14315 is the full name of a text file containing definitions of
14316 symbols to be referenced by the preprocessor. This argument is
14317 optional, and can be replaced by the use of the @code{-D} switch.
14319 @item switches
14320 is an optional sequence of switches as described in the next section.
14321 @end table
14323 @node Switches for gnatprep
14324 @section Switches for @code{gnatprep}
14326 @table @code
14328 @item ^-b^/BLANK_LINES^
14329 Causes both preprocessor lines and the lines deleted by
14330 preprocessing to be replaced by blank lines in the output source file,
14331 preserving line numbers in the output file.
14333 @item ^-c^/COMMENTS^
14334 Causes both preprocessor lines and the lines deleted
14335 by preprocessing to be retained in the output source as comments marked
14336 with the special string "--! ". This option will result in line numbers
14337 being preserved in the output file.
14339 @item -Dsymbol=value
14340 Defines a new symbol, associated with value. If no value is given on the
14341 command line, then symbol is considered to be @code{True}. This switch
14342 can be used in place of a definition file.
14344 @ifset vms
14345 @item /REMOVE (default)
14346 This is the default setting which causes lines deleted by preprocessing
14347 to be entirely removed from the output file.
14348 @end ifset
14350 @item ^-r^/REFERENCE^
14351 Causes a @code{Source_Reference} pragma to be generated that
14352 references the original input file, so that error messages will use
14353 the file name of this original file. The use of this switch implies
14354 that preprocessor lines are not to be removed from the file, so its
14355 use will force @code{^-b^/BLANK_LINES^} mode if
14356 @code{^-c^/COMMENTS^}
14357 has not been specified explicitly.
14359 Note that if the file to be preprocessed contains multiple units, then
14360 it will be necessary to @code{gnatchop} the output file from
14361 @code{gnatprep}. If a @code{Source_Reference} pragma is present
14362 in the preprocessed file, it will be respected by
14363 @code{gnatchop ^-r^/REFERENCE^}
14364 so that the final chopped files will correctly refer to the original
14365 input source file for @code{gnatprep}.
14367 @item ^-s^/SYMBOLS^
14368 Causes a sorted list of symbol names and values to be
14369 listed on the standard output file.
14371 @item ^-u^/UNDEFINED^
14372 Causes undefined symbols to be treated as having the value FALSE in the context
14373 of a preprocessor test. In the absence of this option, an undefined symbol in
14374 a @code{#if} or @code{#elsif} test will be treated as an error.
14376 @end table
14378 @ifclear vms
14379 @noindent
14380 Note: if neither @code{-b} nor @code{-c} is present,
14381 then preprocessor lines and
14382 deleted lines are completely removed from the output, unless -r is
14383 specified, in which case -b is assumed.
14384 @end ifclear
14386 @node Form of Definitions File
14387 @section Form of Definitions File
14389 @noindent
14390 The definitions file contains lines of the form
14392 @smallexample
14393 symbol := value
14394 @end smallexample
14396 @noindent
14397 where symbol is an identifier, following normal Ada (case-insensitive)
14398 rules for its syntax, and value is one of the following:
14400 @itemize @bullet
14401 @item
14402 Empty, corresponding to a null substitution
14403 @item
14404 A string literal using normal Ada syntax
14405 @item
14406 Any sequence of characters from the set
14407 (letters, digits, period, underline).
14408 @end itemize
14410 @noindent
14411 Comment lines may also appear in the definitions file, starting with
14412 the usual @code{--},
14413 and comments may be added to the definitions lines.
14415 @node Form of Input Text for gnatprep
14416 @section Form of Input Text for @code{gnatprep}
14418 @noindent
14419 The input text may contain preprocessor conditional inclusion lines,
14420 as well as general symbol substitution sequences.
14422 The preprocessor conditional inclusion commands have the form
14424 @smallexample
14425 @group
14426 @cartouche
14427 #if @i{expression} [then]
14428    lines
14429 #elsif @i{expression} [then]
14430    lines
14431 #elsif @i{expression} [then]
14432    lines
14434 #else
14435    lines
14436 #end if;
14437 @end cartouche
14438 @end group
14439 @end smallexample
14441 @noindent
14442 In this example, @i{expression} is defined by the following grammar:
14443 @smallexample
14444 @i{expression} ::=  <symbol>
14445 @i{expression} ::=  <symbol> = "<value>"
14446 @i{expression} ::=  <symbol> = <symbol>
14447 @i{expression} ::=  <symbol> 'Defined
14448 @i{expression} ::=  not @i{expression}
14449 @i{expression} ::=  @i{expression} and @i{expression}
14450 @i{expression} ::=  @i{expression} or @i{expression}
14451 @i{expression} ::=  @i{expression} and then @i{expression}
14452 @i{expression} ::=  @i{expression} or else @i{expression}
14453 @i{expression} ::=  ( @i{expression} )
14454 @end smallexample
14456 @noindent
14457 For the first test (@i{expression} ::= <symbol>) the symbol must have
14458 either the value true or false, that is to say the right-hand of the
14459 symbol definition must be one of the (case-insensitive) literals
14460 @code{True} or @code{False}. If the value is true, then the
14461 corresponding lines are included, and if the value is false, they are
14462 excluded.
14464 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
14465 the symbol has been defined in the definition file or by a @code{-D}
14466 switch on the command line. Otherwise, the test is false.
14468 The equality tests are case insensitive, as are all the preprocessor lines.
14470 If the symbol referenced is not defined in the symbol definitions file,
14471 then the effect depends on whether or not switch @code{-u}
14472 is specified. If so, then the symbol is treated as if it had the value
14473 false and the test fails. If this switch is not specified, then
14474 it is an error to reference an undefined symbol. It is also an error to
14475 reference a symbol that is defined with a value other than @code{True}
14476 or @code{False}.
14478 The use of the @code{not} operator inverts the sense of this logical test, so
14479 that the lines are included only if the symbol is not defined.
14480 The @code{then} keyword is optional as shown
14482 The @code{#} must be the first non-blank character on a line, but
14483 otherwise the format is free form. Spaces or tabs may appear between
14484 the @code{#} and the keyword. The keywords and the symbols are case
14485 insensitive as in normal Ada code. Comments may be used on a
14486 preprocessor line, but other than that, no other tokens may appear on a
14487 preprocessor line. Any number of @code{elsif} clauses can be present,
14488 including none at all. The @code{else} is optional, as in Ada.
14490 The @code{#} marking the start of a preprocessor line must be the first
14491 non-blank character on the line, i.e. it must be preceded only by
14492 spaces or horizontal tabs.
14494 Symbol substitution outside of preprocessor lines is obtained by using
14495 the sequence
14497 @smallexample
14498 $symbol
14499 @end smallexample
14501 @noindent
14502 anywhere within a source line, except in a comment or within a
14503 string literal. The identifier
14504 following the @code{$} must match one of the symbols defined in the symbol
14505 definition file, and the result is to substitute the value of the
14506 symbol in place of @code{$symbol} in the output file.
14508 Note that although the substitution of strings within a string literal
14509 is not possible, it is possible to have a symbol whose defined value is
14510 a string literal. So instead of setting XYZ to @code{hello} and writing:
14512 @smallexample
14513 Header : String := "$XYZ";
14514 @end smallexample
14516 @noindent
14517 you should set XYZ to @code{"hello"} and write:
14519 @smallexample
14520 Header : String := $XYZ;
14521 @end smallexample
14523 @noindent
14524 and then the substitution will occur as desired.
14526 @ifset vms
14527 @node The GNAT Run-Time Library Builder gnatlbr
14528 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
14529 @findex gnatlbr
14530 @cindex Library builder
14532 @noindent
14533 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
14534 supplied configuration pragmas.
14536 @menu
14537 * Running gnatlbr::
14538 * Switches for gnatlbr::
14539 * Examples of gnatlbr Usage::
14540 @end menu
14542 @node Running gnatlbr
14543 @section Running @code{gnatlbr}
14545 @noindent
14546 The @code{gnatlbr} command has the form
14548 @smallexample
14549 @ifclear vms
14550 $ gnatlbr --[create | set | delete]=directory --config=file
14551 @end ifclear
14552 @ifset vms
14553 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
14554 @end ifset
14555 @end smallexample
14557 @node Switches for gnatlbr
14558 @section Switches for @code{gnatlbr}
14560 @noindent
14561 @code{gnatlbr} recognizes the following switches:
14563 @table @code
14564 @item ^--create^/CREATE^=directory
14565 @cindex @code{^--create^/CREATE^=directory} (@code{gnatlbr})
14566      Create the new run-time library in the specified directory.
14568 @item ^--set^/SET^=directory
14569 @cindex @code{^--set^/SET^=directory} (@code{gnatlbr})
14570      Make the library in the specified directory the current run-time
14571      library.
14573 @item ^--delete^/DELETE^=directory
14574 @cindex @code{^--delete^/DELETE^=directory} (@code{gnatlbr})
14575      Delete the run-time library in the specified directory.
14577 @item ^--config^/CONFIG^=file
14578 @cindex @code{^--config^/CONFIG^=file} (@code{gnatlbr})
14579      With ^--create^/CREATE^:
14580      Use the configuration pragmas in the specified file when building
14581      the library.
14583      With ^--set^/SET^:
14584      Use the configuration pragmas in the specified file when compiling.
14586 @end table
14588 @node Examples of gnatlbr Usage
14589 @section Example of @code{gnatlbr} Usage
14591 @smallexample
14592 Contents of VAXFLOAT.ADC:
14593 pragma Float_Representation (VAX_Float);
14595 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
14597 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
14599 @end smallexample
14600 @end ifset
14602 @node The GNAT Library Browser gnatls
14603 @chapter The GNAT Library Browser @code{gnatls}
14604 @findex gnatls
14605 @cindex Library browser
14607 @noindent
14608 @code{gnatls} is a tool that outputs information about compiled
14609 units. It gives the relationship between objects, unit names and source
14610 files. It can also be used to check the source dependencies of a unit
14611 as well as various characteristics.
14613 @menu
14614 * Running gnatls::
14615 * Switches for gnatls::
14616 * Examples of gnatls Usage::
14617 @end menu
14619 @node Running gnatls
14620 @section Running @code{gnatls}
14622 @noindent
14623 The @code{gnatls} command has the form
14625 @smallexample
14626 $ gnatls switches @var{object_or_ali_file}
14627 @end smallexample
14629 @noindent
14630 The main argument is the list of object or @file{ali} files
14631 (@pxref{The Ada Library Information Files})
14632 for which information is requested.
14634 In normal mode, without additional option, @code{gnatls} produces a
14635 four-column listing. Each line represents information for a specific
14636 object. The first column gives the full path of the object, the second
14637 column gives the name of the principal unit in this object, the third
14638 column gives the status of the source and the fourth column gives the
14639 full path of the source representing this unit.
14640 Here is a simple example of use:
14642 @smallexample
14643 $ gnatls *.o
14644 ^./^[]^demo1.o            demo1            DIF demo1.adb
14645 ^./^[]^demo2.o            demo2             OK demo2.adb
14646 ^./^[]^hello.o            h1                OK hello.adb
14647 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
14648 ^./^[]^instr.o            instr             OK instr.adb
14649 ^./^[]^tef.o              tef              DIF tef.adb
14650 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
14651 ^./^[]^tgef.o             tgef             DIF tgef.adb
14652 @end smallexample
14654 @noindent
14655 The first line can be interpreted as follows: the main unit which is
14656 contained in
14657 object file @file{demo1.o} is demo1, whose main source is in
14658 @file{demo1.adb}. Furthermore, the version of the source used for the
14659 compilation of demo1 has been modified (DIF). Each source file has a status
14660 qualifier which can be:
14662 @table @code
14663 @item OK (unchanged)
14664 The version of the source file used for the compilation of the
14665 specified unit corresponds exactly to the actual source file.
14667 @item MOK (slightly modified)
14668 The version of the source file used for the compilation of the
14669 specified unit differs from the actual source file but not enough to
14670 require recompilation. If you use gnatmake with the qualifier
14671 @code{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
14672 MOK will not be recompiled.
14674 @item DIF (modified)
14675 No version of the source found on the path corresponds to the source
14676 used to build this object.
14678 @item ??? (file not found)
14679 No source file was found for this unit.
14681 @item HID (hidden,  unchanged version not first on PATH)
14682 The version of the source that corresponds exactly to the source used
14683 for compilation has been found on the path but it is hidden by another
14684 version of the same source that has been modified.
14686 @end table
14688 @node Switches for gnatls
14689 @section Switches for @code{gnatls}
14691 @noindent
14692 @code{gnatls} recognizes the following switches:
14694 @table @code
14695 @item ^-a^/ALL_UNITS^
14696 @cindex @code{^-a^/ALL_UNITS^} (@code{gnatls})
14697 Consider all units, including those of the predefined Ada library.
14698 Especially useful with @code{^-d^/DEPENDENCIES^}.
14700 @item ^-d^/DEPENDENCIES^
14701 @cindex @code{^-d^/DEPENDENCIES^} (@code{gnatls})
14702 List sources from which specified units depend on.
14704 @item ^-h^/OUTPUT=OPTIONS^
14705 @cindex @code{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
14706 Output the list of options.
14708 @item ^-o^/OUTPUT=OBJECTS^
14709 @cindex @code{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
14710 Only output information about object files.
14712 @item ^-s^/OUTPUT=SOURCES^
14713 @cindex @code{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
14714 Only output information about source files.
14716 @item ^-u^/OUTPUT=UNITS^
14717 @cindex @code{^-u^/OUTPUT=UNITS^} (@code{gnatls})
14718 Only output information about compilation units.
14720 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
14721 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
14722 @itemx ^-I^/SEARCH=^@var{dir}
14723 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
14724 @itemx -nostdinc
14725 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
14726 (see @ref{Switches for gnatmake}).
14728 @item --RTS=@var{rts-path}
14729 @cindex @code{--RTS} (@code{gnatls})
14730 Specifies the default location of the runtime library. Same meaning as the
14731 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
14733 @item ^-v^/OUTPUT=VERBOSE^
14734 @cindex @code{^-s^/OUTPUT=VERBOSE^} (@code{gnatls})
14735 Verbose mode. Output the complete source and object paths. Do not use
14736 the default column layout but instead use long format giving as much as
14737 information possible on each requested units, including special
14738 characteristics such as:
14740 @table @code
14741 @item  Preelaborable
14742 The unit is preelaborable in the Ada 95 sense.
14744 @item No_Elab_Code
14745 No elaboration code has been produced by the compiler for this unit.
14747 @item Pure
14748 The unit is pure in the Ada 95 sense.
14750 @item Elaborate_Body
14751 The unit contains a pragma Elaborate_Body.
14753 @item Remote_Types
14754 The unit contains a pragma Remote_Types.
14756 @item Shared_Passive
14757 The unit contains a pragma Shared_Passive.
14759 @item Predefined
14760 This unit is part of the predefined environment and cannot be modified
14761 by the user.
14763 @item Remote_Call_Interface
14764 The unit contains a pragma Remote_Call_Interface.
14766 @end table
14768 @end table
14770 @node Examples of gnatls Usage
14771 @section Example of @code{gnatls} Usage
14772 @ifclear vms
14774 @noindent
14775 Example of using the verbose switch. Note how the source and
14776 object paths are affected by the ^-I^/SEARCH^ switch.
14778 @smallexample
14779 $ gnatls -v -I.. demo1.o
14781 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
14783 Source Search Path:
14784    <Current_Directory>
14785    ../
14786    /home/comar/local/adainclude/
14788 Object Search Path:
14789    <Current_Directory>
14790    ../
14791    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
14793 ./demo1.o
14794    Unit =>
14795      Name   => demo1
14796      Kind   => subprogram body
14797      Flags  => No_Elab_Code
14798      Source => demo1.adb    modified
14799 @end smallexample
14801 @noindent
14802 The following is an example of use of the dependency list.
14803 Note the use of the -s switch
14804 which gives a straight list of source files. This can be useful for
14805 building specialized scripts.
14807 @smallexample
14808 $ gnatls -d demo2.o
14809 ./demo2.o   demo2        OK demo2.adb
14810                          OK gen_list.ads
14811                          OK gen_list.adb
14812                          OK instr.ads
14813                          OK instr-child.ads
14815 $ gnatls -d -s -a demo1.o
14816 demo1.adb
14817 /home/comar/local/adainclude/ada.ads
14818 /home/comar/local/adainclude/a-finali.ads
14819 /home/comar/local/adainclude/a-filico.ads
14820 /home/comar/local/adainclude/a-stream.ads
14821 /home/comar/local/adainclude/a-tags.ads
14822 gen_list.ads
14823 gen_list.adb
14824 /home/comar/local/adainclude/gnat.ads
14825 /home/comar/local/adainclude/g-io.ads
14826 instr.ads
14827 /home/comar/local/adainclude/system.ads
14828 /home/comar/local/adainclude/s-exctab.ads
14829 /home/comar/local/adainclude/s-finimp.ads
14830 /home/comar/local/adainclude/s-finroo.ads
14831 /home/comar/local/adainclude/s-secsta.ads
14832 /home/comar/local/adainclude/s-stalib.ads
14833 /home/comar/local/adainclude/s-stoele.ads
14834 /home/comar/local/adainclude/s-stratt.ads
14835 /home/comar/local/adainclude/s-tasoli.ads
14836 /home/comar/local/adainclude/s-unstyp.ads
14837 /home/comar/local/adainclude/unchconv.ads
14838 @end smallexample
14839 @end ifclear
14841 @ifset vms
14842 @smallexample
14843 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
14845 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
14846 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
14847 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
14848 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
14849 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
14850 demo1.adb
14851 gen_list.ads
14852 gen_list.adb
14853 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
14854 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
14855 instr.ads
14856 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
14857 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
14858 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
14859 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
14860 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
14861 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
14862 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
14863 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
14864 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
14865 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
14866 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
14867 @end smallexample
14868 @end ifset
14870 @ifclear vms
14871 @node GNAT and Libraries
14872 @chapter GNAT and Libraries
14873 @cindex Library, building, installing
14875 @noindent
14876 This chapter addresses some of the issues related to building and using
14877 a library with GNAT. It also shows how the GNAT run-time library can be
14878 recompiled.
14880 @menu
14881 * Creating an Ada Library::
14882 * Installing an Ada Library::
14883 * Using an Ada Library::
14884 * Creating an Ada Library to be Used in a Non-Ada Context::
14885 * Rebuilding the GNAT Run-Time Library::
14886 @end menu
14888 @node Creating an Ada Library
14889 @section Creating an Ada Library
14891 @noindent
14892 In the GNAT environment, a library has two components:
14893 @itemize @bullet
14894 @item
14895 Source files.
14896 @item
14897 Compiled code and Ali files. See @ref{The Ada Library Information Files}.
14898 @end itemize
14900 @noindent
14901 In order to use other packages @ref{The GNAT Compilation Model}
14902 requires a certain number of sources to be available to the compiler.
14903 The minimal set of
14904 sources required includes the specs of all the packages that make up the
14905 visible part of the library as well as all the sources upon which they
14906 depend. The bodies of all visible generic units must also be provided.
14907 @noindent
14908 Although it is not strictly mandatory, it is recommended that all sources
14909 needed to recompile the library be provided, so that the user can make
14910 full use of inter-unit inlining and source-level debugging. This can also
14911 make the situation easier for users that need to upgrade their compilation
14912 toolchain and thus need to recompile the library from sources.
14914 @noindent
14915 The compiled code can be provided in different ways. The simplest way is
14916 to provide directly the set of objects produced by the compiler during
14917 the compilation of the library. It is also possible to group the objects
14918 into an archive using whatever commands are provided by the operating
14919 system. Finally, it is also possible to create a shared library (see
14920 option -shared in the GCC manual).
14922 @noindent
14923 There are various possibilities for compiling the units that make up the
14924 library: for example with a Makefile @ref{Using the GNU make Utility},
14925 or with a conventional script.
14926 For simple libraries, it is also possible to create a
14927 dummy main program which depends upon all the packages that comprise the
14928 interface of the library. This dummy main program can then be given to
14929 gnatmake, in order to build all the necessary objects. Here is an example
14930 of such a dummy program and the generic commands used to build an
14931 archive or a shared library.
14933 @smallexample
14934 @iftex
14935 @leftskip=.7cm
14936 @end iftex
14937 @b{with} My_Lib.Service1;
14938 @b{with} My_Lib.Service2;
14939 @b{with} My_Lib.Service3;
14940 @b{procedure} My_Lib_Dummy @b{is}
14941 @b{begin}
14942    @b{null};
14943 @b{end};
14945 # compiling the library
14946 $ gnatmake -c my_lib_dummy.adb
14948 # we don't need the dummy object itself
14949 $ rm my_lib_dummy.o my_lib_dummy.ali
14951 # create an archive with the remaining objects
14952 $ ar rc libmy_lib.a *.o
14953 # some systems may require "ranlib" to be run as well
14955 # or create a shared library
14956 $ gcc -shared -o libmy_lib.so *.o
14957 # some systems may require the code to have been compiled with -fPIC
14958 @end smallexample
14960 @noindent
14961 When the objects are grouped in an archive or a shared library, the user
14962 needs to specify the desired library at link time, unless a pragma
14963 linker_options has been used in one of the sources:
14964 @smallexample
14965 @b{pragma} Linker_Options ("-lmy_lib");
14966 @end smallexample
14968 @node Installing an Ada Library
14969 @section Installing an Ada Library
14971 @noindent
14972 In the GNAT model, installing a library consists in copying into a specific
14973 location the files that make up this library. It is possible to install
14974 the sources in a different directory from the other files (ALI, objects,
14975 archives) since the source path and the object path can easily be
14976 specified separately.
14978 @noindent
14979 For general purpose libraries, it is possible for the system
14980 administrator to put those libraries in the default compiler paths. To
14981 achieve this, he must specify their location in the configuration files
14982 "ada_source_path" and "ada_object_path" that must be located in the GNAT
14983 installation tree at the same place as the gcc spec file. The location of
14984 the gcc spec file can be determined as follows:
14985 @smallexample
14986 $ gcc -v
14987 @end smallexample
14989 @noindent
14990 The configuration files mentioned above have simple format: each line in them
14991 must contain one unique
14992 directory name. Those names are added to the corresponding path
14993 in their order of appearance in the file. The names can be either absolute
14994 or relative, in the latter case, they are relative to where theses files
14995 are located.
14997 @noindent
14998 "ada_source_path" and "ada_object_path" might actually not be present in a
14999 GNAT installation, in which case, GNAT will look for its run-time library in
15000 the directories "adainclude" for the sources and "adalib" for the
15001 objects and ALI files. When the files exist, the compiler does not
15002 look in "adainclude" and "adalib" at all, and thus the "ada_source_path" file
15003 must contain the location for the GNAT run-time sources (which can simply
15004 be "adainclude"). In the same way, the "ada_object_path" file must contain
15005 the location for the GNAT run-time objects (which can simply
15006 be "adalib").
15008 @noindent
15009 You can also specify a new default path to the runtime library at compilation
15010 time with the switch "--RTS=@var{rts-path}". You can easily choose and change
15011 the runtime you want your program to be compiled with. This switch is
15012 recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref.
15014 @noindent
15015 It is possible to install a library before or after the standard GNAT
15016 library, by reordering the lines in the configuration files. In general, a
15017 library must be installed before the GNAT library if it redefines any part of it.
15019 @node Using an Ada Library
15020 @section Using an Ada Library
15022 @noindent
15023 In order to use a Ada library, you need to make sure that this
15024 library is on both your source and object path
15025 @ref{Search Paths and the Run-Time Library (RTL)}
15026 and @ref{Search Paths for gnatbind}. For
15027 instance, you can use the library "mylib" installed in "/dir/my_lib_src"
15028 and "/dir/my_lib_obj" with the following commands:
15030 @smallexample
15031 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
15032   -largs -lmy_lib
15033 @end smallexample
15035 @noindent
15036 This can be simplified down to the following:
15037 @smallexample
15038 $ gnatmake my_appl
15039 @end smallexample
15040 when the following conditions are met:
15041 @itemize @bullet
15042 @item
15043 "/dir/my_lib_src" has been added by the user to the environment
15044 variable "ADA_INCLUDE_PATH", or by the administrator to the file
15045 "ada_source_path"
15046 @item
15047 "/dir/my_lib_obj" has been added by the user to the environment
15048 variable "ADA_OBJECTS_PATH", or by the administrator to the file
15049 "ada_object_path"
15050 @item
15051 a pragma linker_options, as mentioned in @ref{Creating an Ada Library}
15052 as been added to the sources.
15053 @end itemize
15054 @noindent
15056 @node Creating an Ada Library to be Used in a Non-Ada Context
15057 @section Creating an Ada Library to be Used in a Non-Ada Context
15059 @noindent
15060 The previous sections detailed how to create and install a library that
15061 was usable from an Ada main program. Using this library in a non-Ada
15062 context is not possible, because the elaboration of the library is
15063 automatically done as part of the main program elaboration.
15065 GNAT also provides the ability to build libraries that can be used both
15066 in an Ada and non-Ada context.  This section describes how to build such
15067 a library, and then how to use it from a C program. The method for
15068 interfacing with the library from other languages such as Fortran for
15069 instance remains the same.
15071 @subsection Creating the Library
15073 @itemize @bullet
15074 @item Identify the units representing the interface of the library.
15076 Here is an example of simple library interface:
15078 @smallexample
15079 package Interface is
15081    procedure Do_Something;
15083    procedure Do_Something_Else;
15085 end Interface;
15086 @end smallexample
15088 @item Use @code{pragma Export} or @code{pragma Convention} for the
15089 exported entities.
15091 Our package @code{Interface} is then updated as follow:
15092 @smallexample
15093 package Interface is
15095    procedure Do_Something;
15096    pragma Export (C, Do_Something, "do_something");
15098    procedure Do_Something_Else;
15099    pragma Export (C, Do_Something_Else, "do_something_else");
15101 end Interface;
15102 @end smallexample
15104 @item Compile all the units composing the library.
15106 @item Bind the library objects.
15108 This step is performed by invoking gnatbind with the @code{-L<prefix>}
15109 switch. @code{gnatbind} will then generate the library elaboration
15110 procedure (named @code{<prefix>init}) and the run-time finalization
15111 procedure (named @code{<prefix>final}).
15113 @smallexample
15114 # generate the binder file in Ada
15115 $ gnatbind -Lmylib interface
15117 # generate the binder file in C
15118 $ gnatbind -C -Lmylib interface
15119 @end smallexample
15121 @item Compile the files generated by the binder
15123 @smallexample
15124 $ gcc -c b~interface.adb
15125 @end smallexample
15127 @item Create the library;
15129 The procedure is identical to the procedure explained in
15130 @ref{Creating an Ada Library},
15131 except that @file{b~interface.o} needs to be added to
15132 the list of objects.
15134 @smallexample
15135 # create an archive file
15136 $ ar cr libmylib.a b~interface.o <other object files>
15138 # create a shared library
15139 $ gcc -shared -o libmylib.so b~interface.o <other object files>
15140 @end smallexample
15142 @item Provide a "foreign" view of the library interface;
15144 The example below shows the content of @code{mylib_interface.h} (note
15145 that there is no rule for the naming of this file, any name can be used)
15146 @smallexample
15147 /* the library elaboration procedure */
15148 extern void mylibinit (void);
15150 /* the library finalization procedure */
15151 extern void mylibfinal (void);
15153 /* the interface exported by the library */
15154 extern void do_something (void);
15155 extern void do_something_else (void);
15156 @end smallexample
15157 @end itemize
15159 @subsection Using the Library
15161 @noindent
15162 Libraries built as explained above can be used from any program, provided
15163 that the elaboration procedures (named @code{mylibinit} in the previous
15164 example) are called before the library services are used. Any number of
15165 libraries can be used simultaneously, as long as the elaboration
15166 procedure of each library is called.
15168 Below is an example of C program that uses our @code{mylib} library.
15170 @smallexample
15171 #include "mylib_interface.h"
15174 main (void)
15176    /* First, elaborate the library before using it */
15177    mylibinit ();
15179    /* Main program, using the library exported entities */
15180    do_something ();
15181    do_something_else ();
15183    /* Library finalization at the end of the program */
15184    mylibfinal ();
15185    return 0;
15187 @end smallexample
15189 @noindent
15190 Note that this same library can be used from an equivalent Ada main
15191 program. In addition, if the libraries are installed as detailed in
15192 @ref{Installing an Ada Library}, it is not necessary to invoke the
15193 library elaboration and finalization routines. The binder will ensure
15194 that this is done as part of the main program elaboration and
15195 finalization phases.
15197 @subsection The Finalization Phase
15199 @noindent
15200 Invoking any library finalization procedure generated by @code{gnatbind}
15201 shuts down the Ada run time permanently. Consequently, the finalization
15202 of all Ada libraries must be performed at the end of the program. No
15203 call to these libraries nor the Ada run time should be made past the
15204 finalization phase.
15206 @subsection Restrictions in Libraries
15208 @noindent
15209 The pragmas listed below should be used with caution inside libraries,
15210 as they can create incompatibilities with other Ada libraries:
15211 @itemize @bullet
15212 @item pragma @code{Locking_Policy}
15213 @item pragma @code{Queuing_Policy}
15214 @item pragma @code{Task_Dispatching_Policy}
15215 @item pragma @code{Unreserve_All_Interrupts}
15216 @end itemize
15217 When using a library that contains such pragmas, the user must make sure
15218 that all libraries use the same pragmas with the same values. Otherwise,
15219 a @code{Program_Error} will
15220 be raised during the elaboration of the conflicting
15221 libraries. The usage of these pragmas and its consequences for the user
15222 should therefore be well documented.
15224 Similarly, the traceback in exception occurrences mechanism should be
15225 enabled or disabled in a consistent manner across all libraries.
15226 Otherwise, a Program_Error will be raised during the elaboration of the
15227 conflicting libraries.
15229 If the @code{'Version} and @code{'Body_Version}
15230 attributes are used inside a library, then it is necessary to
15231 perform a @code{gnatbind} step that mentions all ali files in all
15232 libraries, so that version identifiers can be properly computed.
15233 In practice these attributes are rarely used, so this is unlikely
15234 to be a consideration.
15236 @node  Rebuilding the GNAT Run-Time Library
15237 @section Rebuilding the GNAT Run-Time Library
15239 @noindent
15240 It may be useful to recompile the GNAT library in various contexts, the
15241 most important one being the use of partition-wide configuration pragmas
15242 such as Normalize_Scalar. A special Makefile called
15243 @code{Makefile.adalib} is provided to that effect and can be found in
15244 the directory containing the GNAT library. The location of this
15245 directory depends on the way the GNAT environment has been installed and can
15246 be determined by means of the command:
15248 @smallexample
15249 $ gnatls -v
15250 @end smallexample
15252 @noindent
15253 The last entry in the object search path usually contains the
15254 gnat library. This Makefile contains its own documentation and in
15255 particular the set of instructions needed to rebuild a new library and
15256 to use it.
15258 @node Using the GNU make Utility
15259 @chapter Using the GNU @code{make} Utility
15260 @findex make
15262 @noindent
15263 This chapter offers some examples of makefiles that solve specific
15264 problems. It does not explain how to write a makefile (see the GNU make
15265 documentation), nor does it try to replace the @code{gnatmake} utility
15266 (@pxref{The GNAT Make Program gnatmake}).
15268 All the examples in this section are specific to the GNU version of
15269 make. Although @code{make} is a standard utility, and the basic language
15270 is the same, these examples use some advanced features found only in
15271 @code{GNU make}.
15273 @menu
15274 * Using gnatmake in a Makefile::
15275 * Automatically Creating a List of Directories::
15276 * Generating the Command Line Switches::
15277 * Overcoming Command Line Length Limits::
15278 @end menu
15280 @node Using gnatmake in a Makefile
15281 @section Using gnatmake in a Makefile
15282 @findex makefile
15283 @cindex GNU make
15285 @noindent
15286 Complex project organizations can be handled in a very powerful way by
15287 using GNU make combined with gnatmake. For instance, here is a Makefile
15288 which allows you to build each subsystem of a big project into a separate
15289 shared library. Such a makefile allows you to significantly reduce the link
15290 time of very big applications while maintaining full coherence at
15291 each step of the build process.
15293 The list of dependencies are handled automatically by
15294 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
15295 the appropriate directories.
15297 Note that you should also read the example on how to automatically
15298 create the list of directories (@pxref{Automatically Creating a List of Directories})
15299 which might help you in case your project has a lot of
15300 subdirectories.
15302 @smallexample
15303 @iftex
15304 @leftskip=0cm
15305 @font@heightrm=cmr8
15306 @heightrm
15307 @end iftex
15308 ## This Makefile is intended to be used with the following directory
15309 ## configuration:
15310 ##  - The sources are split into a series of csc (computer software components)
15311 ##    Each of these csc is put in its own directory.
15312 ##    Their name are referenced by the directory names.
15313 ##    They will be compiled into shared library (although this would also work
15314 ##    with static libraries
15315 ##  - The main program (and possibly other packages that do not belong to any
15316 ##    csc is put in the top level directory (where the Makefile is).
15317 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
15318 ##                    \_ second_csc (sources) __ lib (will contain the library)
15319 ##                    \_ ...
15320 ## Although this Makefile is build for shared library, it is easy to modify
15321 ## to build partial link objects instead (modify the lines with -shared and
15322 ## gnatlink below)
15324 ## With this makefile, you can change any file in the system or add any new
15325 ## file, and everything will be recompiled correctly (only the relevant shared
15326 ## objects will be recompiled, and the main program will be re-linked).
15328 # The list of computer software component for your project. This might be
15329 # generated automatically.
15330 CSC_LIST=aa bb cc
15332 # Name of the main program (no extension)
15333 MAIN=main
15335 # If we need to build objects with -fPIC, uncomment the following line
15336 #NEED_FPIC=-fPIC
15338 # The following variable should give the directory containing libgnat.so
15339 # You can get this directory through 'gnatls -v'. This is usually the last
15340 # directory in the Object_Path.
15341 GLIB=...
15343 # The directories for the libraries
15344 # (This macro expands the list of CSC to the list of shared libraries, you
15345 # could simply use the expanded form :
15346 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
15347 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
15349 $@{MAIN@}: objects $@{LIB_DIR@}
15350     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
15351     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
15353 objects::
15354     # recompile the sources
15355     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
15357 # Note: In a future version of GNAT, the following commands will be simplified
15358 # by a new tool, gnatmlib
15359 $@{LIB_DIR@}:
15360     mkdir -p $@{dir $@@ @}
15361     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
15362     cd $@{dir $@@ @}; cp -f ../*.ali .
15364 # The dependencies for the modules
15365 # Note that we have to force the expansion of *.o, since in some cases make won't
15366 # be able to do it itself.
15367 aa/lib/libaa.so: $@{wildcard aa/*.o@}
15368 bb/lib/libbb.so: $@{wildcard bb/*.o@}
15369 cc/lib/libcc.so: $@{wildcard cc/*.o@}
15371 # Make sure all of the shared libraries are in the path before starting the
15372 # program
15373 run::
15374     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
15376 clean::
15377     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
15378     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
15379     $@{RM@} $@{CSC_LIST:%=%/*.o@}
15380     $@{RM@} *.o *.ali $@{MAIN@}
15381 @end smallexample
15383 @node Automatically Creating a List of Directories
15384 @section Automatically Creating a List of Directories
15386 @noindent
15387 In most makefiles, you will have to specify a list of directories, and
15388 store it in a variable. For small projects, it is often easier to
15389 specify each of them by hand, since you then have full control over what
15390 is the proper order for these directories, which ones should be
15391 included...
15393 However, in larger projects, which might involve hundreds of
15394 subdirectories, it might be more convenient to generate this list
15395 automatically.
15397 The example below presents two methods. The first one, although less
15398 general, gives you more control over the list. It involves wildcard
15399 characters, that are automatically expanded by @code{make}. Its
15400 shortcoming is that you need to explicitly specify some of the
15401 organization of your project, such as for instance the directory tree
15402 depth, whether some directories are found in a separate tree,...
15404 The second method is the most general one. It requires an external
15405 program, called @code{find}, which is standard on all Unix systems. All
15406 the directories found under a given root directory will be added to the
15407 list.
15409 @smallexample
15410 @iftex
15411 @leftskip=0cm
15412 @font@heightrm=cmr8
15413 @heightrm
15414 @end iftex
15415 # The examples below are based on the following directory hierarchy:
15416 # All the directories can contain any number of files
15417 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
15418 #                       ->  ab
15419 #                       ->  ac
15420 #                ->  b  ->  ba  ->  baa
15421 #                       ->  bb
15422 #                       ->  bc
15423 # This Makefile creates a variable called DIRS, that can be reused any time
15424 # you need this list (see the other examples in this section)
15426 # The root of your project's directory hierarchy
15427 ROOT_DIRECTORY=.
15429 ####
15430 # First method: specify explicitly the list of directories
15431 # This allows you to specify any subset of all the directories you need.
15432 ####
15434 DIRS := a/aa/ a/ab/ b/ba/
15436 ####
15437 # Second method: use wildcards
15438 # Note that the argument(s) to wildcard below should end with a '/'.
15439 # Since wildcards also return file names, we have to filter them out
15440 # to avoid duplicate directory names.
15441 # We thus use make's @code{dir} and @code{sort} functions.
15442 # It sets DIRs to the following value (note that the directories aaa and baa
15443 # are not given, unless you change the arguments to wildcard).
15444 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
15445 ####
15447 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ $@{ROOT_DIRECTORY@}/*/*/@}@}@}
15449 ####
15450 # Third method: use an external program
15451 # This command is much faster if run on local disks, avoiding NFS slowdowns.
15452 # This is the most complete command: it sets DIRs to the following value:
15453 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
15454 ####
15456 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
15458 @end smallexample
15460 @node Generating the Command Line Switches
15461 @section Generating the Command Line Switches
15463 @noindent
15464 Once you have created the list of directories as explained in the
15465 previous section (@pxref{Automatically Creating a List of Directories}),
15466 you can easily generate the command line arguments to pass to gnatmake.
15468 For the sake of completeness, this example assumes that the source path
15469 is not the same as the object path, and that you have two separate lists
15470 of directories.
15472 @smallexample
15473 # see "Automatically creating a list of directories" to create
15474 # these variables
15475 SOURCE_DIRS=
15476 OBJECT_DIRS=
15478 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
15479 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
15481 all:
15482         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
15483 @end smallexample
15485 @node Overcoming Command Line Length Limits
15486 @section Overcoming Command Line Length Limits
15488 @noindent
15489 One problem that might be encountered on big projects is that many
15490 operating systems limit the length of the command line. It is thus hard to give
15491 gnatmake the list of source and object directories.
15493 This example shows how you can set up environment variables, which will
15494 make @code{gnatmake} behave exactly as if the directories had been
15495 specified on the command line, but have a much higher length limit (or
15496 even none on most systems).
15498 It assumes that you have created a list of directories in your Makefile,
15499 using one of the methods presented in
15500 @ref{Automatically Creating a List of Directories}.
15501 For the sake of completeness, we assume that the object
15502 path (where the ALI files are found) is different from the sources patch.
15504 Note a small trick in the Makefile below: for efficiency reasons, we
15505 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
15506 expanded immediately by @code{make}. This way we overcome the standard
15507 make behavior which is to expand the variables only when they are
15508 actually used.
15510 @smallexample
15511 @iftex
15512 @leftskip=0cm
15513 @font@heightrm=cmr8
15514 @heightrm
15515 @end iftex
15516 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
15517 # This is the same thing as putting the -I arguments on the command line.
15518 # (the equivalent of using -aI on the command line would be to define
15519 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
15520 # You can of course have different values for these variables.
15522 # Note also that we need to keep the previous values of these variables, since
15523 # they might have been set before running 'make' to specify where the GNAT
15524 # library is installed.
15526 # see "Automatically creating a list of directories" to create these
15527 # variables
15528 SOURCE_DIRS=
15529 OBJECT_DIRS=
15531 empty:=
15532 space:=$@{empty@} $@{empty@}
15533 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
15534 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
15535 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
15536 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
15537 export ADA_INCLUDE_PATH
15538 export ADA_OBJECT_PATH
15540 all:
15541         gnatmake main_unit
15542 @end smallexample
15544 @ifclear vxworks
15545 @node Finding Memory Problems with gnatmem
15546 @chapter Finding Memory Problems with @code{gnatmem}
15547 @findex gnatmem
15549 @noindent
15550 @code{gnatmem}, is a tool that monitors dynamic allocation and
15551 deallocation activity in a program, and displays information about
15552 incorrect deallocations and possible sources of memory leaks. Gnatmem
15553 provides three type of information:
15554 @itemize @bullet
15555 @item
15556 General information concerning memory management, such as the total
15557 number of allocations and deallocations, the amount of allocated
15558 memory and the high water mark, i.e. the largest amount of allocated
15559 memory in the course of program execution.
15561 @item
15562 Backtraces for all incorrect deallocations, that is to say deallocations
15563 which do not correspond to a valid allocation.
15565 @item
15566 Information on each allocation that is potentially the origin of a memory
15567 leak.
15568 @end itemize
15570 The @code{gnatmem} command has two modes. It can be used with @code{gdb}
15571 or with instrumented allocation and deallocation routines. The later
15572 mode is called the @code{GMEM} mode. Both modes produce the very same
15573 output.
15575 @menu
15576 * Running gnatmem (GDB Mode)::
15577 * Running gnatmem (GMEM Mode)::
15578 * Switches for gnatmem::
15579 * Examples of gnatmem Usage::
15580 * GDB and GMEM Modes::
15581 * Implementation Note::
15582 @end menu
15584 @node Running gnatmem (GDB Mode)
15585 @section Running @code{gnatmem} (GDB Mode)
15587 @noindent
15588 The @code{gnatmem} command has the form
15590 @smallexample
15591    $ gnatmem [-q] [n] [-o file] user_program [program_arg]*
15593    $ gnatmem [-q] [n] -i file
15594 @end smallexample
15596 @noindent
15597 Gnatmem must be supplied with the executable to examine, followed by its
15598 run-time inputs. For example, if a program is executed with the command:
15599 @smallexample
15600 $ my_program arg1 arg2
15601 @end smallexample
15602 then it can be run under @code{gnatmem} control using the command:
15603 @smallexample
15604 $ gnatmem my_program arg1 arg2
15605 @end smallexample
15607 The program is transparently executed under the control of the debugger
15608 @ref{The GNAT Debugger GDB}. This does not affect the behavior
15609 of the program, except for sensitive real-time programs. When the program
15610 has completed execution, @code{gnatmem} outputs a report containing general
15611 allocation/deallocation information and potential memory leak.
15612 For better results, the user program should be compiled with
15613 debugging options @ref{Switches for gcc}.
15615 Here is a simple example of use:
15617 *************** debut cc
15618 @smallexample
15619 $ gnatmem test_gm
15621 Global information
15622 ------------------
15623    Total number of allocations        :  45
15624    Total number of deallocations      :   6
15625    Final Water Mark (non freed mem)   :  11.29 Kilobytes
15626    High Water Mark                    :  11.40 Kilobytes
15631 Allocation Root # 2
15632 -------------------
15633  Number of non freed allocations    :  11
15634  Final Water Mark (non freed mem)   :   1.16 Kilobytes
15635  High Water Mark                    :   1.27 Kilobytes
15636  Backtrace                          :
15637    test_gm.adb:23 test_gm.alloc
15641 @end smallexample
15643 The first block of output give general information. In this case, the
15644 Ada construct "@b{new}" was executed 45 times, and only 6 calls to an
15645 unchecked deallocation routine occurred.
15647 Subsequent paragraphs display  information on all allocation roots.
15648 An allocation root is a specific point in the execution of the program
15649 that generates some dynamic allocation, such as a "@b{new}" construct. This
15650 root is represented by an execution backtrace (or subprogram call
15651 stack). By default the backtrace depth for allocations roots is 1, so
15652 that a root corresponds exactly to a source location. The backtrace can
15653 be made deeper, to make the root more specific.
15655 @node Running gnatmem (GMEM Mode)
15656 @section Running @code{gnatmem} (GMEM Mode)
15657 @cindex @code{GMEM} (@code{gnatmem})
15659 @noindent
15660 The @code{gnatmem} command has the form
15662 @smallexample
15663    $ gnatmem [-q] [n] -i gmem.out user_program [program_arg]*
15664 @end smallexample
15666 The program must have been linked with the instrumented version of the
15667 allocation and deallocation routines. This is done with linking with the
15668 @file{libgmem.a} library. For better results, the user program should be
15669 compiled with debugging options @ref{Switches for gcc}. For example to
15670 build @file{my_program}:
15672 @smallexample
15673 $ gnatmake -g my_program -largs -lgmem
15674 @end smallexample
15676 @noindent
15677 When running @file{my_program} the file @file{gmem.out} is produced. This file
15678 contains information about all allocations and deallocations done by the
15679 program. It is produced by the instrumented allocations and
15680 deallocations routines and will be used by @code{gnatmem}.
15682 @noindent
15683 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
15684 examine followed by its run-time inputs. For example, if a program is
15685 executed with the command:
15686 @smallexample
15687 $ my_program arg1 arg2
15688 @end smallexample
15689 then @file{gmem.out} can be analysed by @code{gnatmem} using the command:
15690 @smallexample
15691 $ gnatmem -i gmem.out my_program arg1 arg2
15692 @end smallexample
15694 @node Switches for gnatmem
15695 @section Switches for @code{gnatmem}
15697 @noindent
15698 @code{gnatmem} recognizes the following switches:
15700 @table @code
15702 @item @code{-q}
15703 @cindex @code{-q} (@code{gnatmem})
15704 Quiet. Gives the minimum output needed to identify the origin of the
15705 memory leaks. Omit statistical information.
15707 @item @code{n}
15708 @cindex @code{n} (@code{gnatmem})
15709 N is an integer literal (usually between 1 and 10) which controls the
15710 depth of the backtraces defining allocation root. The default value for
15711 N is 1. The deeper the backtrace, the more precise the localization of
15712 the root. Note that the total number of roots can depend on this
15713 parameter.
15715 @item @code{-o file}
15716 @cindex @code{-o} (@code{gnatmem})
15717 Direct the gdb output to the specified file. The @code{gdb} script used
15718 to generate this output is also saved in the file @file{gnatmem.tmp}.
15720 @item @code{-i file}
15721 @cindex @code{-i} (@code{gnatmem})
15722 Do the @code{gnatmem} processing starting from @file{file} which has
15723 been generated by a previous call to @code{gnatmem} with the -o
15724 switch or @file{gmem.out} produced by @code{GMEM} mode. This is useful
15725 for post mortem processing.
15727 @end table
15729 @node Examples of gnatmem Usage
15730 @section Example of @code{gnatmem} Usage
15732 @noindent
15733 This section is based on the @code{GDB} mode of @code{gnatmem}. The same
15734 results can be achieved using @code{GMEM} mode. See section
15735 @ref{Running gnatmem (GMEM Mode)}.
15737 @noindent
15738 The first example shows the use of @code{gnatmem}
15739 on a simple leaking program.
15740 Suppose that we have the following Ada program:
15742 @smallexample
15743 @group
15744 @cartouche
15745 @b{with} Unchecked_Deallocation;
15746 @b{procedure} Test_Gm @b{is}
15748    @b{type} T @b{is array} (1..1000) @b{of} Integer;
15749    @b{type} Ptr @b{is access} T;
15750    @b{procedure} Free @b{is new} Unchecked_Deallocation (T, Ptr);
15751    A : Ptr;
15753    @b{procedure} My_Alloc @b{is}
15754    @b{begin}
15755       A := @b{new} T;
15756    @b{end} My_Alloc;
15758    @b{procedure} My_DeAlloc @b{is}
15759       B : Ptr := A;
15760    @b{begin}
15761       Free (B);
15762    @b{end} My_DeAlloc;
15764 @b{begin}
15765    My_Alloc;
15766    @b{for} I @b{in} 1 .. 5 @b{loop}
15767       @b{for} J @b{in} I .. 5 @b{loop}
15768          My_Alloc;
15769       @b{end loop};
15770       My_Dealloc;
15771    @b{end loop};
15772 @b{end};
15773 @end cartouche
15774 @end group
15775 @end smallexample
15777 @noindent
15778 The program needs to be compiled with debugging option:
15780 @smallexample
15781 $ gnatmake -g test_gm
15782 @end smallexample
15784 @code{gnatmem} is invoked simply with
15785 @smallexample
15786 $ gnatmem test_gm
15787 @end smallexample
15789 @noindent
15790 which produces the following output:
15792 @smallexample
15793 Global information
15794 ------------------
15795    Total number of allocations        :  18
15796    Total number of deallocations      :   5
15797    Final Water Mark (non freed mem)   :  53.00 Kilobytes
15798    High Water Mark                    :  56.90 Kilobytes
15800 Allocation Root # 1
15801 -------------------
15802  Number of non freed allocations    :  11
15803  Final Water Mark (non freed mem)   :  42.97 Kilobytes
15804  High Water Mark                    :  46.88 Kilobytes
15805  Backtrace                          :
15806    test_gm.adb:11 test_gm.my_alloc
15808 Allocation Root # 2
15809 -------------------
15810  Number of non freed allocations    :   1
15811  Final Water Mark (non freed mem)   :  10.02 Kilobytes
15812  High Water Mark                    :  10.02 Kilobytes
15813  Backtrace                          :
15814    s-secsta.adb:81 system.secondary_stack.ss_init
15816 Allocation Root # 3
15817 -------------------
15818  Number of non freed allocations    :   1
15819  Final Water Mark (non freed mem)   :  12 Bytes
15820  High Water Mark                    :  12 Bytes
15821  Backtrace                          :
15822    s-secsta.adb:181 system.secondary_stack.ss_init
15823 @end smallexample
15825 @noindent
15826 Note that the GNAT run time contains itself a certain number of
15827 allocations that have no  corresponding deallocation,
15828 as shown here for root #2 and root
15829 #1. This is a normal behavior when the number of non freed allocations
15830 is one, it locates dynamic data structures that the run time needs for
15831 the complete lifetime of the program. Note also that there is only one
15832 allocation root in the user program with a single line back trace:
15833 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
15834 program shows that 'My_Alloc' is called at 2 different points in the
15835 source (line 21 and line 24). If those two allocation roots need to be
15836 distinguished, the backtrace depth parameter can be used:
15838 @smallexample
15839 $ gnatmem 3 test_gm
15840 @end smallexample
15842 @noindent
15843 which will give the following output:
15845 @smallexample
15846 Global information
15847 ------------------
15848    Total number of allocations        :  18
15849    Total number of deallocations      :   5
15850    Final Water Mark (non freed mem)   :  53.00 Kilobytes
15851    High Water Mark                    :  56.90 Kilobytes
15853 Allocation Root # 1
15854 -------------------
15855  Number of non freed allocations    :  10
15856  Final Water Mark (non freed mem)   :  39.06 Kilobytes
15857  High Water Mark                    :  42.97 Kilobytes
15858  Backtrace                          :
15859    test_gm.adb:11 test_gm.my_alloc
15860    test_gm.adb:24 test_gm
15861    b_test_gm.c:52 main
15863 Allocation Root # 2
15864 -------------------
15865  Number of non freed allocations    :   1
15866  Final Water Mark (non freed mem)   :  10.02 Kilobytes
15867  High Water Mark                    :  10.02 Kilobytes
15868  Backtrace                          :
15869    s-secsta.adb:81  system.secondary_stack.ss_init
15870    s-secsta.adb:283 <system__secondary_stack___elabb>
15871    b_test_gm.c:33   adainit
15873 Allocation Root # 3
15874 -------------------
15875  Number of non freed allocations    :   1
15876  Final Water Mark (non freed mem)   :   3.91 Kilobytes
15877  High Water Mark                    :   3.91 Kilobytes
15878  Backtrace                          :
15879    test_gm.adb:11 test_gm.my_alloc
15880    test_gm.adb:21 test_gm
15881    b_test_gm.c:52 main
15883 Allocation Root # 4
15884 -------------------
15885  Number of non freed allocations    :   1
15886  Final Water Mark (non freed mem)   :  12 Bytes
15887  High Water Mark                    :  12 Bytes
15888  Backtrace                          :
15889    s-secsta.adb:181 system.secondary_stack.ss_init
15890    s-secsta.adb:283 <system__secondary_stack___elabb>
15891    b_test_gm.c:33   adainit
15892 @end smallexample
15894 @noindent
15895 The allocation root #1 of the first example has been split in 2 roots #1
15896 and #3 thanks to the more precise associated backtrace.
15898 @node GDB and GMEM Modes
15899 @section GDB and GMEM Modes
15901 @noindent
15902 The main advantage of the @code{GMEM} mode is that it is a lot faster than the
15903 @code{GDB} mode where the application must be monitored by a @code{GDB} script.
15904 But the @code{GMEM} mode is available only for DEC Unix, Linux x86,
15905 Solaris (sparc and x86) and Windows 95/98/NT/2000 (x86).
15907 @noindent
15908 The main advantage of the @code{GDB} mode is that it is available on all
15909 supported platforms. But it can be very slow if the application does a
15910 lot of allocations and deallocations.
15912 @node Implementation Note
15913 @section Implementation Note
15915 @menu
15916 * gnatmem Using GDB Mode::
15917 * gnatmem Using GMEM Mode::
15918 @end menu
15920 @node gnatmem Using GDB Mode
15921 @subsection @code{gnatmem} Using @code{GDB} Mode
15923 @noindent
15924 @code{gnatmem} executes the user program under the control of @code{GDB} using
15925 a script that sets breakpoints and gathers information on each dynamic
15926 allocation and deallocation. The output of the script is then analyzed
15927 by @code{gnatmem}
15928 in order to locate memory leaks and their origin in the
15929 program. Gnatmem works by recording each address returned by the
15930 allocation procedure (@code{__gnat_malloc})
15931 along with the backtrace at the
15932 allocation point. On each deallocation, the deallocated address is
15933 matched with the corresponding allocation. At the end of the processing,
15934 the unmatched allocations are considered potential leaks. All the
15935 allocations associated with the same backtrace are grouped together and
15936 form an allocation root. The allocation roots are then sorted so that
15937 those with the biggest number of unmatched allocation are printed
15938 first. A delicate aspect of this technique is to distinguish between the
15939 data produced by the user program and the data produced by the gdb
15940 script. Currently, on systems that allow probing the terminal, the gdb
15941 command "tty" is used to force the program output to be redirected to the
15942 current terminal while the @code{gdb} output is directed to a file or to a
15943 pipe in order to be processed subsequently by @code{gnatmem}.
15945 @node gnatmem Using GMEM Mode
15946 @subsection @code{gnatmem} Using @code{GMEM} Mode
15948 @noindent
15949 This mode use the same algorithm to detect memory leak as the @code{GDB}
15950 mode of @code{gnatmem}, the only difference is in the way data are
15951 gathered. In @code{GMEM} mode the program is linked with instrumented
15952 version of @code{__gnat_malloc} and @code{__gnat_free}
15953 routines. Information needed to find memory leak are recorded by these
15954 routines in file @file{gmem.out}. This mode also require that the stack
15955 traceback be available, this is only implemented on some platforms
15956 @ref{GDB and GMEM Modes}.
15958 @end ifclear
15959 @end ifclear
15961 @node Finding Memory Problems with GNAT Debug Pool
15962 @chapter Finding Memory Problems with GNAT Debug Pool
15963 @findex Debug Pool
15964 @cindex storage, pool, memory corruption
15966 @noindent
15967 The use of unchecked deallocation and unchecked conversion can easily
15968 lead to incorrect memory references. The problems generated by such
15969 references are usually difficult to tackle because the symptoms can be
15970 very remote from the origin of the problem. In such cases, it is
15971 very helpful to detect the problem as early as possible. This is the
15972 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
15974 @noindent
15975 In order to use the GNAT specific debugging pool, the user must
15976 associate a debug pool object with each of the access types that may be
15977 related to suspected memory problems. See Ada Reference Manual
15978 13.11.
15979 @smallexample
15980 @b{type} Ptr @b{is} @b{access} Some_Type;
15981 Pool : GNAT.Debug_Pools.Debug_Pool;
15982 @b{for} Ptr'Storage_Pool @b{use} Pool;
15983 @end smallexample
15985 @code{GNAT.Debug_Pools} is derived from of a GNAT-specific kind of
15986 pool: the Checked_Pool. Such pools, like standard Ada storage pools,
15987 allow the user to redefine allocation and deallocation strategies. They
15988 also provide a checkpoint for each dereference, through the use of
15989 the primitive operation @code{Dereference} which is implicitly called at
15990 each dereference of an access value.
15992 Once an access type has been associated with a debug pool, operations on
15993 values of the type may raise four distinct exceptions,
15994 which correspond to four potential kinds of memory corruption:
15995 @itemize @bullet
15996 @item
15997 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
15998 @item
15999 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
16000 @item
16001 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
16002 @item
16003 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
16004 @end itemize
16006 @noindent
16007 For types associated with a Debug_Pool, dynamic allocation is performed using
16008 the standard
16009 GNAT allocation routine. References to all allocated chunks of memory
16010 are kept in an internal dictionary. The deallocation strategy consists
16011 in not releasing the memory to the underlying system but rather to fill
16012 it with a memory pattern easily recognizable during debugging sessions:
16013 The memory pattern is the old IBM hexadecimal convention: 16#DEADBEEF#.
16014 Upon each dereference, a check is made that the access value denotes a properly
16015 allocated memory location. Here is a complete example of use of
16016 @code{Debug_Pools}, that includes typical instances of  memory corruption:
16017 @smallexample
16018 @iftex
16019 @leftskip=0cm
16020 @end iftex
16021 @b{with} Gnat.Io; @b{use} Gnat.Io;
16022 @b{with} Unchecked_Deallocation;
16023 @b{with} Unchecked_Conversion;
16024 @b{with} GNAT.Debug_Pools;
16025 @b{with} System.Storage_Elements;
16026 @b{with} Ada.Exceptions; @b{use} Ada.Exceptions;
16027 @b{procedure} Debug_Pool_Test @b{is}
16029    @b{type} T @b{is} @b{access} Integer;
16030    @b{type} U @b{is} @b{access} @b{all} T;
16032    P : GNAT.Debug_Pools.Debug_Pool;
16033    @b{for} T'Storage_Pool @b{use} P;
16035    @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T);
16036    @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T);
16037    A, B : @b{aliased} T;
16039    @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line);
16041 @b{begin}
16042    Info (P);
16043    A := @b{new} Integer;
16044    B := @b{new} Integer;
16045    B := A;
16046    Info (P);
16047    Free (A);
16048    @b{begin}
16049       Put_Line (Integer'Image(B.@b{all}));
16050    @b{exception}
16051       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
16052    @b{end};
16053    @b{begin}
16054       Free (B);
16055    @b{exception}
16056       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
16057    @b{end};
16058    B := UC(A'Access);
16059    @b{begin}
16060       Put_Line (Integer'Image(B.@b{all}));
16061    @b{exception}
16062       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
16063    @b{end};
16064    @b{begin}
16065       Free (B);
16066    @b{exception}
16067       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
16068    @b{end};
16069    Info (P);
16070 @b{end} Debug_Pool_Test;
16071 @end smallexample
16072 @noindent
16073 The debug pool mechanism provides the following precise diagnostics on the
16074 execution of this erroneous program:
16075 @smallexample
16076 Debug Pool info:
16077   Total allocated bytes :  0
16078   Total deallocated bytes :  0
16079   Current Water Mark:  0
16080   High Water Mark:  0
16082 Debug Pool info:
16083   Total allocated bytes :  8
16084   Total deallocated bytes :  0
16085   Current Water Mark:  8
16086   High Water Mark:  8
16088 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16089 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16090 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16091 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16092 Debug Pool info:
16093   Total allocated bytes :  8
16094   Total deallocated bytes :  4
16095   Current Water Mark:  4
16096   High Water Mark:  8
16098 @end smallexample
16100 @node Creating Sample Bodies Using gnatstub
16101 @chapter Creating Sample Bodies Using @code{gnatstub}
16102 @findex gnatstub
16104 @noindent
16105 @code{gnatstub} creates body stubs, that is, empty but compilable bodies
16106 for library unit declarations.
16108 To create a body stub, @code{gnatstub} has to compile the library
16109 unit declaration. Therefore, bodies can be created only for legal
16110 library units. Moreover, if a library unit depends semantically upon
16111 units located outside the current directory, you have to provide
16112 the source search path when calling @code{gnatstub}, see the description
16113 of @code{gnatstub} switches below.
16115 @menu
16116 * Running gnatstub::
16117 * Switches for gnatstub::
16118 @end menu
16120 @node Running gnatstub
16121 @section Running @code{gnatstub}
16123 @noindent
16124 @code{gnatstub} has the command-line interface of the form
16126 @smallexample
16127 $ gnatstub [switches] filename [directory]
16128 @end smallexample
16130 @noindent
16131 where
16132 @table @code
16133 @item filename
16134 is the name of the source file that contains a library unit declaration
16135 for which a body must be created. This name should follow the GNAT file name
16136 conventions. No crunching is allowed for this file name. The file
16137 name may contain the path information.
16139 @item directory
16140 indicates the directory to place a body stub (default is the
16141 current directory)
16143 @item switches
16144 is an optional sequence of switches as described in the next section
16145 @end table
16147 @node Switches for gnatstub
16148 @section Switches for @code{gnatstub}
16150 @table @code
16152 @item ^-f^/FULL^
16153 If the destination directory already contains a file with a name of the body file
16154 for the argument spec file, replace it with the generated body stub.
16156 @item ^-hs^/HEADER=SPEC^
16157 Put the comment header (i.e. all the comments preceding the
16158 compilation unit) from the source of the library unit declaration
16159 into the body stub.
16161 @item ^-hg^/HEADER=GENERAL^
16162 Put a sample comment header into the body stub.
16164 @item -IDIR
16165 @itemx ^-I-^/NOCURRENT_DIRECTORY^
16166 These switches have the same meaning as in calls to gcc.
16167 They define the source search path in the call to gcc issued
16168 by @code{gnatstub} to compile an argument source file.
16170 @item ^-i^/INDENTATION=^@var{n}
16171 (@var{n} is a decimal natural number). Set the indentation level in the
16172 generated body sample to n, '^-i0^/INDENTATION=0^' means "no indentation",
16173 the default indentation is 3.
16175 @item ^-k^/TREE_FILE=SAVE^
16176 Do not remove the tree file (i.e. the snapshot of the compiler internal
16177 structures used by @code{gnatstub}) after creating the body stub.
16179 @item ^-l^/LINE_LENGTH=^@var{n}
16180 (@var{n} is a decimal positive number) Set the maximum line length in the
16181 body stub to n, the default is 78.
16183 @item ^-q^/QUIET^
16184 Quiet mode: do not generate a confirmation when a body is
16185 successfully created or a message when a body is not required for an
16186 argument unit.
16188 @item ^-r^/TREE_FILE=REUSE^
16189 Reuse the tree file (if it exists) instead of creating it: instead of
16190 creating the tree file for the library unit declaration, gnatstub
16191 tries to find it in the current directory and use it for creating
16192 a body. If the tree file is not found, no body is created. @code{^-r^/REUSE^}
16193 also implies @code{^-k^/SAVE^}, whether or not
16194 @code{^-k^/SAVE^} is set explicitly.
16196 @item ^-t^/TREE_FILE=OVERWRITE^
16197 Overwrite the existing tree file: if the current directory already
16198 contains the file which, according to the GNAT file name rules should
16199 be considered as a tree file for the argument source file, gnatstub
16200 will refuse to create the tree file needed to create a body sampler,
16201 unless @code{-t} option is set
16203 @item ^-v^/VERBOSE^
16204 Verbose mode: generate version information.
16206 @end table
16208 @node Reducing the Size of Ada Executables with gnatelim
16209 @chapter Reducing the Size of Ada Executables with @code{gnatelim}
16210 @findex gnatelim
16212 @menu
16213 * About gnatelim::
16214 * Eliminate Pragma::
16215 * Tree Files::
16216 * Preparing Tree and Bind Files for gnatelim::
16217 * Running gnatelim::
16218 * Correcting the List of Eliminate Pragmas::
16219 * Making Your Executables Smaller::
16220 * Summary of the gnatelim Usage Cycle::
16221 @end menu
16223 @node About gnatelim
16224 @section About @code{gnatelim}
16226 @noindent
16227 When a program shares a set of Ada
16228 packages with other programs, it may happen that this program uses
16229 only a fraction of the subprograms defined in these packages. The code
16230 created for these unused subprograms increases the size of the executable.
16232 @code{gnatelim} tracks unused subprograms in an Ada program and
16233 outputs a list of GNAT-specific @code{Eliminate} pragmas (see next
16234 section) marking all the subprograms that are declared but never called.
16235 By placing the list of @code{Eliminate} pragmas in the GNAT configuration
16236 file @file{gnat.adc} and recompiling your program, you may decrease the
16237 size of its executable, because the compiler will not generate the code
16238 for 'eliminated' subprograms.
16240 @code{gnatelim} needs as its input data a set of tree files
16241 (see @ref{Tree Files}) representing all the components of a program to
16242 process and a bind file for a main subprogram (see
16243 @ref{Preparing Tree and Bind Files for gnatelim}).
16245 @node Eliminate Pragma
16246 @section @code{Eliminate} Pragma
16247 @findex Eliminate
16249 @noindent
16250 The simplified syntax of the Eliminate pragma used by @code{gnatelim} is:
16252 @smallexample
16253 @cartouche
16254 @b{pragma} Eliminate (Library_Unit_Name, Subprogram_Name);
16255 @end cartouche
16256 @end smallexample
16258 @noindent
16259 where
16260 @table @code
16261 @item Library_Unit_Name
16262 full expanded Ada name of a library unit
16264 @item Subprogram_Name
16265 a simple or expanded name of a subprogram declared within this
16266 compilation unit
16268 @end table
16270 @noindent
16271 The effect of an @code{Eliminate} pragma placed in the GNAT configuration
16272 file @file{gnat.adc} is:
16274 @itemize @bullet
16276 @item
16277 If the subprogram @code{Subprogram_Name} is declared within
16278 the library unit @code{Library_Unit_Name}, the compiler will not generate
16279 code for this subprogram. This applies to all overloaded subprograms denoted
16280 by @code{Subprogram_Name}.
16282 @item
16283 If a subprogram marked by the pragma @code{Eliminate} is used (called)
16284 in a program, the compiler will produce an error message in the place where
16285 it is called.
16286 @end itemize
16288 @node Tree Files
16289 @section Tree Files
16290 @cindex Tree file
16292 @noindent
16293 A tree file stores a snapshot of the compiler internal data
16294 structures at the very end of a successful compilation. It contains all the
16295 syntactic and semantic information for the compiled unit and all the
16296 units upon which it depends semantically.
16297 To use tools that make use of tree files, you
16298 need to first produce the right set of tree files.
16300 GNAT produces correct tree files when -gnatt -gnatc options are set
16301 in a gcc call. The tree files have an .adt extension.
16302 Therefore, to produce a tree file for the compilation unit contained in a file
16303 named @file{foo.adb}, you must use the command
16305 @smallexample
16306 $ gcc -c -gnatc -gnatt foo.adb
16307 @end smallexample
16309 @noindent
16310 and you will get the tree file @file{foo.adt}.
16311 compilation.
16313 @node Preparing Tree and Bind Files for gnatelim
16314 @section Preparing Tree and Bind Files for @code{gnatelim}
16316 @noindent
16317 A set of tree files covering the program to be analyzed with
16318 @code{gnatelim} and
16319 the bind file for the main subprogram does not have to
16320 be in the current directory.
16321 '-T' gnatelim option may be used to provide
16322 the search path for tree files, and '-b'
16323 option may be used to point to the bind
16324 file to process (see @ref{Running gnatelim})
16326 If you do not have the appropriate set of tree
16327 files and the right bind file, you
16328 may create them in the current directory using the following procedure.
16330 Let @code{Main_Prog} be the name of a main subprogram, and suppose
16331 this subprogram is in a file named @file{main_prog.adb}.
16333 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
16334 the main subprogram. @code{gnatelim} can work with both Ada and C
16335 bind files; when both are present, it uses the Ada bind file.
16336 The following commands will build the program and create the bind file:
16338 @smallexample
16339 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
16340 $ gnatbind main_prog
16341 @end smallexample
16343 @noindent
16344 To create a minimal set of tree files covering the whole program, call
16345 @code{gnatmake} for this program as follows:
16347 @smallexample
16348 @ifset vms
16349 $ GNAT MAKE /FORCE_COMPILE /ACTIONS=COMPILE /NOLOAD /TREE_OUTPUT MAIN_PROG
16350 @end ifset
16351 @ifclear vms
16352 $ gnatmake -f -c -gnatc -gnatt Main_Prog
16353 @end ifclear
16354 @end smallexample
16356 @noindent
16357 The @code{^-c^/ACTIONS=COMPILE^} gnatmake option turns off the bind and link
16358 steps, that are useless anyway because the sources are compiled with
16359 @option{-gnatc} option which turns off code generation.
16361 The @code{^-f^/FORCE_COMPILE^} gnatmake option forces
16362 recompilation of all the needed sources.
16364 This sequence of actions will create all the data needed by @code{gnatelim}
16365 from scratch and therefore guarantee its consistency. If you would like to
16366 use some existing set of files as @code{gnatelim} output, you must make
16367 sure that the set of files is complete and consistent. You can use the
16368 @code{-m} switch to check if there are missed tree files
16370 Note, that @code{gnatelim} needs neither object nor ALI files.
16372 @node Running gnatelim
16373 @section Running @code{gnatelim}
16375 @noindent
16376 @code{gnatelim} has the following command-line interface:
16378 @smallexample
16379 $ gnatelim [options] name
16380 @end smallexample
16382 @noindent
16383 @code{name} should be a full expanded Ada name of a main subprogram
16384 of a program (partition).
16386 @code{gnatelim} options:
16388 @table @code
16389 @item ^-q^/QUIET^
16390 Quiet mode: by default @code{gnatelim} generates to the standard error
16391 stream a trace of the source file names of the compilation units being
16392 processed. This option turns this trace off.
16394 @item ^-v^/VERBOSE^
16395 Verbose mode: @code{gnatelim} version information is printed as Ada
16396 comments to the standard output stream.
16398 @item ^-a^/ALL^
16399 Also look for subprograms from the GNAT run time that can be eliminated.
16401 @item ^-m^/MISSED^
16402 Check if any tree files are missing for an accurate result.
16404 @item ^-T^/TREE_DIRS=^@var{dir}
16405 When looking for tree files also look in directory @var{dir}
16407 @item ^-b^/BIND_FILE=^@var{bind_file}
16408 Specifies @var{bind_file} as the bind file to process. If not set, the name
16409 of the bind file is computed from the full expanded Ada name of a main subprogram.
16411 @item -d@var{x}
16412 Activate internal debugging switches. @var{x} is a letter or digit, or
16413 string of letters or digits, which specifies the type of debugging
16414 mode desired.  Normally these are used only for internal development
16415 or system debugging purposes. You can find full documentation for these
16416 switches in the body of the @code{Gnatelim.Options} unit in the compiler
16417 source file @file{gnatelim-options.adb}.
16418 @end table
16420 @noindent
16421 @code{gnatelim} sends its output to the standard output stream, and all the
16422 tracing and debug information is sent to the standard error stream.
16423 In order to produce a proper GNAT configuration file
16424 @file{gnat.adc}, redirection must be used:
16426 @smallexample
16427 @ifset vms
16428 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
16429 @end ifset
16430 @ifclear vms
16431 $ gnatelim Main_Prog > gnat.adc
16432 @end ifclear
16433 @end smallexample
16435 @ifclear vms
16436 @noindent
16439 @smallexample
16440 $ gnatelim Main_Prog >> gnat.adc
16441 @end smallexample
16442 @end ifclear
16444 @noindent
16445 In order to append the @code{gnatelim} output to the existing contents of
16446 @file{gnat.adc}.
16448 @node Correcting the List of Eliminate Pragmas
16449 @section Correcting the List of Eliminate Pragmas
16451 @noindent
16452 In some rare cases it may happen that @code{gnatelim} will try to eliminate
16453 subprograms which are actually called in the program. In this case, the
16454 compiler will generate an error message of the form:
16456 @smallexample
16457 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
16458 @end smallexample
16460 @noindent
16461 You will need to manually remove the wrong @code{Eliminate} pragmas from
16462 the @file{gnat.adc} file. It is advised that you recompile your program
16463 from scratch after that because you need a consistent @file{gnat.adc} file
16464 during the entire compilation.
16466 @node Making Your Executables Smaller
16467 @section Making Your Executables Smaller
16469 @noindent
16470 In order to get a smaller executable for your program you now have to
16471 recompile the program completely with the new @file{gnat.adc} file
16472 created by @code{gnatelim} in your current directory:
16474 @smallexample
16475 $ gnatmake ^-f Main_Prog^/FORCE_COMPILE MAIN_PROG^
16476 @end smallexample
16478 @noindent
16479 (you will need @code{^-f^/FORCE_COMPILE^} option for gnatmake to
16480 recompile everything
16481 with the set of pragmas @code{Eliminate} you have obtained with
16482 @code{gnatelim}).
16484 Be aware that the set of @code{Eliminate} pragmas is specific to each
16485 program. It is not recommended to merge sets of @code{Eliminate}
16486 pragmas created for different programs in one @file{gnat.adc} file.
16488 @node Summary of the gnatelim Usage Cycle
16489 @section Summary of the gnatelim Usage Cycle
16491 @noindent
16492 Here is a quick summary of the steps to be taken in order to reduce
16493 the size of your executables with @code{gnatelim}. You may use
16494 other GNAT options to control the optimization level,
16495 to produce the debugging information, to set search path, etc.
16497 @enumerate
16498 @item
16499 Produce a bind file and a set of tree files
16501 @smallexample
16502 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
16503 $ gnatbind main_prog
16504 @ifset vms
16505 $ GNAT MAKE /FORCE_COMPILE /NO_LINK /NOLOAD /TREE_OUTPUT MAIN_PROG
16506 @end ifset
16507 @ifclear vms
16508 $ gnatmake -f -c -gnatc -gnatt Main_Prog
16509 @end ifclear
16510 @end smallexample
16512 @item
16513 Generate a list of @code{Eliminate} pragmas
16514 @smallexample
16515 @ifset vms
16516 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
16517 @end ifset
16518 @ifclear vms
16519 $ gnatelim Main_Prog >[>] gnat.adc
16520 @end ifclear
16521 @end smallexample
16523 @item
16524 Recompile the application
16526 @smallexample
16527 $ gnatmake ^-f Main_Prog^/FORCE_COMPILE MAIN_PROG^
16528 @end smallexample
16530 @end enumerate
16532 @node Other Utility Programs
16533 @chapter Other Utility Programs
16535 @noindent
16536 This chapter discusses some other utility programs available in the Ada
16537 environment.
16539 @menu
16540 * Using Other Utility Programs with GNAT::
16541 * The gnatpsta Utility Program::
16542 * The External Symbol Naming Scheme of GNAT::
16543 * Ada Mode for Glide::
16544 * Converting Ada Files to html with gnathtml::
16545 * Installing gnathtml::
16546 @ifset vms
16547 * LSE::
16548 * Profiling::
16549 @end ifset
16550 @end menu
16552 @node Using Other Utility Programs with GNAT
16553 @section Using Other Utility Programs with GNAT
16555 @noindent
16556 The object files generated by GNAT are in standard system format and in
16557 particular the debugging information uses this format. This means
16558 programs generated by GNAT can be used with existing utilities that
16559 depend on these formats.
16561 @ifclear vms
16562 In general, any utility program that works with C will also often work with
16563 Ada programs generated by GNAT. This includes software utilities such as
16564 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
16565 as Purify.
16566 @end ifclear
16568 @node The gnatpsta Utility Program
16569 @section The @code{gnatpsta} Utility Program
16571 @noindent
16572 Many of the definitions in package Standard are implementation-dependent.
16573 However, the source of this package does not exist as an Ada source
16574 file, so these values cannot be determined by inspecting the source.
16575 They can be determined by examining in detail the coding of
16576 @file{cstand.adb} which creates the image of Standard in the compiler,
16577 but this is awkward and requires a great deal of internal knowledge
16578 about the system.
16580 The @code{gnatpsta} utility is designed to deal with this situation.
16581 It is an Ada program that dynamically determines the
16582 values of all the relevant parameters in Standard, and prints them
16583 out in the form of an Ada source listing for Standard, displaying all
16584 the values of interest. This output is generated to
16585 @file{stdout}.
16587 To determine the value of any parameter in package Standard, simply
16588 run @code{gnatpsta} with no qualifiers or arguments, and examine
16589 the output. This is preferable to consulting documentation, because
16590 you know that the values you are getting are the actual ones provided
16591 by the executing system.
16593 @node The External Symbol Naming Scheme of GNAT
16594 @section The External Symbol Naming Scheme of GNAT
16596 @noindent
16597 In order to interpret the output from GNAT, when using tools that are
16598 originally intended for use with other languages, it is useful to
16599 understand the conventions used to generate link names from the Ada
16600 entity names.
16602 All link names are in all lowercase letters. With the exception of library
16603 procedure names, the mechanism used is simply to use the full expanded
16604 Ada name with dots replaced by double underscores. For example, suppose
16605 we have the following package spec:
16607 @smallexample
16608 @group
16609 @cartouche
16610 @b{package} QRS @b{is}
16611    MN : Integer;
16612 @b{end} QRS;
16613 @end cartouche
16614 @end group
16615 @end smallexample
16617 @noindent
16618 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
16619 the corresponding link name is @code{qrs__mn}.
16620 @findex Export
16621 Of course if a @code{pragma Export} is used this may be overridden:
16623 @smallexample
16624 @group
16625 @cartouche
16626 @b{package} Exports @b{is}
16627    Var1 : Integer;
16628    @b{pragma} Export (Var1, C, External_Name => "var1_name");
16629    Var2 : Integer;
16630    @b{pragma} Export (Var2, C, Link_Name => "var2_link_name");
16631 @b{end} Exports;
16632 @end cartouche
16633 @end group
16634 @end smallexample
16636 @noindent
16637 In this case, the link name for @var{Var1} is whatever link name the
16638 C compiler would assign for the C function @var{var1_name}. This typically
16639 would be either @var{var1_name} or @var{_var1_name}, depending on operating
16640 system conventions, but other possibilities exist. The link name for
16641 @var{Var2} is @var{var2_link_name}, and this is not operating system
16642 dependent.
16644 @findex _main
16645 One exception occurs for library level procedures. A potential ambiguity
16646 arises between the required name @code{_main} for the C main program,
16647 and the name we would otherwise assign to an Ada library level procedure
16648 called @code{Main} (which might well not be the main program).
16650 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
16651 names. So if we have a library level procedure such as
16653 @smallexample
16654 @group
16655 @cartouche
16656 @b{procedure} Hello (S : String);
16657 @end cartouche
16658 @end group
16659 @end smallexample
16661 @noindent
16662 the external name of this procedure will be @var{_ada_hello}.
16664 @node Ada Mode for Glide
16665 @section Ada Mode for @code{Glide}
16667 @noindent
16668 The Glide mode for programming in Ada (both, Ada83 and Ada95) helps the
16669 user in understanding existing code and facilitates writing new code. It
16670 furthermore provides some utility functions for easier integration of
16671 standard Emacs features when programming in Ada.
16673 @subsection General Features:
16675 @itemize @bullet
16676 @item
16677 Full Integrated Development Environment :
16679 @itemize @bullet
16680 @item
16681 support of 'project files' for the configuration (directories,
16682 compilation options,...)
16684 @item
16685 compiling and stepping through error messages.
16687 @item
16688 running and debugging your applications within Glide.
16689 @end itemize
16691 @item
16692 easy to use for beginners by pull-down menus,
16694 @item
16695 user configurable by many user-option variables.
16696 @end itemize
16698 @subsection Ada Mode Features That Help Understanding Code:
16700 @itemize @bullet
16701 @item
16702 functions for easy and quick stepping through Ada code,
16704 @item
16705 getting cross reference information for identifiers (e.g. find the
16706 defining place by a keystroke),
16708 @item
16709 displaying an index menu of types and subprograms and move point to
16710 the chosen one,
16712 @item
16713 automatic color highlighting of the various entities in Ada code.
16714 @end itemize
16716 @subsection Glide Support for Writing Ada Code:
16718 @itemize @bullet
16719 @item
16720 switching between spec and body files with possible
16721 autogeneration of body files,
16723 @item
16724 automatic formating of subprograms parameter lists.
16726 @item
16727 automatic smart indentation according to Ada syntax,
16729 @item
16730 automatic completion of identifiers,
16732 @item
16733 automatic casing of identifiers, keywords, and attributes,
16735 @item
16736 insertion of statement templates,
16738 @item
16739 filling comment paragraphs like filling normal text,
16740 @end itemize
16742 For more information, please refer to the online Glide documentation
16743 available in the Glide --> Help Menu.
16745 @node Converting Ada Files to html with gnathtml
16746 @section Converting Ada Files to html with @code{gnathtml}
16748 @noindent
16749 This @code{Perl} script allows Ada source files to be browsed using
16750 standard Web browsers. For installation procedure, see the section
16751 @xref{Installing gnathtml}.
16753 Ada reserved keywords are highlighted in a bold font and Ada comments in
16754 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
16755 switch to suppress the generation of cross-referencing information, user
16756 defined variables and types will appear in a different color; you will
16757 be able to click on any identifier and go to its declaration.
16759 The command line is as follow:
16760 @smallexample
16761 $ perl gnathtml.pl [switches] ada-files
16762 @end smallexample
16764 You can pass it as many Ada files as you want. @code{gnathtml} will generate
16765 an html file for every ada file, and a global file called @file{index.htm}.
16766 This file is an index of every identifier defined in the files.
16768 The available switches are the following ones :
16770 @table @code
16771 @item -83
16772 @cindex @code{-83} (@code{gnathtml})
16773 Only the subset on the Ada 83 keywords will be highlighted, not the full
16774 Ada 95 keywords set.
16776 @item -cc @var{color}
16777 This option allows you to change the color used for comments. The default
16778 value is green. The color argument can be any name accepted by html.
16780 @item -d
16781 @cindex @code{-d} (@code{gnathtml})
16782 If the ada files depend on some other files (using for instance the
16783 @code{with} command, the latter will also be converted to html.
16784 Only the files in the user project will be converted to html, not the files
16785 in the run-time library itself.
16787 @item -D
16788 This command is the same as -d above, but @code{gnathtml} will also look
16789 for files in the run-time library, and generate html files for them.
16791 @item -f
16792 @cindex @code{-f} (@code{gnathtml})
16793 By default, gnathtml will generate html links only for global entities
16794 ('with'ed units, global variables and types,...). If you specify the
16795 @code{-f} on the command line, then links will be generated for local
16796 entities too.
16798 @item -l @var{number}
16799 @cindex @code{-l} (@code{gnathtml})
16800 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
16801 will number the html files every @var{number} line.
16803 @item -I @var{dir}
16804 @cindex @code{-I} (@code{gnathtml})
16805 Specify a directory to search for library files (@file{.ali} files) and
16806 source files. You can provide several -I switches on the command line,
16807 and the directories will be parsed in the order of the command line.
16809 @item -o @var{dir}
16810 @cindex @code{-o} (@code{gnathtml})
16811 Specify the output directory for html files. By default, gnathtml will
16812 saved the generated html files in a subdirectory named @file{html/}.
16814 @item -p @var{file}
16815 @cindex @code{-p} (@code{gnathtml})
16816 If you are using Emacs and the most recent Emacs Ada mode, which provides
16817 a full Integrated Development Environment for compiling, checking,
16818 running and debugging applications, you may be using @file{.adp} files
16819 to give the directories where Emacs can find sources and object files.
16821 Using this switch, you can tell gnathtml to use these files. This allows
16822 you to get an html version of your application, even if it is spread
16823 over multiple directories.
16825 @item -sc @var{color}
16826 @cindex @code{-sc} (@code{gnathtml})
16827 This option allows you to change the color used for symbol definitions.
16828 The default value is red. The color argument can be any name accepted by html.
16830 @item -t @var{file}
16831 @cindex @code{-t} (@code{gnathtml})
16832 This switch provides the name of a file. This file contains a list of
16833 file names to be converted, and the effect is exactly as though they had
16834 appeared explicitly on the command line. This
16835 is the recommended way to work around the command line length limit on some
16836 systems.
16838 @end table
16840 @node Installing gnathtml
16841 @section Installing @code{gnathtml}
16843 @noindent
16844 @code{Perl} needs to be installed on your machine to run this script.
16845 @code{Perl} is freely available for almost every architecture and
16846 Operating System via the Internet.
16848 On Unix systems, you  may want to modify  the  first line of  the script
16849 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
16850 is. The syntax of this line is :
16851 @smallexample
16852 #!full_path_name_to_perl
16853 @end smallexample
16855 @noindent
16856 Alternatively, you may run the script using the following command line:
16858 @smallexample
16859 $ perl gnathtml.pl [switches] files
16860 @end smallexample
16862 @ifset vms
16863 @node LSE
16864 @section LSE
16865 @findex LSE
16867 @noindent
16868 The GNAT distribution provides an Ada 95 template for the Digital Language
16869 Sensitive Editor (LSE), a component of DECset. In order to
16870 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
16872 @node Profiling
16873 @section Profiling
16874 @findex PCA
16876 @noindent
16877 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
16878 of DECset. To use it proceed as outlined under "HELP PCA", except for running
16879 the collection phase with the /DEBUG qualifier.
16881 @smallexample
16882 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
16883 $ DEFINE LIB$DEBUG PCA$COLLECTOR
16884 $ RUN/DEBUG <PROGRAM_NAME>
16885 @end smallexample
16886 @noindent
16887 @end ifset
16889 @node Running and Debugging Ada Programs
16890 @chapter Running and Debugging Ada Programs
16891 @cindex Debugging
16893 @noindent
16894 This chapter discusses how to debug Ada programs. An incorrect Ada program
16895 may be handled in three ways by the GNAT compiler:
16897 @enumerate
16898 @item
16899 The illegality may be a violation of the static semantics of Ada. In
16900 that case GNAT diagnoses the constructs in the program that are illegal.
16901 It is then a straightforward matter for the user to modify those parts of
16902 the program.
16904 @item
16905 The illegality may be a violation of the dynamic semantics of Ada. In
16906 that case the program compiles and executes, but may generate incorrect
16907 results, or may terminate abnormally with some exception.
16909 @item
16910 When presented with a program that contains convoluted errors, GNAT
16911 itself may terminate abnormally without providing full diagnostics on
16912 the incorrect user program.
16913 @end enumerate
16915 @menu
16916 * The GNAT Debugger GDB::
16917 * Running GDB::
16918 * Introduction to GDB Commands::
16919 * Using Ada Expressions::
16920 * Calling User-Defined Subprograms::
16921 * Using the Next Command in a Function::
16922 * Ada Exceptions::
16923 * Ada Tasks::
16924 * Debugging Generic Units::
16925 * GNAT Abnormal Termination or Failure to Terminate::
16926 * Naming Conventions for GNAT Source Files::
16927 * Getting Internal Debugging Information::
16928 * Stack Traceback::
16929 @end menu
16931 @cindex Debugger
16932 @findex gdb
16934 @node The GNAT Debugger GDB
16935 @section The GNAT Debugger GDB
16937 @noindent
16938 @code{GDB} is a general purpose, platform-independent debugger that
16939 can be used to debug mixed-language programs compiled with @code{GCC},
16940 and in particular is capable of debugging Ada programs compiled with
16941 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
16942 complex Ada data structures.
16944 The manual @cite{Debugging with GDB}
16945 @ifset vms
16946 , located in the GNU:[DOCS] directory,
16947 @end ifset
16948 contains full details on the usage of @code{GDB}, including a section on
16949 its usage on programs. This manual should be consulted for full
16950 details. The section that follows is a brief introduction to the
16951 philosophy and use of @code{GDB}.
16953 When GNAT programs are compiled, the compiler optionally writes debugging
16954 information into the generated object file, including information on
16955 line numbers, and on declared types and variables. This information is
16956 separate from the generated code. It makes the object files considerably
16957 larger, but it does not add to the size of the actual executable that
16958 will be loaded into memory, and has no impact on run-time performance. The
16959 generation of debug information is triggered by the use of the
16960 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
16961 the compilations. It is important to emphasize that the use of these
16962 options does not change the generated code.
16964 The debugging information is written in standard system formats that
16965 are used by many tools, including debuggers and profilers. The format
16966 of the information is typically designed to describe C types and
16967 semantics, but GNAT implements a translation scheme which allows full
16968 details about Ada types and variables to be encoded into these
16969 standard C formats. Details of this encoding scheme may be found in
16970 the file exp_dbug.ads in the GNAT source distribution. However, the
16971 details of this encoding are, in general, of no interest to a user,
16972 since @code{GDB} automatically performs the necessary decoding.
16974 When a program is bound and linked, the debugging information is
16975 collected from the object files, and stored in the executable image of
16976 the program. Again, this process significantly increases the size of
16977 the generated executable file, but it does not increase the size of
16978 the executable program itself. Furthermore, if this program is run in
16979 the normal manner, it runs exactly as if the debug information were
16980 not present, and takes no more actual memory.
16982 However, if the program is run under control of @code{GDB}, the
16983 debugger is activated.  The image of the program is loaded, at which
16984 point it is ready to run.  If a run command is given, then the program
16985 will run exactly as it would have if @code{GDB} were not present. This
16986 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
16987 entirely non-intrusive until a breakpoint is encountered.  If no
16988 breakpoint is ever hit, the program will run exactly as it would if no
16989 debugger were present. When a breakpoint is hit, @code{GDB} accesses
16990 the debugging information and can respond to user commands to inspect
16991 variables, and more generally to report on the state of execution.
16993 @node Running GDB
16994 @section Running GDB
16996 @ifclear vxworks
16997 @noindent
16998 The debugger can be launched directly and simply from @code{glide} or
16999 through its graphical interface: @code{gvd}. It can also be used
17000 directly in text mode. Here is described the basic use of @code{GDB}
17001 in text mode. All the commands described below can be used in the
17002 @code{gvd} console window eventhough there is usually other more
17003 graphical ways to achieve the same goals.
17005 @ifclear vms
17006 @noindent
17007 The command to run de graphical interface of the debugger is
17008 @smallexample
17009 $ gvd program
17010 @end smallexample
17011 @end ifclear
17013 @noindent
17014 The command to run @code{GDB} in text mode is
17016 @smallexample
17017 $ ^gdb program^$ GDB PROGRAM^
17018 @end smallexample
17020 @noindent
17021 where @code{^program^PROGRAM^} is the name of the executable file. This
17022 activates the debugger and results in a prompt for debugger commands.
17023 The simplest command is simply @code{run}, which causes the program to run
17024 exactly as if the debugger were not present. The following section
17025 describes some of the additional commands that can be given to @code{GDB}.
17026 @end ifclear
17028 @ifset vxworks
17029 Please refer to the debugging section of the chapter specific to your
17030 cross environment at the end of this manual.
17031 @end ifset
17033 @node Introduction to GDB Commands
17034 @section Introduction to GDB Commands
17036 @noindent
17037 @code{GDB} contains a large repertoire of commands. The manual
17038 @cite{Debugging with GDB}
17039 @ifset vms
17040 , located in the GNU:[DOCS] directory,
17041 @end ifset
17042 includes extensive documentation on the use
17043 of these commands, together with examples of their use. Furthermore,
17044 the command @var{help} invoked from within @code{GDB} activates a simple help
17045 facility which summarizes the available commands and their options.
17046 In this section we summarize a few of the most commonly
17047 used commands to give an idea of what @code{GDB} is about. You should create
17048 a simple program with debugging information and experiment with the use of
17049 these @code{GDB} commands on the program as you read through the
17050 following section.
17052 @table @code
17053 @item set args @var{arguments}
17054 The @var{arguments} list above is a list of arguments to be passed to
17055 the program on a subsequent run command, just as though the arguments
17056 had been entered on a normal invocation of the program. The @code{set args}
17057 command is not needed if the program does not require arguments.
17059 @item run
17060 The @code{run} command causes execution of the program to start from
17061 the beginning. If the program is already running, that is to say if
17062 you are currently positioned at a breakpoint, then a prompt will ask
17063 for confirmation that you want to abandon the current execution and
17064 restart.
17066 @item breakpoint @var{location}
17067 The breakpoint command sets a breakpoint, that is to say a point at which
17068 execution will halt and @code{GDB} will await further
17069 commands. @var{location} is
17070 either a line number within a file, given in the format @code{file:linenumber},
17071 or it is the name of a subprogram. If you request that a breakpoint be set on
17072 a subprogram that is overloaded, a prompt will ask you to specify on which of
17073 those subprograms you want to breakpoint. You can also
17074 specify that all of them should be breakpointed. If the program is run
17075 and execution encounters the breakpoint, then the program
17076 stops and @code{GDB} signals that the breakpoint was encountered by
17077 printing the line of code before which the program is halted.
17079 @item breakpoint exception @var{name}
17080 A special form of the breakpoint command which breakpoints whenever
17081 exception @var{name} is raised.
17082 If @var{name} is omitted,
17083 then a breakpoint will occur when any exception is raised.
17085 @item print @var{expression}
17086 This will print the value of the given expression. Most simple
17087 Ada expression formats are properly handled by @code{GDB}, so the expression
17088 can contain function calls, variables, operators, and attribute references.
17090 @item continue
17091 Continues execution following a breakpoint, until the next breakpoint or the
17092 termination of the program.
17094 @item step
17095 Executes a single line after a breakpoint. If the next statement is a subprogram
17096 call, execution continues into (the first statement of) the
17097 called subprogram.
17099 @item next
17100 Executes a single line. If this line is a subprogram call, executes and
17101 returns from the call.
17103 @item list
17104 Lists a few lines around the current source location. In practice, it
17105 is usually more convenient to have a separate edit window open with the
17106 relevant source file displayed. Successive applications of this command
17107 print subsequent lines. The command can be given an argument which is a
17108 line number, in which case it displays a few lines around the specified one.
17110 @item backtrace
17111 Displays a backtrace of the call chain. This command is typically
17112 used after a breakpoint has occurred, to examine the sequence of calls that
17113 leads to the current breakpoint. The display includes one line for each
17114 activation record (frame) corresponding to an active subprogram.
17116 @item up
17117 At a breakpoint, @code{GDB} can display the values of variables local
17118 to the current frame. The command @code{up} can be used to
17119 examine the contents of other active frames, by moving the focus up
17120 the stack, that is to say from callee to caller, one frame at a time.
17122 @item down
17123 Moves the focus of @code{GDB} down from the frame currently being
17124 examined to the frame of its callee (the reverse of the previous command),
17126 @item frame @var{n}
17127 Inspect the frame with the given number. The value 0 denotes the frame
17128 of the current breakpoint, that is to say the top of the call stack.
17130 @end table
17132 The above list is a very short introduction to the commands that
17133 @code{GDB} provides. Important additional capabilities, including conditional
17134 breakpoints, the ability to execute command sequences on a breakpoint,
17135 the ability to debug at the machine instruction level and many other
17136 features are described in detail in @cite{Debugging with GDB}.
17137 Note that most commands can be abbreviated
17138 (for example, c for continue, bt for backtrace).
17140 @node Using Ada Expressions
17141 @section Using Ada Expressions
17142 @cindex Ada expressions
17144 @noindent
17145 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
17146 extensions. The philosophy behind the design of this subset is
17148 @itemize @bullet
17149 @item
17150 That @code{GDB} should provide basic literals and access to operations for
17151 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
17152 leaving more sophisticated computations to subprograms written into the
17153 program (which therefore may be called from @code{GDB}).
17155 @item
17156 That type safety and strict adherence to Ada language restrictions
17157 are not particularly important to the @code{GDB} user.
17159 @item
17160 That brevity is important to the @code{GDB} user.
17161 @end itemize
17163 Thus, for brevity, the debugger acts as if there were
17164 implicit @code{with} and @code{use} clauses in effect for all user-written
17165 packages, thus making it unnecessary to fully qualify most names with
17166 their packages, regardless of context. Where this causes ambiguity,
17167 @code{GDB} asks the user's intent.
17169 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
17171 @node Calling User-Defined Subprograms
17172 @section Calling User-Defined Subprograms
17174 @noindent
17175 An important capability of @code{GDB} is the ability to call user-defined
17176 subprograms while debugging. This is achieved simply by entering
17177 a subprogram call statement in the form:
17179 @smallexample
17180 call subprogram-name (parameters)
17181 @end smallexample
17183 @noindent
17184 The keyword @code{call} can be omitted in the normal case where the
17185 @code{subprogram-name} does not coincide with any of the predefined
17186 @code{GDB} commands.
17188 The effect is to invoke the given subprogram, passing it the
17189 list of parameters that is supplied. The parameters can be expressions and
17190 can include variables from the program being debugged. The
17191 subprogram must be defined
17192 at the library level within your program, and @code{GDB} will call the
17193 subprogram within the environment of your program execution (which
17194 means that the subprogram is free to access or even modify variables
17195 within your program).
17197 The most important use of this facility is in allowing the inclusion of
17198 debugging routines that are tailored to particular data structures
17199 in your program. Such debugging routines can be written to provide a suitably
17200 high-level description of an abstract type, rather than a low-level dump
17201 of its physical layout. After all, the standard
17202 @code{GDB print} command only knows the physical layout of your
17203 types, not their abstract meaning. Debugging routines can provide information
17204 at the desired semantic level and are thus enormously useful.
17206 For example, when debugging GNAT itself, it is crucial to have access to
17207 the contents of the tree nodes used to represent the program internally.
17208 But tree nodes are represented simply by an integer value (which in turn
17209 is an index into a table of nodes).
17210 Using the @code{print} command on a tree node would simply print this integer
17211 value, which is not very useful. But the PN routine (defined in file
17212 treepr.adb in the GNAT sources) takes a tree node as input, and displays
17213 a useful high level representation of the tree node, which includes the
17214 syntactic category of the node, its position in the source, the integers
17215 that denote descendant nodes and parent node, as well as varied
17216 semantic information. To study this example in more detail, you might want to
17217 look at the body of the PN procedure in the stated file.
17219 @node Using the Next Command in a Function
17220 @section Using the Next Command in a Function
17222 @noindent
17223 When you use the @code{next} command in a function, the current source
17224 location will advance to the next statement as usual. A special case
17225 arises in the case of a @code{return} statement.
17227 Part of the code for a return statement is the "epilog" of the function.
17228 This is the code that returns to the caller. There is only one copy of
17229 this epilog code, and it is typically associated with the last return
17230 statement in the function if there is more than one return. In some
17231 implementations, this epilog is associated with the first statement
17232 of the function.
17234 The result is that if you use the @code{next} command from a return
17235 statement that is not the last return statement of the function you
17236 may see a strange apparent jump to the last return statement or to
17237 the start of the function. You should simply ignore this odd jump.
17238 The value returned is always that from the first return statement
17239 that was stepped through.
17241 @node Ada Exceptions
17242 @section Breaking on Ada Exceptions
17243 @cindex Exceptions
17245 @noindent
17246 You can set breakpoints that trip when your program raises
17247 selected exceptions.
17249 @table @code
17250 @item break exception
17251 Set a breakpoint that trips whenever (any task in the) program raises
17252 any exception.
17254 @item break exception @var{name}
17255 Set a breakpoint that trips whenever (any task in the) program raises
17256 the exception @var{name}.
17258 @item break exception unhandled
17259 Set a breakpoint that trips whenever (any task in the) program raises an
17260 exception for which there is no handler.
17262 @item info exceptions
17263 @itemx info exceptions @var{regexp}
17264 The @code{info exceptions} command permits the user to examine all defined
17265 exceptions within Ada programs. With a regular expression, @var{regexp}, as
17266 argument, prints out only those exceptions whose name matches @var{regexp}.
17267 @end table
17269 @node Ada Tasks
17270 @section Ada Tasks
17271 @cindex Tasks
17273 @noindent
17274 @code{GDB} allows the following task-related commands:
17276 @table @code
17277 @item info tasks
17278 This command shows a list of current Ada tasks, as in the following example:
17280 @smallexample
17281 @iftex
17282 @leftskip=0cm
17283 @end iftex
17284 (gdb) info tasks
17285   ID       TID P-ID   Thread Pri State                 Name
17286    1   8088000   0   807e000  15 Child Activation Wait main_task
17287    2   80a4000   1   80ae000  15 Accept/Select Wait    b
17288    3   809a800   1   80a4800  15 Child Activation Wait a
17289 *  4   80ae800   3   80b8000  15 Running               c
17290 @end smallexample
17292 @noindent
17293 In this listing, the asterisk before the first task indicates it to be the
17294 currently running task. The first column lists the task ID that is used
17295 to refer to tasks in the following commands.
17297 @item break @var{linespec} task @var{taskid}
17298 @itemx break @var{linespec} task @var{taskid} if @dots{}
17299 @cindex Breakpoints and tasks
17300 These commands are like the @code{break @dots{} thread @dots{}}.
17301 @var{linespec} specifies source lines.
17303 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
17304 to specify that you only want @code{GDB} to stop the program when a
17305 particular Ada task reaches this breakpoint. @var{taskid} is one of the
17306 numeric task identifiers assigned by @code{GDB}, shown in the first
17307 column of the @samp{info tasks} display.
17309 If you do not specify @samp{task @var{taskid}} when you set a
17310 breakpoint, the breakpoint applies to @emph{all} tasks of your
17311 program.
17313 You can use the @code{task} qualifier on conditional breakpoints as
17314 well; in this case, place @samp{task @var{taskid}} before the
17315 breakpoint condition (before the @code{if}).
17317 @item task @var{taskno}
17318 @cindex Task switching
17320 This command allows to switch to the task referred by @var{taskno}. In
17321 particular, This allows to browse the backtrace of the specified
17322 task. It is advised to switch back to the original task before
17323 continuing execution otherwise the scheduling of the program may be
17324 perturbated.
17325 @end table
17327 @noindent
17328 For more detailed information on the tasking support, see @cite{Debugging with GDB}.
17330 @node Debugging Generic Units
17331 @section Debugging Generic Units
17332 @cindex Debugging Generic Units
17333 @cindex Generics
17335 @noindent
17336 GNAT always uses code expansion for generic instantiation. This means that
17337 each time an instantiation occurs, a complete copy of the original code is
17338 made, with appropriate substitutions of formals by actuals.
17340 It is not possible to refer to the original generic entities in
17341 @code{GDB}, but it is always possible to debug a particular instance of
17342 a generic, by using the appropriate expanded names. For example, if we have
17344 @smallexample
17345 @group
17346 @cartouche
17347 @b{procedure} g @b{is}
17349    @b{generic package} k @b{is}
17350       @b{procedure} kp (v1 : @b{in out} integer);
17351    @b{end} k;
17353    @b{package body} k @b{is}
17354       @b{procedure} kp (v1 : @b{in out} integer) @b{is}
17355       @b{begin}
17356          v1 := v1 + 1;
17357       @b{end} kp;
17358    @b{end} k;
17360    @b{package} k1 @b{is new} k;
17361    @b{package} k2 @b{is new} k;
17363    var : integer := 1;
17365 @b{begin}
17366    k1.kp (var);
17367    k2.kp (var);
17368    k1.kp (var);
17369    k2.kp (var);
17370 @b{end};
17371 @end cartouche
17372 @end group
17373 @end smallexample
17375 @noindent
17376 Then to break on a call to procedure kp in the k2 instance, simply
17377 use the command:
17379 @smallexample
17380 (gdb) break g.k2.kp
17381 @end smallexample
17383 @noindent
17384 When the breakpoint occurs, you can step through the code of the
17385 instance in the normal manner and examine the values of local variables, as for
17386 other units.
17388 @node GNAT Abnormal Termination or Failure to Terminate
17389 @section GNAT Abnormal Termination or Failure to Terminate
17390 @cindex GNAT Abnormal Termination or Failure to Terminate
17392 @noindent
17393 When presented with programs that contain serious errors in syntax
17394 or semantics,
17395 GNAT may on rare occasions  experience problems in operation, such
17396 as aborting with a
17397 segmentation fault or illegal memory access, raising an internal
17398 exception, terminating abnormally, or failing to terminate at all.
17399 In such cases, you can activate
17400 various features of GNAT that can help you pinpoint the construct in your
17401 program that is the likely source of the problem.
17403 The following strategies are presented in increasing order of
17404 difficulty, corresponding to your experience in using GNAT and your
17405 familiarity with compiler internals.
17407 @enumerate
17408 @item
17409 Run @code{gcc} with the @option{-gnatf}. This first
17410 switch causes all errors on a given line to be reported. In its absence,
17411 only the first error on a line is displayed.
17413 The @option{-gnatdO} switch causes errors to be displayed as soon as they
17414 are encountered, rather than after compilation is terminated. If GNAT
17415 terminates prematurely or goes into an infinite loop, the last error
17416 message displayed may help to pinpoint the culprit.
17418 @item
17419 Run @code{gcc} with the @code{^-v (verbose)^/VERBOSE^} switch. In this mode,
17420 @code{gcc} produces ongoing information about the progress of the
17421 compilation and provides the name of each procedure as code is
17422 generated. This switch allows you to find which Ada procedure was being
17423 compiled when it encountered a code generation problem.
17425 @item
17426 @cindex @option{-gnatdc} switch
17427 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
17428 switch that does for the front-end what @code{^-v^VERBOSE^} does for the back end.
17429 The system prints the name of each unit, either a compilation unit or
17430 nested unit, as it is being analyzed.
17431 @item
17432 Finally, you can start
17433 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
17434 front-end of GNAT, and can be run independently (normally it is just
17435 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
17436 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
17437 @code{where} command is the first line of attack; the variable
17438 @code{lineno} (seen by @code{print lineno}), used by the second phase of
17439 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
17440 which the execution stopped, and @code{input_file name} indicates the name of
17441 the source file.
17442 @end enumerate
17444 @node Naming Conventions for GNAT Source Files
17445 @section Naming Conventions for GNAT Source Files
17447 @noindent
17448 In order to examine the workings of the GNAT system, the following
17449 brief description of its organization may be helpful:
17451 @itemize @bullet
17452 @item
17453 Files with prefix @file{^sc^SC^} contain the lexical scanner.
17455 @item
17456 All files prefixed with @file{^par^PAR^} are components of the parser. The
17457 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
17458 parsing of select statements can be found in @file{par-ch9.adb}.
17460 @item
17461 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
17462 numbers correspond to chapters of the Ada standard. For example, all
17463 issues involving context clauses can be found in @file{sem_ch10.adb}. In
17464 addition, some features of the language require sufficient special processing
17465 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
17466 dynamic dispatching, etc.
17468 @item
17469 All files prefixed with @file{^exp^EXP^} perform normalization and
17470 expansion of the intermediate representation (abstract syntax tree, or AST).
17471 these files use the same numbering scheme as the parser and semantics files.
17472 For example, the construction of record initialization procedures is done in
17473 @file{exp_ch3.adb}.
17475 @item
17476 The files prefixed with @file{^bind^BIND^} implement the binder, which
17477 verifies the consistency of the compilation, determines an order of
17478 elaboration, and generates the bind file.
17480 @item
17481 The files @file{atree.ads} and @file{atree.adb} detail the low-level
17482 data structures used by the front-end.
17484 @item
17485 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
17486 the abstract syntax tree as produced by the parser.
17488 @item
17489 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
17490 all entities, computed during semantic analysis.
17492 @item
17493 Library management issues are dealt with in files with prefix
17494 @file{^lib^LIB^}.
17496 @item
17497 @findex Ada
17498 @cindex Annex A
17499 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
17500 defined in Annex A.
17502 @item
17503 @findex Interfaces
17504 @cindex Annex B
17505 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
17506 defined in Annex B.
17508 @item
17509 @findex System
17510 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
17511 both language-defined children and GNAT run-time routines.
17513 @item
17514 @findex GNAT
17515 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
17516 general-purpose packages, fully documented in their specifications. All
17517 the other @file{.c} files are modifications of common @code{gcc} files.
17518 @end itemize
17520 @node Getting Internal Debugging Information
17521 @section Getting Internal Debugging Information
17523 @noindent
17524 Most compilers have internal debugging switches and modes. GNAT
17525 does also, except GNAT internal debugging switches and modes are not
17526 secret. A summary and full description of all the compiler and binder
17527 debug flags are in the file @file{debug.adb}. You must obtain the
17528 sources of the compiler to see the full detailed effects of these flags.
17530 The switches that print the source of the program (reconstructed from
17531 the internal tree) are of general interest for user programs, as are the
17532 options to print
17533 the full internal tree, and the entity table (the symbol table
17534 information). The reconstructed source provides a readable version of the
17535 program after the front-end has completed analysis and  expansion, and is useful
17536 when studying the performance of specific constructs. For example, constraint
17537 checks are indicated, complex aggregates are replaced with loops and
17538 assignments, and tasking primitives are replaced with run-time calls.
17540 @node Stack Traceback
17541 @section Stack Traceback
17542 @cindex traceback
17543 @cindex stack traceback
17544 @cindex stack unwinding
17546 @noindent
17547 Traceback is a mechanism to display the sequence of subprogram calls that
17548 leads to a specified execution point in a program. Often (but not always)
17549 the execution point is an instruction at which an exception has been raised.
17550 This mechanism is also known as @i{stack unwinding} because it obtains
17551 its information by scanning the run-time stack and recovering the activation
17552 records of all active subprograms. Stack unwinding is one of the most
17553 important tools for program debugging.
17555 @noindent
17556 The first entry stored in traceback corresponds to the deepest calling level,
17557 that is to say the subprogram currently executing the instruction
17558 from which we want to obtain the traceback.
17560 @noindent
17561 Note that there is no runtime performance penalty when stack traceback
17562 is enabled and no exception are raised during program execution.
17564 @menu
17565 * Non-Symbolic Traceback::
17566 * Symbolic Traceback::
17567 @end menu
17569 @node Non-Symbolic Traceback
17570 @subsection Non-Symbolic Traceback
17571 @cindex traceback, non-symbolic
17573 @noindent
17574 Note: this feature is not supported on all platforms. See
17575 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
17576 platforms.
17578 @menu
17579 * Tracebacks From an Unhandled Exception::
17580 * Tracebacks From Exception Occurrences (non-symbolic)::
17581 * Tracebacks From Anywhere in a Program (non-symbolic)::
17582 @end menu
17584 @node Tracebacks From an Unhandled Exception
17585 @subsubsection Tracebacks From an Unhandled Exception
17587 @noindent
17588 A runtime non-symbolic traceback is a list of addresses of call instructions.
17589 To enable this feature you must use the @code{-E}
17590 @code{gnatbind}'s option. With this option a stack traceback is stored as part
17591 of exception information. It is possible to retrieve this information using the
17592 standard @code{Ada.Exception.Exception_Information} routine.
17594 @noindent
17595 Let's have a look at a simple example:
17597 @smallexample
17598 @cartouche
17599 @group
17600 procedure STB is
17602    procedure P1 is
17603    begin
17604       raise Constraint_Error;
17605    end P1;
17607    procedure P2 is
17608    begin
17609       P1;
17610    end P2;
17612 begin
17613    P2;
17614 end STB;
17615 @end group
17616 @end cartouche
17617 @end smallexample
17619 @smallexample
17620 $ gnatmake stb -bargs -E
17621 $ stb
17623 Execution terminated by unhandled exception
17624 Exception name: CONSTRAINT_ERROR
17625 Message: stb.adb:5
17626 Call stack traceback locations:
17627 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
17628 @end smallexample
17630 @noindent
17631 As we see the traceback lists a sequence of addresses for the unhandled
17632 exception @code{CONSTAINT_ERROR} raised in procedure P1. It is easy to
17633 guess that this exception come from procedure P1. To translate these
17634 addresses into the source lines where the calls appear, the
17635 @code{addr2line} tool, described below, is invaluable. The use of this tool
17636 requires the program to be compiled with debug information.
17638 @smallexample
17639 $ gnatmake -g stb -bargs -E
17640 $ stb
17642 Execution terminated by unhandled exception
17643 Exception name: CONSTRAINT_ERROR
17644 Message: stb.adb:5
17645 Call stack traceback locations:
17646 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
17648 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
17649    0x4011f1 0x77e892a4
17651 00401373 at d:/stb/stb.adb:5
17652 0040138B at d:/stb/stb.adb:10
17653 0040139C at d:/stb/stb.adb:14
17654 00401335 at d:/stb/b~stb.adb:104
17655 004011C4 at /build/.../crt1.c:200
17656 004011F1 at /build/.../crt1.c:222
17657 77E892A4 in ?? at ??:0
17658 @end smallexample
17660 @noindent
17661 @code{addr2line} has a number of other useful options:
17663 @table @code
17664 @item --functions
17665 to get the function name corresponding to any location
17667 @item --demangle=gnat
17668 to use the @b{gnat} decoding mode for the function names. Note that
17669 for binutils version 2.9.x the option is simply @code{--demangle}.
17670 @end table
17672 @smallexample
17673 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
17674    0x40139c 0x401335 0x4011c4 0x4011f1
17676 00401373 in stb.p1 at d:/stb/stb.adb:5
17677 0040138B in stb.p2 at d:/stb/stb.adb:10
17678 0040139C in stb at d:/stb/stb.adb:14
17679 00401335 in main at d:/stb/b~stb.adb:104
17680 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
17681 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
17682 @end smallexample
17684 @noindent
17685 From this traceback we can see that the exception was raised in
17686 @file{stb.adb} at line 5, which was reached from a procedure call in
17687 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
17688 which contains the call to the main program.
17689 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
17690 and the output will vary from platform to platform.
17692 @noindent
17693 It is also possible to use @code{GDB} with these traceback addresses to debug
17694 the program. For example, we can break at a given code location, as reported
17695 in the stack traceback:
17697 @smallexample
17698 $ gdb -nw stb
17699 @ifset wnt
17700 @noindent
17701 Furthermore, this feature is not implemented inside Windows DLL. Only
17702 the non-symbolic traceback is reported in this case.
17703 @end ifset
17705 (gdb) break *0x401373
17706 Breakpoint 1 at 0x401373: file stb.adb, line 5.
17707 @end smallexample
17709 @noindent
17710 It is important to note that the stack traceback addresses
17711 do not change when debug information is included. This is particularly useful
17712 because it makes it possible to release software without debug information (to
17713 minimize object size), get a field report that includes a stack traceback
17714 whenever an internal bug occurs, and then be able to retrieve the sequence
17715 of calls with the same program compiled with debug information.
17717 @node Tracebacks From Exception Occurrences (non-symbolic)
17718 @subsubsection Tracebacks From Exception Occurrences
17720 @noindent
17721 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
17722 The stack traceback is attached to the exception information string, and can
17723 be retrieved in an exception handler within the Ada program, by means of the
17724 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
17726 @smallexample
17727 @cartouche
17728 @group
17729 with Ada.Text_IO;
17730 with Ada.Exceptions;
17732 procedure STB is
17734    use Ada;
17735    use Ada.Exceptions;
17737    procedure P1 is
17738       K : Positive := 1;
17739    begin
17740       K := K - 1;
17741    exception
17742       when E : others =>
17743          Text_IO.Put_Line (Exception_Information (E));
17744    end P1;
17746    procedure P2 is
17747    begin
17748       P1;
17749    end P2;
17751 begin
17752    P2;
17753 end STB;
17754 @end group
17755 @end cartouche
17756 @end smallexample
17758 @noindent
17759 This program will output:
17761 @smallexample
17762 $ stb
17764 Exception name: CONSTRAINT_ERROR
17765 Message: stb.adb:12
17766 Call stack traceback locations:
17767 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
17768 @end smallexample
17770 @node Tracebacks From Anywhere in a Program (non-symbolic)
17771 @subsubsection Tracebacks From Anywhere in a Program
17773 @noindent
17774 It is also possible to retrieve a stack traceback from anywhere in a
17775 program. For this you need to
17776 use the @code{GNAT.Traceback} API. This package includes a procedure called
17777 @code{Call_Chain} that computes a complete stack traceback, as well as useful
17778 display procedures described below. It is not necessary to use the
17779 @code{-E gnatbind} option in this case, because the stack traceback mechanism
17780 is invoked explicitly.
17782 @noindent
17783 In the following example we compute a traceback at a specific location in
17784 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
17785 convert addresses to strings:
17787 @smallexample
17788 @cartouche
17789 @group
17790 with Ada.Text_IO;
17791 with GNAT.Traceback;
17792 with GNAT.Debug_Utilities;
17794 procedure STB is
17796    use Ada;
17797    use GNAT;
17798    use GNAT.Traceback;
17800    procedure P1 is
17801       TB  : Tracebacks_Array (1 .. 10);
17802       --  We are asking for a maximum of 10 stack frames.
17803       Len : Natural;
17804       --  Len will receive the actual number of stack frames returned.
17805    begin
17806       Call_Chain (TB, Len);
17808       Text_IO.Put ("In STB.P1 : ");
17810       for K in 1 .. Len loop
17811          Text_IO.Put (Debug_Utilities.Image (TB (K)));
17812          Text_IO.Put (' ');
17813       end loop;
17815       Text_IO.New_Line;
17816    end P1;
17818    procedure P2 is
17819    begin
17820       P1;
17821    end P2;
17823 begin
17824    P2;
17825 end STB;
17826 @end group
17827 @end cartouche
17828 @end smallexample
17830 @smallexample
17831 $ gnatmake stb
17832 $ stb
17834 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
17835 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
17836 @end smallexample
17838 @node Symbolic Traceback
17839 @subsection Symbolic Traceback
17840 @cindex traceback, symbolic
17842 @noindent
17843 A symbolic traceback is a stack traceback in which procedure names are
17844 associated with each code location.
17846 @noindent
17847 Note that this feature is not supported on all platforms. See
17848 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
17849 list of currently supported platforms.
17851 @noindent
17852 Note that the symbolic traceback requires that the program be compiled
17853 with debug information. If it is not compiled with debug information
17854 only the non-symbolic information will be valid.
17856 @menu
17857 * Tracebacks From Exception Occurrences (symbolic)::
17858 * Tracebacks From Anywhere in a Program (symbolic)::
17859 @end menu
17861 @node Tracebacks From Exception Occurrences (symbolic)
17862 @subsubsection Tracebacks From Exception Occurrences
17864 @smallexample
17865 @cartouche
17866 @group
17867 with Ada.Text_IO;
17868 with GNAT.Traceback.Symbolic;
17870 procedure STB is
17872    procedure P1 is
17873    begin
17874       raise Constraint_Error;
17875    end P1;
17877    procedure P2 is
17878    begin
17879       P1;
17880    end P2;
17882    procedure P3 is
17883    begin
17884       P2;
17885    end P3;
17887 begin
17888    P3;
17889 exception
17890    when E : others =>
17891       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
17892 end STB;
17893 @end group
17894 @end cartouche
17895 @end smallexample
17897 @smallexample
17898 $ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl
17899 $ stb
17901 0040149F in stb.p1 at stb.adb:8
17902 004014B7 in stb.p2 at stb.adb:13
17903 004014CF in stb.p3 at stb.adb:18
17904 004015DD in ada.stb at stb.adb:22
17905 00401461 in main at b~stb.adb:168
17906 004011C4 in __mingw_CRTStartup at crt1.c:200
17907 004011F1 in mainCRTStartup at crt1.c:222
17908 77E892A4 in ?? at ??:0
17909 @end smallexample
17911 @noindent
17912 The exact sequence of linker options may vary from platform to platform.
17913 The above @code{-largs} section is for Windows platforms. By contrast,
17914 under Unix there is no need for the @code{-largs} section.
17915 Differences across platforms are due to details of linker implementation.
17917 @node Tracebacks From Anywhere in a Program (symbolic)
17918 @subsubsection Tracebacks From Anywhere in a Program
17920 @noindent
17921 It is possible to get a symbolic stack traceback
17922 from anywhere in a program, just as for non-symbolic tracebacks.
17923 The first step is to obtain a non-symbolic
17924 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
17925 information. Here is an example:
17927 @smallexample
17928 @cartouche
17929 @group
17930 with Ada.Text_IO;
17931 with GNAT.Traceback;
17932 with GNAT.Traceback.Symbolic;
17934 procedure STB is
17936    use Ada;
17937    use GNAT.Traceback;
17938    use GNAT.Traceback.Symbolic;
17940    procedure P1 is
17941       TB  : Tracebacks_Array (1 .. 10);
17942       --  We are asking for a maximum of 10 stack frames.
17943       Len : Natural;
17944       --  Len will receive the actual number of stack frames returned.
17945    begin
17946       Call_Chain (TB, Len);
17947       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
17948    end P1;
17950    procedure P2 is
17951    begin
17952       P1;
17953    end P2;
17955 begin
17956    P2;
17957 end STB;
17958 @end group
17959 @end cartouche
17960 @end smallexample
17962 @ifset vms
17963 @node Compatibility with DEC Ada
17964 @chapter Compatibility with DEC Ada
17965 @cindex Compatibility
17967 @noindent
17968 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
17969 OpenVMS Alpha. GNAT achieves a high level of compatibility
17970 with DEC Ada, and it should generally be straightforward to port code
17971 from the DEC Ada environment to GNAT. However, there are a few language
17972 and implementation differences of which the user must be aware. These
17973 differences are discussed in this section. In
17974 addition, the operating environment and command structure for the
17975 compiler are different, and these differences are also discussed.
17977 Note that this discussion addresses specifically the implementation
17978 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
17979 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems, GNAT
17980 always follows the Alpha implementation.
17982 @menu
17983 * Ada 95 Compatibility::
17984 * Differences in the Definition of Package System::
17985 * Language-Related Features::
17986 * The Package STANDARD::
17987 * The Package SYSTEM::
17988 * Tasking and Task-Related Features::
17989 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
17990 * Pragmas and Pragma-Related Features::
17991 * Library of Predefined Units::
17992 * Bindings::
17993 * Main Program Definition::
17994 * Implementation-Defined Attributes::
17995 * Compiler and Run-Time Interfacing::
17996 * Program Compilation and Library Management::
17997 * Input-Output::
17998 * Implementation Limits::
17999 * Tools::
18000 @end menu
18002 @node Ada 95 Compatibility
18003 @section Ada 95 Compatibility
18005 @noindent
18006 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
18007 compiler. Ada 95 is almost completely upwards compatible
18008 with Ada 83, and therefore Ada 83 programs will compile
18009 and run under GNAT with
18010 no changes or only minor changes. The Ada 95 Reference
18011 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
18012 incompatibilities.
18014 GNAT provides the switch /83 on the GNAT COMPILE command,
18015 as well as the pragma ADA_83, to force the compiler to
18016 operate in Ada 83 mode. This mode does not guarantee complete
18017 conformance to Ada 83, but in practice is sufficient to
18018 eliminate most sources of incompatibilities.
18019 In particular, it eliminates the recognition of the
18020 additional Ada 95 keywords, so that their use as identifiers
18021 in Ada83 program is legal, and handles the cases of packages
18022 with optional bodies, and generics that instantiate unconstrained
18023 types without the use of @code{(<>)}.
18025 @node Differences in the Definition of Package System
18026 @section Differences in the Definition of Package System
18028 @noindent
18029 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
18030 implementation-dependent declarations to package System. In normal mode,
18031 GNAT does not take advantage of this permission, and the version of System
18032 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
18034 However, DEC Ada adds an extensive set of declarations to package System,
18035 as fully documented in the DEC Ada manuals. To minimize changes required
18036 for programs that make use of these extensions, GNAT provides the pragma
18037 Extend_System for extending the definition of package System. By using:
18039 @smallexample
18040 @group
18041 @cartouche
18042 @b{pragma} Extend_System (Aux_DEC);
18043 @end cartouche
18044 @end group
18045 @end smallexample
18047 @noindent
18048 The set of definitions in System is extended to include those in package
18049 @code{System.Aux_DEC}.
18050 These definitions are incorporated directly into package
18051 System, as though they had been declared there in the first place. For a
18052 list of the declarations added, see the specification of this package,
18053 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
18054 The pragma Extend_System is a configuration pragma, which means that
18055 it can be placed in the file @file{gnat.adc}, so that it will automatically
18056 apply to all subsequent compilations. See the section on Configuration
18057 Pragmas for further details.
18059 An alternative approach that avoids the use of the non-standard
18060 Extend_System pragma is to add a context clause to the unit that
18061 references these facilities:
18063 @smallexample
18064 @group
18065 @cartouche
18066 @b{with} System.Aux_DEC;
18067 @b{use}  System.Aux_DEC;
18068 @end cartouche
18069 @end group
18070 @end smallexample
18072 @noindent
18073 The effect is not quite semantically identical to incorporating the declarations
18074 directly into package @code{System},
18075 but most programs will not notice a difference
18076 unless they use prefix notation (e.g. @code{System.Integer_8})
18077 to reference the
18078 entities directly in package @code{System}.
18079 For units containing such references,
18080 the prefixes must either be removed, or the pragma @code{Extend_System}
18081 must be used.
18083 @node Language-Related Features
18084 @section Language-Related Features
18086 @noindent
18087 The following sections highlight differences in types,
18088 representations of types, operations, alignment, and
18089 related topics.
18091 @menu
18092 * Integer Types and Representations::
18093 * Floating-Point Types and Representations::
18094 * Pragmas Float_Representation and Long_Float::
18095 * Fixed-Point Types and Representations::
18096 * Record and Array Component Alignment::
18097 * Address Clauses::
18098 * Other Representation Clauses::
18099 @end menu
18101 @node Integer Types and Representations
18102 @subsection Integer Types and Representations
18104 @noindent
18105 The set of predefined integer types is identical in DEC Ada and GNAT.
18106 Furthermore the representation of these integer types is also identical,
18107 including the capability of size clauses forcing biased representation.
18109 In addition,
18110 DEC Ada for OpenVMS Alpha systems has defined the
18111 following additional integer types in package System:
18113 @itemize @bullet
18115 @item
18116 INTEGER_8
18118 @item
18119 INTEGER_16
18121 @item
18122 INTEGER_32
18124 @item
18125 INTEGER_64
18127 @item
18128 LARGEST_INTEGER
18129 @end itemize
18131 @noindent
18132 When using GNAT, the first four of these types may be obtained from the
18133 standard Ada 95 package @code{Interfaces}.
18134 Alternatively, by use of the pragma
18135 @code{Extend_System}, identical
18136 declarations can be referenced directly in package @code{System}.
18137 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
18139 @node Floating-Point Types and Representations
18140 @subsection Floating-Point Types and Representations
18141 @cindex Floating-Point types
18143 @noindent
18144 The set of predefined floating-point types is identical in DEC Ada and GNAT.
18145 Furthermore the representation of these floating-point
18146 types is also identical. One important difference is that the default
18147 representation for DEC Ada is VAX_Float, but the default representation
18148 for GNAT is IEEE.
18150 Specific types may be declared to be VAX_Float or IEEE, using the pragma
18151 @code{Float_Representation} as described in the DEC Ada documentation.
18152 For example, the declarations:
18154 @smallexample
18155 @group
18156 @cartouche
18157 @b{type} F_Float @b{is digits} 6;
18158 @b{pragma} Float_Representation (VAX_Float, F_Float);
18159 @end cartouche
18160 @end group
18161 @end smallexample
18163 @noindent
18164 declare a type F_Float that will be represented in VAX_Float format.
18165 This set of declarations actually appears in System.Aux_DEC, which provides
18166 the full set of additional floating-point declarations provided in
18167 the DEC Ada version of package
18168 System. This and similar declarations may be accessed in a user program by using
18169 pragma @code{Extend_System}. The use of this
18170 pragma, and the related pragma @code{Long_Float} is described in further
18171 detail in the following section.
18173 @node Pragmas Float_Representation and Long_Float
18174 @subsection Pragmas Float_Representation and Long_Float
18176 @noindent
18177 DEC Ada provides the pragma @code{Float_Representation}, which
18178 acts as a program library switch to allow control over
18179 the internal representation chosen for the predefined
18180 floating-point types declared in the package @code{Standard}.
18181 The format of this pragma is as follows:
18183 @smallexample
18184 @group
18185 @cartouche
18186 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
18187 @end cartouche
18188 @end group
18189 @end smallexample
18191 @noindent
18192 This pragma controls the representation of floating-point
18193 types as follows:
18195 @itemize @bullet
18196 @item
18197 @code{VAX_Float} specifies that floating-point
18198 types are represented by default with the VAX hardware types
18199 F-floating, D-floating, G-floating. Note that the H-floating
18200 type is available only on DIGITAL Vax systems, and is not available
18201 in either DEC Ada or GNAT for Alpha systems.
18203 @item
18204 @code{IEEE_Float} specifies that floating-point
18205 types are represented by default with the IEEE single and
18206 double floating-point types.
18207 @end itemize
18209 @noindent
18210 GNAT provides an identical implementation of the pragma
18211 @code{Float_Representation}, except that it functions as a
18212 configuration pragma, as defined by Ada 95. Note that the
18213 notion of configuration pragma corresponds closely to the
18214 DEC Ada notion of a program library switch.
18216 When no pragma is used in GNAT, the default is IEEE_Float, which is different
18217 from DEC Ada 83, where the default is VAX_Float. In addition, the
18218 predefined libraries in GNAT are built using IEEE_Float, so it is not
18219 advisable to change the format of numbers passed to standard library
18220 routines, and if necessary explicit type conversions may be needed.
18222 The use of IEEE_Float is recommended in GNAT since it is more efficient,
18223 and (given that it conforms to an international standard) potentially more
18224 portable. The situation in which VAX_Float may be useful is in interfacing
18225 to existing code and data that expects the use of VAX_Float. There are
18226 two possibilities here. If the requirement for the use of VAX_Float is
18227 localized, then the best approach is to use the predefined VAX_Float
18228 types in package @code{System}, as extended by
18229 @code{Extend_System}. For example, use @code{System.F_Float}
18230 to specify the 32-bit @code{F-Float} format.
18232 Alternatively, if an entire program depends heavily on the use of
18233 the @code{VAX_Float} and in particular assumes that the types in
18234 package @code{Standard} are in @code{Vax_Float} format, then it
18235 may be desirable to reconfigure GNAT to assume Vax_Float by default.
18236 This is done by using the GNAT LIBRARY command to rebuild the library, and
18237 then using the general form of the @code{Float_Representation}
18238 pragma to ensure that this default format is used throughout.
18239 The form of the GNAT LIBRARY command is:
18241 @smallexample
18242 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
18243 @end smallexample
18245 @noindent
18246 where @i{file} contains the new configuration pragmas
18247 and @i{directory} is the directory to be created to contain
18248 the new library.
18250 @noindent
18251 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
18252 to allow control over the internal representation chosen
18253 for the predefined type @code{Long_Float} and for floating-point
18254 type declarations with digits specified in the range 7 .. 15.
18255 The format of this pragma is as follows:
18257 @smallexample
18258 @cartouche
18259 @b{pragma} Long_Float (D_FLOAT | G_FLOAT);
18260 @end cartouche
18261 @end smallexample
18263 @node Fixed-Point Types and Representations
18264 @subsection Fixed-Point Types and Representations
18266 @noindent
18267 On DEC Ada for OpenVMS Alpha systems, rounding is
18268 away from zero for both positive and negative numbers.
18269 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
18271 On GNAT for OpenVMS Alpha, the results of operations
18272 on fixed-point types are in accordance with the Ada 95
18273 rules. In particular, results of operations on decimal
18274 fixed-point types are truncated.
18276 @node Record and Array Component Alignment
18277 @subsection Record and Array Component Alignment
18279 @noindent
18280 On DEC Ada for OpenVMS Alpha, all non composite components
18281 are aligned on natural boundaries. For example, 1-byte
18282 components are aligned on byte boundaries, 2-byte
18283 components on 2-byte boundaries, 4-byte components on 4-byte
18284 byte boundaries, and so on. The OpenVMS Alpha hardware
18285 runs more efficiently with naturally aligned data.
18287 ON GNAT for OpenVMS Alpha, alignment rules are compatible
18288 with DEC Ada for OpenVMS Alpha.
18290 @node Address Clauses
18291 @subsection Address Clauses
18293 @noindent
18294 In DEC Ada and GNAT, address clauses are supported for
18295 objects and imported subprograms.
18296 The predefined type @code{System.Address} is a private type
18297 in both compilers, with the same representation (it is simply
18298 a machine pointer). Addition, subtraction, and comparison
18299 operations are available in the standard Ada 95 package
18300 @code{System.Storage_Elements}, or in package @code{System}
18301 if it is extended to include @code{System.Aux_DEC} using a
18302 pragma @code{Extend_System} as previously described.
18304 Note that code that with's both this extended package @code{System}
18305 and the package @code{System.Storage_Elements} should not @code{use}
18306 both packages, or ambiguities will result. In general it is better
18307 not to mix these two sets of facilities. The Ada 95 package was
18308 designed specifically to provide the kind of features that DEC Ada
18309 adds directly to package @code{System}.
18311 GNAT is compatible with DEC Ada in its handling of address
18312 clauses, except for some limitations in
18313 the form of address clauses for composite objects with
18314 initialization. Such address clauses are easily replaced
18315 by the use of an explicitly-defined constant as described
18316 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
18317 of declarations:
18319 @smallexample
18320 @group
18321 @cartouche
18322 X, Y : Integer := Init_Func;
18323 Q : String (X .. Y) := "abc";
18325 @b{for} Q'Address @b{use} Compute_Address;
18326 @end cartouche
18327 @end group
18328 @end smallexample
18330 @noindent
18331 will be rejected by GNAT, since the address cannot be computed at the time
18332 that Q is declared. To achieve the intended effect, write instead:
18334 @smallexample
18335 @group
18336 @cartouche
18337 X, Y : Integer := Init_Func;
18338 Q_Address : @b{constant} Address := Compute_Address;
18339 Q : String (X .. Y) := "abc";
18341 @b{for} Q'Address @b{use} Q_Address;
18342 @end cartouche
18343 @end group
18344 @end smallexample
18346 @noindent
18347 which will be accepted by GNAT (and other Ada 95 compilers), and is also
18348 backwards compatible with Ada 83. A fuller description of the restrictions
18349 on address specifications is found in the GNAT Reference Manual.
18351 @node Other Representation Clauses
18352 @subsection Other Representation Clauses
18354 @noindent
18355 GNAT supports in a compatible manner all the representation
18356 clauses supported by DEC Ada. In addition, it
18357 supports representation clause forms that are new in Ada 95
18358 including COMPONENT_SIZE and SIZE clauses for objects.
18360 @node The Package STANDARD
18361 @section The Package STANDARD
18363 @noindent
18364 The package STANDARD, as implemented by DEC Ada, is fully
18365 described in the Reference Manual for the Ada Programming
18366 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
18367 Language Reference Manual. As implemented by GNAT, the
18368 package STANDARD is described in the Ada 95 Reference
18369 Manual.
18371 In addition, DEC Ada supports the Latin-1 character set in
18372 the type CHARACTER. GNAT supports the Latin-1 character set
18373 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
18374 the type WIDE_CHARACTER.
18376 The floating-point types supported by GNAT are those
18377 supported by DEC Ada, but defaults are different, and are controlled by
18378 pragmas. See @pxref{Floating-Point Types and Representations} for details.
18380 @node The Package SYSTEM
18381 @section The Package SYSTEM
18383 @noindent
18384 DEC Ada provides a system-specific version of the package
18385 SYSTEM for each platform on which the language ships.
18386 For the complete specification of the package SYSTEM, see
18387 Appendix F of the DEC Ada Language Reference Manual.
18389 On DEC Ada, the package SYSTEM includes the following conversion functions:
18390 @itemize @bullet
18391 @item TO_ADDRESS(INTEGER)
18393 @item  TO_ADDRESS(UNSIGNED_LONGWORD)
18395 @item  TO_ADDRESS(universal_integer)
18397 @item  TO_INTEGER(ADDRESS)
18399 @item  TO_UNSIGNED_LONGWORD(ADDRESS)
18401 @item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
18402                  functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
18403 @end itemize
18405 @noindent
18406 By default, GNAT supplies a version of SYSTEM that matches
18407 the definition given in the Ada 95 Reference Manual.
18408 This
18409 is a subset of the DIGITAL system definitions, which is as
18410 close as possible to the original definitions. The only difference
18411 is that the definition of SYSTEM_NAME is different:
18413 @smallexample
18414 @group
18415 @cartouche
18416 @b{type} Name @b{is} (SYSTEM_NAME_GNAT);
18417 System_Name : @b{constant} Name := SYSTEM_NAME_GNAT;
18418 @end cartouche
18419 @end group
18420 @end smallexample
18422 @noindent
18423 Also, GNAT adds the new Ada 95 declarations for
18424 BIT_ORDER and DEFAULT_BIT_ORDER.
18426 However, the use of the following pragma causes GNAT
18427 to extend the definition of package SYSTEM so that it
18428 encompasses the full set of DIGITAL-specific extensions,
18429 including the functions listed above:
18431 @smallexample
18432 @cartouche
18433 @b{pragma} Extend_System (Aux_DEC);
18434 @end cartouche
18435 @end smallexample
18437 @noindent
18438 The pragma Extend_System is a configuration pragma that
18439 is most conveniently placed in the @file{gnat.adc} file. See the
18440 GNAT Reference Manual for further details.
18442 DEC Ada does not allow the recompilation of the package
18443 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
18444 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
18445 the package SYSTEM. On OpenVMS Alpha systems, the pragma
18446 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
18447 its single argument.
18449 GNAT does permit the recompilation of package SYSTEM using
18450 a special switch (-gnatg) and this switch can be used if
18451 it is necessary to change constants in SYSTEM. GNAT does
18452 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
18453 or MEMORY_SIZE by any other means.
18455 On GNAT systems, the pragma SYSTEM_NAME takes the
18456 enumeration literal SYSTEM_NAME_GNAT.
18458 The definitions provided by the use of
18460 @smallexample
18461 pragma Extend_System (AUX_Dec);
18462 @end smallexample
18464 @noindent
18465 are virtually identical to those provided by the DEC Ada 83 package
18466 System. One important difference is that the name of the TO_ADDRESS
18467 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
18468 See the GNAT Reference manual for a discussion of why this change was
18469 necessary.
18471 @noindent
18472 The version of TO_ADDRESS taking a universal integer argument is in fact
18473 an extension to Ada 83 not strictly compatible with the reference manual.
18474 In GNAT, we are constrained to be exactly compatible with the standard,
18475 and this means we cannot provide this capability. In DEC Ada 83, the
18476 point of this definition is to deal with a call like:
18478 @smallexample
18479 TO_ADDRESS (16#12777#);
18480 @end smallexample
18482 @noindent
18483 Normally, according to the Ada 83 standard, one would expect this to be
18484 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
18485 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
18486 definition using universal_integer takes precedence.
18488 In GNAT, since the version with universal_integer cannot be supplied, it is
18489 not possible to be 100% compatible. Since there are many programs using
18490 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
18491 to change the name of the function in the UNSIGNED_LONGWORD case, so the
18492 declarations provided in the GNAT version of AUX_Dec are:
18494 @smallexample
18495 function To_Address (X : Integer) return Address;
18496 pragma Pure_Function (To_Address);
18498 function To_Address_Long (X : Unsigned_Longword) return Address;
18499 pragma Pure_Function (To_Address_Long);
18500 @end smallexample
18502 @noindent
18503 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
18504 change the name to TO_ADDRESS_LONG.
18506 @node Tasking and Task-Related Features
18507 @section Tasking and Task-Related Features
18509 @noindent
18510 The concepts relevant to a comparison of tasking on GNAT
18511 and on DEC Ada for OpenVMS Alpha systems are discussed in
18512 the following sections.
18514 For detailed information on concepts related to tasking in
18515 DEC Ada, see the DEC Ada Language Reference Manual and the
18516 relevant run-time reference manual.
18518 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
18519 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
18521 @noindent
18522 On OpenVMS Alpha systems, each Ada task (except a passive
18523 task) is implemented as a single stream of execution
18524 that is created and managed by the kernel. On these
18525 systems, DEC Ada tasking support is based on DECthreads,
18526 an implementation of the POSIX standard for threads.
18528 Although tasks are implemented as threads, all tasks in
18529 an Ada program are part of the same process. As a result,
18530 resources such as open files and virtual memory can be
18531 shared easily among tasks. Having all tasks in one process
18532 allows better integration with the programming environment
18533 (the shell and the debugger, for example).
18535 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
18536 code that calls DECthreads routines can be used together.
18537 The interaction between Ada tasks and DECthreads routines
18538 can have some benefits. For example when on OpenVMS Alpha,
18539 DEC Ada can call C code that is already threaded.
18540 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
18541 and Ada tasks are mapped to threads.
18543 @menu
18544 * Assigning Task IDs::
18545 * Task IDs and Delays::
18546 * Task-Related Pragmas::
18547 * Scheduling and Task Priority::
18548 * The Task Stack::
18549 * External Interrupts::
18550 @end menu
18552 @node Assigning Task IDs
18553 @subsection Assigning Task IDs
18555 @noindent
18556 The DEC Ada Run-Time Library always assigns %TASK 1 to
18557 the environment task that executes the main program. On
18558 OpenVMS Alpha systems, %TASK 0 is often used for tasks
18559 that have been created but are not yet activated.
18561 On OpenVMS Alpha systems, task IDs are assigned at
18562 activation. On GNAT systems, task IDs are also assigned at
18563 task creation but do not have the same form or values as
18564 task ID values in DEC Ada. There is no null task, and the
18565 environment task does not have a specific task ID value.
18567 @node Task IDs and Delays
18568 @subsection Task IDs and Delays
18570 @noindent
18571 On OpenVMS Alpha systems, tasking delays are implemented
18572 using Timer System Services. The Task ID is used for the
18573 identification of the timer request (the REQIDT parameter).
18574 If Timers are used in the application take care not to use
18575 0 for the identification, because cancelling such a timer
18576 will cancel all timers and may lead to unpredictable results.
18578 @node Task-Related Pragmas
18579 @subsection Task-Related Pragmas
18581 @noindent
18582 Ada supplies the pragma TASK_STORAGE, which allows
18583 specification of the size of the guard area for a task
18584 stack. (The guard area forms an area of memory that has no
18585 read or write access and thus helps in the detection of
18586 stack overflow.) On OpenVMS Alpha systems, if the pragma
18587 TASK_STORAGE specifies a value of zero, a minimal guard
18588 area is created. In the absence of a pragma TASK_STORAGE, a default guard
18589 area is created.
18591 GNAT supplies the following task-related pragmas:
18593 @itemize @bullet
18594 @item  TASK_INFO
18596               This pragma appears within a task definition and
18597               applies to the task in which it appears. The argument
18598               must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
18600 @item  TASK_STORAGE
18602               GNAT implements pragma TASK_STORAGE in the same way as
18603               DEC Ada.
18604               Both DEC Ada and GNAT supply the pragmas PASSIVE,
18605               SUPPRESS, and VOLATILE.
18606 @end itemize
18607 @node Scheduling and Task Priority
18608 @subsection Scheduling and Task Priority
18610 @noindent
18611 DEC Ada implements the Ada language requirement that
18612 when two tasks are eligible for execution and they have
18613 different priorities, the lower priority task does not
18614 execute while the higher priority task is waiting. The DEC
18615 Ada Run-Time Library keeps a task running until either the
18616 task is suspended or a higher priority task becomes ready.
18618 On OpenVMS Alpha systems, the default strategy is round-
18619 robin with preemption. Tasks of equal priority take turns
18620 at the processor. A task is run for a certain period of
18621 time and then placed at the rear of the ready queue for
18622 its priority level.
18624 DEC Ada provides the implementation-defined pragma TIME_SLICE,
18625 which can be used to enable or disable round-robin
18626 scheduling of tasks with the same priority.
18627 See the relevant DEC Ada run-time reference manual for
18628 information on using the pragmas to control DEC Ada task
18629 scheduling.
18631 GNAT follows the scheduling rules of Annex D (real-time
18632 Annex) of the Ada 95 Reference Manual. In general, this
18633 scheduling strategy is fully compatible with DEC Ada
18634 although it provides some additional constraints (as
18635 fully documented in Annex D).
18636 GNAT implements time slicing control in a manner compatible with
18637 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
18638 to the DEC Ada 83 pragma of the same name.
18639 Note that it is not possible to mix GNAT tasking and
18640 DEC Ada 83 tasking in the same program, since the two run times are
18641 not compatible.
18643 @node The Task Stack
18644 @subsection The Task Stack
18646 @noindent
18647 In DEC Ada, a task stack is allocated each time a
18648 non passive task is activated. As soon as the task is
18649 terminated, the storage for the task stack is deallocated.
18650 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
18651 a default stack size is used. Also, regardless of the size
18652 specified, some additional space is allocated for task
18653 management purposes. On OpenVMS Alpha systems, at least
18654 one page is allocated.
18656 GNAT handles task stacks in a similar manner. According to
18657 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
18658 an alternative method for controlling the task stack size.
18659 The specification of the attribute T'STORAGE_SIZE is also
18660 supported in a manner compatible with DEC Ada.
18662 @node External Interrupts
18663 @subsection External Interrupts
18665 @noindent
18666 On DEC Ada, external interrupts can be associated with task entries.
18667 GNAT is compatible with DEC Ada in its handling of external interrupts.
18669 @node Pragmas and Pragma-Related Features
18670 @section Pragmas and Pragma-Related Features
18672 @noindent
18673 Both DEC Ada and GNAT supply all language-defined pragmas
18674 as specified by the Ada 83 standard. GNAT also supplies all
18675 language-defined pragmas specified in the Ada 95 Reference Manual.
18676 In addition, GNAT implements the implementation-defined pragmas
18677 from DEC Ada 83.
18679 @itemize @bullet
18680 @item  AST_ENTRY
18682 @item  COMMON_OBJECT
18684 @item  COMPONENT_ALIGNMENT
18686 @item  EXPORT_EXCEPTION
18688 @item  EXPORT_FUNCTION
18690 @item  EXPORT_OBJECT
18692 @item  EXPORT_PROCEDURE
18694 @item  EXPORT_VALUED_PROCEDURE
18696 @item  FLOAT_REPRESENTATION
18698 @item  IDENT
18700 @item  IMPORT_EXCEPTION
18702 @item  IMPORT_FUNCTION
18704 @item  IMPORT_OBJECT
18706 @item  IMPORT_PROCEDURE
18708 @item  IMPORT_VALUED_PROCEDURE
18710 @item  INLINE_GENERIC
18712 @item  INTERFACE_NAME
18714 @item  LONG_FLOAT
18716 @item  MAIN_STORAGE
18718 @item  PASSIVE
18720 @item  PSET_OBJECT
18722 @item  SHARE_GENERIC
18724 @item  SUPPRESS_ALL
18726 @item  TASK_STORAGE
18728 @item  TIME_SLICE
18730 @item  TITLE
18731 @end itemize
18733 @noindent
18734 These pragmas are all fully implemented, with the exception of @code{Title},
18735 @code{Passive}, and @code{Share_Generic}, which are
18736 recognized, but which have no
18737 effect in GNAT. The effect of @code{Passive} may be obtained by the
18738 use of protected objects in Ada 95. In GNAT, all generics are inlined.
18740 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
18741 a separate subprogram specification which must appear before the
18742 subprogram body.
18744 GNAT also supplies a number of implementation-defined pragmas as follows:
18745 @itemize @bullet
18746 @item  C_PASS_BY_COPY
18748 @item  EXTEND_SYSTEM
18750 @item  SOURCE_FILE_NAME
18752 @item  UNSUPPRESS
18754 @item  WARNINGS
18756 @item  ABORT_DEFER
18758 @item  ADA_83
18760 @item  ADA_95
18762 @item  ANNOTATE
18764 @item  ASSERT
18766 @item  CPP_CLASS
18768 @item  CPP_CONSTRUCTOR
18770 @item  CPP_DESTRUCTOR
18772 @item  CPP_VIRTUAL
18774 @item  CP_VTABLE
18776 @item  DEBUG
18778 @item  LINKER_ALIAS
18780 @item  LINKER_SECTION
18782 @item  MACHINE_ATTRIBUTE
18784 @item  NO_RETURN
18786 @item  PURE_FUNCTION
18788 @item  SOURCE_REFERENCE
18790 @item  TASK_INFO
18792 @item  UNCHECKED_UNION
18794 @item  UNIMPLEMENTED_UNIT
18796 @item  WEAK_EXTERNAL
18797 @end itemize
18799 @noindent
18800 For full details on these GNAT implementation-defined pragmas, see
18801 the GNAT Reference Manual.
18803 @menu
18804 * Restrictions on the Pragma INLINE::
18805 * Restrictions on the Pragma INTERFACE::
18806 * Restrictions on the Pragma SYSTEM_NAME::
18807 @end menu
18809 @node Restrictions on the Pragma INLINE
18810 @subsection Restrictions on the Pragma INLINE
18812 @noindent
18813 DEC Ada applies the following restrictions to the pragma INLINE:
18814 @itemize @bullet
18815 @item  Parameters cannot be a task type.
18817 @item  Function results cannot be task types, unconstrained
18818 array types, or unconstrained types with discriminants.
18820 @item  Bodies cannot declare the following:
18821 @itemize @bullet
18822 @item  Subprogram body or stub (imported subprogram is allowed)
18824 @item  Tasks
18826 @item  Generic declarations
18828 @item  Instantiations
18830 @item  Exceptions
18832 @item  Access types (types derived from access types allowed)
18834 @item  Array or record types
18836 @item  Dependent tasks
18838 @item  Direct recursive calls of subprogram or containing
18839 subprogram, directly or via a renaming
18841 @end itemize
18842 @end itemize
18844 @noindent
18845 In GNAT, the only restriction on pragma INLINE is that the
18846 body must occur before the call if both are in the same
18847 unit, and the size must be appropriately small. There are
18848 no other specific restrictions which cause subprograms to
18849 be incapable of being inlined.
18851 @node  Restrictions on the Pragma INTERFACE
18852 @subsection  Restrictions on the Pragma INTERFACE
18854 @noindent
18855 The following lists and describes the restrictions on the
18856 pragma INTERFACE on DEC Ada and GNAT:
18857 @itemize @bullet
18858 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
18859 Default is the default on OpenVMS Alpha systems.
18861 @item  Parameter passing: Language specifies default
18862 mechanisms but can be overridden with an EXPORT pragma.
18864 @itemize @bullet
18865 @item  Ada: Use internal Ada rules.
18867 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
18868 record or task type. Result cannot be a string, an
18869 array, or a record.
18871 @item  Fortran: Parameters cannot be a task. Result cannot
18872 be a string, an array, or a record.
18873 @end itemize
18874 @end itemize
18876 @noindent
18877 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
18878 record parameters for all languages.
18880 @node  Restrictions on the Pragma SYSTEM_NAME
18881 @subsection  Restrictions on the Pragma SYSTEM_NAME
18883 @noindent
18884 For DEC Ada for OpenVMS Alpha, the enumeration literal
18885 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
18886 literal for the type NAME is SYSTEM_NAME_GNAT.
18888 @node  Library of Predefined Units
18889 @section  Library of Predefined Units
18891 @noindent
18892 A library of predefined units is provided as part of the
18893 DEC Ada and GNAT implementations. DEC Ada does not provide
18894 the package MACHINE_CODE but instead recommends importing
18895 assembler code.
18897 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
18898 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
18899 version. During GNAT installation, the DEC Ada Predefined
18900 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
18901 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
18902 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
18903 for details.
18905 The GNAT RTL is contained in
18906 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
18907 the default search path is set up to find DECLIB units in preference
18908 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
18909 for example).
18911 However, it is possible to change the default so that the
18912 reverse is true, or even to mix them using child package
18913 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
18914 is the package name, and the Ada units are available in the
18915 standard manner defined for Ada 95, that is to say as Ada.xxx. To
18916 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
18917 appropriately. For example, to change the default to use the Ada95
18918 versions do:
18920 @smallexample
18921 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
18922                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
18923 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
18924                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
18925 @end smallexample
18927 @menu
18928 * Changes to DECLIB::
18929 @end menu
18931 @node Changes to DECLIB
18932 @subsection Changes to DECLIB
18934 @noindent
18935 The changes made to the DEC Ada predefined library for GNAT and Ada 95
18936 compatibility are minor and include the following:
18938 @itemize @bullet
18939 @item  Adjusting the location of pragmas and record representation
18940 clauses to obey Ada 95 rules
18942 @item  Adding the proper notation to generic formal parameters
18943 that take unconstrained types in instantiation
18945 @item  Adding pragma ELABORATE_BODY to package specifications
18946 that have package bodies not otherwise allowed
18948 @item  Occurrences of the identifier "PROTECTED" are renamed to "PROTECTD".
18949 Currently these are found only in the STARLET package spec.
18950 @end itemize
18952 @noindent
18953 None of the above changes is visible to users.
18955 @node Bindings
18956 @section Bindings
18958 @noindent
18959 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
18960 @itemize @bullet
18962 @item  Command Language Interpreter (CLI interface)
18964 @item  DECtalk Run-Time Library (DTK interface)
18966 @item  Librarian utility routines (LBR interface)
18968 @item  General Purpose Run-Time Library (LIB interface)
18970 @item  Math Run-Time Library (MTH interface)
18972 @item  National Character Set Run-Time Library (NCS interface)
18974 @item  Compiled Code Support Run-Time Library (OTS interface)
18976 @item  Parallel Processing Run-Time Library (PPL interface)
18978 @item  Screen Management Run-Time Library (SMG interface)
18980 @item  Sort Run-Time Library (SOR interface)
18982 @item  String Run-Time Library (STR interface)
18984 @item STARLET System Library
18985 @findex Starlet
18987 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
18989 @item  X Windows Toolkit (XT interface)
18991 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
18992 @end itemize
18994 @noindent
18995 GNAT provides implementations of these DEC bindings in the DECLIB directory.
18997 The X/Motif bindings used to build DECLIB are whatever versions are in the
18998 DEC Ada ADA$PREDEFINED directory with extension .ADC. The build script will
18999 automatically add a pragma Linker_Options to packages Xm, Xt, and X_Lib
19000 causing the default X/Motif shareable image libraries to be linked in. This
19001 is done via options files named xm.opt, xt.opt, and x_lib.opt (also located
19002 in the DECLIB directory).
19004 It may be necessary to edit these options files to update or correct the
19005 library names if, for example, the newer X/Motif bindings from ADA$EXAMPLES
19006 had been (previous to installing GNAT) copied and renamed to superseded the
19007 default ADA$PREDEFINED versions.
19009 @menu
19010 * Shared Libraries and Options Files::
19011 * Interfaces to C::
19012 @end menu
19014 @node Shared Libraries and Options Files
19015 @subsection Shared Libraries and Options Files
19017 @noindent
19018 When using the DEC Ada
19019 predefined X and Motif bindings, the linking with their shareable images is
19020 done automatically by GNAT LINK. When using other X and Motif bindings, it
19021 is necessary to add the corresponding shareable images to the command line for
19022 GNAT LINK. When linking with shared libraries, or with .OPT files, it is
19023 also necessary to add them to the command line for GNAT LINK.
19025 A shared library to be used with GNAT is built in the same way as other
19026 libraries under VMS. The VMS Link command can be used in standard fashion.
19028 @node Interfaces to C
19029 @subsection Interfaces to C
19031 @noindent
19032 DEC Ada
19033 provides the following Ada types and operations:
19035 @itemize @bullet
19036 @item C types package (C_TYPES)
19038 @item C strings (C_TYPES.NULL_TERMINATED)
19040 @item Other_types (SHORT_INT)
19041 @end itemize
19043 @noindent
19044 Interfacing to C with GNAT, one can use the above approach
19045 described for DEC Ada or the facilities of Annex B of
19046 the Ada 95 Reference Manual (packages INTERFACES.C,
19047 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
19048 information, see the section "Interfacing to C" in the
19049 GNAT Reference Manual.
19051 The @option{-gnatF} qualifier forces default and explicit
19052 @code{External_Name} parameters in pragmas Import and Export
19053 to be uppercased for compatibility with the default behavior
19054 of DEC C. The qualifier has no effect on @code{Link_Name} parameters.
19056 @node Main Program Definition
19057 @section Main Program Definition
19059 @noindent
19060 The following section discusses differences in the
19061 definition of main programs on DEC Ada and GNAT.
19062 On DEC Ada, main programs are defined to meet the
19063 following conditions:
19064 @itemize @bullet
19065 @item  Procedure with no formal parameters (returns 0 upon
19066        normal completion)
19068 @item  Procedure with no formal parameters (returns 42 when
19069        unhandled exceptions are raised)
19071 @item  Function with no formal parameters whose returned value
19072        is of a discrete type
19074 @item  Procedure with one OUT formal of a discrete type for
19075        which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
19077 @end itemize
19079 @noindent
19080 When declared with the pragma EXPORT_VALUED_PROCEDURE,
19081 a main function or main procedure returns a discrete
19082 value whose size is less than 64 bits (32 on VAX systems),
19083 the value is zero- or sign-extended as appropriate.
19084 On GNAT, main programs are defined as follows:
19085 @itemize @bullet
19086 @item  Must be a non-generic, parameter-less subprogram that
19087 is either a procedure or function returning an Ada
19088 STANDARD.INTEGER (the predefined type)
19090 @item  Cannot be a generic subprogram or an instantiation of a
19091 generic subprogram
19092 @end itemize
19094 @node Implementation-Defined Attributes
19095 @section Implementation-Defined Attributes
19097 @noindent
19098 GNAT provides all DEC Ada implementation-defined
19099 attributes.
19101 @node Compiler and Run-Time Interfacing
19102 @section Compiler and Run-Time Interfacing
19104 @noindent
19105 DEC Ada provides the following ways to pass options to the linker (ACS LINK):
19106 @itemize @bullet
19107 @item  /WAIT and /SUBMIT qualifiers
19109 @item  /COMMAND qualifier
19111 @item  /[NO]MAP qualifier
19113 @item  /OUTPUT=file-spec
19115 @item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
19116 @end itemize
19118 @noindent
19119 To pass options to the linker, GNAT provides the following
19120 switches:
19122 @itemize @bullet
19123 @item   /EXECUTABLE=exec-name
19125 @item   /VERBOSE qualifier
19127 @item   /[NO]DEBUG and /[NO]TRACEBACK qualifiers
19128 @end itemize
19130 @noindent
19131 For more information on these switches, see the section
19132 "Switches for gnatlink" in the corresponding section of this Guide.
19133 In DEC Ada, the command-line switch /OPTIMIZE is available
19134 to control optimization. DEC Ada also supplies the
19135 following pragmas:
19136 @itemize @bullet
19137 @item  OPTIMIZE
19139 @item  INLINE
19141 @item  INLINE_GENERIC
19143 @item  SUPPRESS_ALL
19145 @item  PASSIVE
19146 @end itemize
19148 @noindent
19149 In GNAT, optimization is controlled strictly by command
19150 line parameters, as described in the corresponding section of this guide.
19151 The DIGITAL pragmas for control of optimization are
19152 recognized but ignored.
19154 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
19155 the default is that optimization is turned on.
19157 @node Program Compilation and Library Management
19158 @section Program Compilation and Library Management
19160 @noindent
19161 DEC Ada and GNAT provide a comparable set of commands to
19162 build programs. DEC Ada also provides a program library,
19163 which is a concept that does not exist on GNAT. Instead,
19164 GNAT provides directories of sources that are compiled as
19165 needed.
19167 The following table summarizes
19168 the DEC Ada commands and provides
19169 equivalent GNAT commands. In this table, some GNAT
19170 equivalents reflect the fact that GNAT does not use the
19171 concept of a program library. Instead, it uses a model
19172 in which collections of source and object files are used
19173 in a manner consistent with other languages like C and
19174 Fortran. Therefore, standard system file commands are used
19175 to manipulate these elements. Those GNAT commands are marked with
19176 an asterisk in the table that follows.
19177 Note that, unlike DEC Ada,  none of the GNAT commands accepts wild cards.
19179 @need 1500
19180 @multitable @columnfractions .31 .30 .39
19182 @item @strong{DEC_Ada_Command}
19183 @tab @strong{GNAT_Equivalent}
19184 @tab @strong{Description}
19186 @item  ADA
19187 @tab     GNAT COMPILE
19188 @tab     Invokes the compiler to compile one or more Ada source files.
19190 @item  ACS ATTACH
19191 @tab     No equivalent
19192 @tab     Switches control of terminal from current process running the program
19193                                                 library manager.
19195 @item   ACS CHECK
19196 @tab      GNAT MAKE /DEPENDENCY_LIST
19197 @tab      Forms the execution closure of one
19198           or more compiled units and checks completeness and currency.
19200 @item   ACS COMPILE
19201 @tab      GNAT MAKE /ACTIONS=COMPILE
19202 @tab      Forms the execution closure of one or
19203           more specified units, checks completeness and currency,
19204           identifies units that have revised source files, compiles same,
19205           and recompiles units that are or will become obsolete.
19206           Also completes incomplete generic instantiations.
19208 @item   ACS COPY FOREIGN
19209 @tab      Copy (*)
19210 @tab      Copies a foreign object file into the program library as a
19211           library unit body.
19213 @item   ACS COPY UNIT
19214 @tab      Copy (*)
19215 @tab      Copies a compiled unit from one program library to another.
19217 @item   ACS CREATE LIBRARY
19218 @tab      Create /directory (*)
19219 @tab      Creates a program library.
19221 @item   ACS CREATE SUBLIBRARY
19222 @tab      Create /directory (*)
19223 @tab      Creates a program sublibrary.
19225 @item   ACS DELETE LIBRARY
19226 @tab
19227 @tab       Deletes a program library and its contents.
19229 @item   ACS DELETE SUBLIBRARY
19230 @tab
19231 @tab      Deletes a program sublibrary and its contents.
19233 @item   ACS DELETE UNIT
19234 @tab      Delete @i{file} (*)
19235 @tab      On OpenVMS systems, deletes one or more compiled units from
19236           the current program library.
19238 @item   ACS DIRECTORY
19239 @tab       Directory (*)
19240 @tab       On OpenVMS systems, lists units contained in the current
19241            program library.
19243 @item   ACS ENTER FOREIGN
19244 @tab      Copy (*)
19245 @tab      Allows the import of a foreign body as an Ada library
19246           specification and enters a reference to a pointer.
19248 @item   ACS ENTER UNIT
19249 @tab      Copy (*)
19250 @tab      Enters a reference (pointer) from the current program library to
19251           a unit compiled into another program library.
19253 @item   ACS EXIT
19254 @tab      No equivalent
19255 @tab      Exits from the program library manager.
19257 @item   ACS EXPORT
19258 @tab      Copy (*)
19259 @tab      Creates an object file that contains system-specific object code
19260           for one or more units. With GNAT, object files can simply be copied
19261           into the desired directory.
19263 @item   ACS EXTRACT SOURCE
19264 @tab      Copy (*)
19265 @tab      Allows access to the copied source file for each Ada compilation unit
19267 @item   ACS HELP
19268 @tab      HELP GNAT
19269 @tab      Provides online help.
19271 @item    ACS LINK
19272 @tab       GNAT LINK
19273 @tab       Links an object file containing Ada units into an executable
19274            file.
19276 @item    ACS LOAD
19277 @tab       Copy (*)
19278 @tab       Loads (partially compiles) Ada units into the program library.
19279            Allows loading a program from a collection of files into a library
19280            without knowing the relationship among units.
19282 @item    ACS MERGE
19283 @tab      Copy (*)
19284 @tab      Merges into the current program library, one or more units from
19285           another library where they were modified.
19287 @item    ACS RECOMPILE
19288 @tab       GNAT MAKE /ACTIONS=COMPILE
19289 @tab       Recompiles from   external or copied source files any obsolete
19290            unit in the closure. Also, completes any incomplete generic
19291            instantiations.
19293 @item    ACS REENTER
19294 @tab       GNAT MAKE
19295 @tab       Reenters current references to units compiled after last entered
19296            with the ACS ENTER UNIT command.
19298 @item    ACS SET LIBRARY
19299 @tab       Set default (*)
19300 @tab       Defines a program library to be the compilation context as well
19301            as the target library for compiler output and commands in general.
19303 @item    ACS SET PRAGMA
19304 @tab       Edit gnat.adc (*)
19305 @tab       Redefines specified  values of the library characteristics
19306             LONG_ FLOAT, MEMORY_SIZE, SYSTEM_NAME, and @code{Float_Representation}.
19308 @item    ACS SET SOURCE
19309 @tab       define @* ADA_INCLUDE_PATH @i{path} (*)
19310 @tab       Defines the source file search list for the ACS COMPILE  command.
19312 @item    ACS SHOW LIBRARY
19313 @tab       Directory (*)
19314 @tab        Lists information about one or more program libraries.
19316 @item    ACS SHOW PROGRAM
19317 @tab       No equivalent
19318 @tab       Lists information about the execution closure of one or
19319            more units in the program library.
19321 @item    ACS SHOW SOURCE
19322 @tab       Show logical @* ADA_INCLUDE_PATH
19323 @tab       Shows the source file search used when compiling units.
19325 @item    ACS SHOW VERSION
19326 @tab       Compile with VERBOSE option
19327 @tab       Displays the version number of the compiler and program library
19328            manager used.
19330 @item    ACS SPAWN
19331 @tab        No equivalent
19332 @tab        Creates a subprocess of the current process (same as DCL SPAWN
19333             command).
19335 @item    ACS VERIFY
19336 @tab       No equivalent
19337 @tab       Performs a series of consistency checks on a program library to
19338            determine whether the library structure and library files are in
19339            valid_form.
19341 @end multitable
19343 @noindent
19345 @node Input-Output
19346 @section Input-Output
19348 @noindent
19349 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
19350 Management Services (RMS) to perform operations on
19351 external files.
19353 @noindent
19354 DEC Ada and GNAT predefine an identical set of input-
19355 output packages. To make the use of the
19356 generic TEXT_IO operations more convenient, DEC Ada
19357 provides predefined library packages that instantiate the
19358 integer and floating-point operations for the predefined
19359 integer and floating-point types as shown in the following table.
19361 @table @code
19363 @item   Package_Name
19364       Instantiation
19366 @item   INTEGER_TEXT_IO
19367       INTEGER_IO(INTEGER)
19369 @item   SHORT_INTEGER_TEXT_IO
19370      INTEGER_IO(SHORT_INTEGER)
19372 @item   SHORT_SHORT_INTEGER_TEXT_IO
19373      INTEGER_IO(SHORT_SHORT_ INTEGER)
19375 @item   FLOAT_TEXT_IO
19376       FLOAT_IO(FLOAT)
19378 @item   LONG_FLOAT_TEXT_IO
19379       FLOAT_IO(LONG_FLOAT)
19380 @end table
19382 @noindent
19383 The DEC Ada predefined packages and their operations
19384 are implemented using OpenVMS Alpha files and input-
19385 output facilities. DEC Ada supports asynchronous input-
19386 output on OpenVMS Alpha. Familiarity with the following is
19387 recommended:
19388 @itemize @bullet
19389 @item  RMS file organizations and access methods
19391 @item  OpenVMS file specifications and directories
19393 @item  OpenVMS File Definition Language (FDL)
19394 @end itemize
19396 @noindent
19397 GNAT provides I/O facilities that are completely
19398 compatible with DEC Ada. The distribution includes the
19399 standard DEC Ada versions of all I/O packages, operating
19400 in a manner compatible with DEC Ada. In particular, the
19401 following packages are by default the DEC Ada (Ada 83)
19402 versions of these packages rather than the renamings
19403 suggested in annex J of the Ada 95 Reference Manual:
19404 @itemize @bullet
19405 @item  TEXT_IO
19407 @item  SEQUENTIAL_IO
19409 @item  DIRECT_IO
19410 @end itemize
19412 @noindent
19413 The use of the standard Ada 95 syntax for child packages (for
19414 example, ADA.TEXT_IO) retrieves the Ada 95 versions of these
19415 packages, as defined in the Ada 95 Reference Manual.
19416 GNAT provides DIGITAL-compatible predefined instantiations
19417 of the TEXT_IO packages, and also
19418 provides the standard predefined instantiations required
19419 by the Ada 95 Reference Manual.
19421 For further information on how GNAT interfaces to the file
19422 system or how I/O is implemented in programs written in
19423 mixed languages, see the chapter "Implementation of the
19424 Standard I/O" in the GNAT Reference Manual.
19425 This chapter covers the following:
19426 @itemize @bullet
19427 @item  Standard I/O packages
19429 @item  FORM strings
19431 @item  DIRECT_IO
19433 @item  SEQUENTIAL_IO
19435 @item  TEXT_IO
19437 @item  Stream pointer positioning
19439 @item  Reading and writing non-regular files
19441 @item  GET_IMMEDIATE
19443 @item  Treating TEXT_IO files as streams
19445 @item  Shared files
19447 @item  Open modes
19448 @end itemize
19450 @node Implementation Limits
19451 @section Implementation Limits
19453 @noindent
19454 The following table lists implementation limits for DEC Ada and GNAT systems.
19455 @multitable @columnfractions .60 .20 .20
19456 @item  Compilation Parameter
19457 @tab   DEC Ada
19458 @tab   GNAT
19460 @item  In a subprogram or entry  declaration, maximum number of
19461        formal parameters that are of an unconstrained record type
19462 @tab   32
19463 @tab   No set limit
19465 @item  Maximum identifier length (number of characters)
19466 @tab   255
19467 @tab   255
19469 @item  Maximum number of characters in a source line
19470 @tab   255
19471 @tab   255
19473 @item  Maximum collection size   (number of bytes)
19474 @tab   2**31-1
19475 @tab   2**31-1
19477 @item  Maximum number of discriminants for a record type
19478 @tab   245
19479 @tab   No set limit
19481 @item  Maximum number of formal parameters in an entry or
19482        subprogram declaration
19483 @tab   246
19484 @tab    No set limit
19486 @item  Maximum number of dimensions in an array type
19487 @tab   255
19488 @tab   No set limit
19490 @item  Maximum number of library  units and subunits in a compilation.
19491 @tab   4095
19492 @tab   No set limit
19494 @item  Maximum number of library units and subunits in an execution.
19495 @tab   16383
19496 @tab   No set limit
19498 @item  Maximum number of objects declared with the pragma COMMON_OBJECT
19499        or PSECT_OBJECT
19500 @tab   32757
19501 @tab   No set limit
19503 @item  Maximum number of enumeration literals in an enumeration type
19504        definition
19505 @tab   65535
19506 @tab   No set limit
19508 @item  Maximum number of lines in a source file
19509 @tab   65534
19510 @tab   No set limit
19512 @item  Maximum number of bits in any object
19513 @tab   2**31-1
19514 @tab   2**31-1
19516 @item  Maximum size of the static portion of a stack frame (approximate)
19517 @tab   2**31-1
19518 @tab   2**31-1
19519 @end multitable
19521 @node  Tools
19522 @section Tools
19524 @end ifset
19526 @node Inline Assembler
19527 @chapter Inline Assembler
19529 @noindent
19530 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:
19532 @itemize @bullet
19533 @item No need to use non-Ada tools
19534 @item Consistent interface over different targets
19535 @item Automatic usage of the proper calling conventions
19536 @item Access to Ada constants and variables
19537 @item Definition of intrinsic routines
19538 @item Possibility of inlining a subprogram comprising assembler code
19539 @item Code optimizer can take Inline Assembler code into account
19540 @end itemize
19542 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.
19544 @menu
19545 * Basic Assembler Syntax::
19546 * A Simple Example of Inline Assembler::
19547 * Output Variables in Inline Assembler::
19548 * Input Variables in Inline Assembler::
19549 * Inlining Inline Assembler Code::
19550 * Other Asm Functionality::
19551 * A Complete Example::
19552 @end menu
19554 @c ---------------------------------------------------------------------------
19555 @node Basic Assembler Syntax
19556 @section Basic Assembler Syntax
19558 @noindent
19559 The assembler used by GNAT and gcc is based not on the Intel assembly language, but rather on a
19560 language that descends from the AT&T Unix assembler @emph{as} (and which is often
19561 referred to as ``AT&T syntax'').
19562 The following table summarizes the main features of @emph{as} syntax and points out the differences from the Intel conventions.
19563 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
19564 pre-processor) documentation for further information.
19566 @table @asis
19567 @item Register names
19568 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
19570 Intel: No extra punctuation; for example @code{eax}
19572 @item Immediate operand
19573 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
19575 Intel: No extra punctuation; for example @code{4}
19577 @item Address
19578 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
19580 Intel: No extra punctuation; for example @code{loc}
19582 @item Memory contents
19583 gcc / @emph{as}: No extra punctuation; for example @code{loc}
19585 Intel: Square brackets; for example @code{[loc]}
19587 @item Register contents
19588 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
19590 Intel: Square brackets; for example @code{[eax]}
19592 @item Hexadecimal numbers
19593 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
19595 Intel: Trailing ``h''; for example @code{A0h}
19597 @item Operand size
19598 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move a 16-bit word
19600 Intel: Implicit, deduced by assembler; for example @code{mov}
19602 @item Instruction repetition
19603 gcc / @emph{as}: Split into two lines; for example
19605 @code{rep}
19607 @code{stosl}
19609 Intel: Keep on one line; for example @code{rep stosl}
19611 @item Order of operands
19612 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
19614 Intel: Destination first; for example @code{mov eax, 4}
19615 @end table
19617 @c ---------------------------------------------------------------------------
19618 @node A Simple Example of Inline Assembler
19619 @section A Simple Example of Inline Assembler
19621 @noindent
19622 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.
19624 @smallexample
19625 @group
19626 with System.Machine_Code; use System.Machine_Code;
19627 procedure Nothing is
19628 begin
19629    Asm ("nop");
19630 end Nothing;
19631 @end group
19632 @end smallexample
19634 @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.
19635 @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.
19637 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}.
19639 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:
19640 @smallexample
19641 gnatmake nothing
19642 @end smallexample
19643 However, the interesting aspect of this example is not its run-time behavior but rather the
19644 generated assembly code.  To see this output, invoke the compiler as follows:
19645 @smallexample
19646    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
19647 @end smallexample
19648 where the options are:
19650 @table @code
19651 @item -c
19652 compile only (no bind or link)
19653 @item -S
19654 generate assembler listing
19655 @item -fomit-frame-pointer
19656 do not set up separate stack frames
19657 @item -gnatp
19658 do not add runtime checks
19659 @end table
19661 This gives a human-readable assembler version of the code. The resulting
19662 file will have the same name as the Ada source file, but with a @code{.s} extension.
19663 In our example, the file @file{nothing.s} has the following contents:
19665 @smallexample
19666 @group
19667 .file "nothing.adb"
19668 gcc2_compiled.:
19669 ___gnu_compiled_ada:
19670 .text
19671    .align 4
19672 .globl __ada_nothing
19673 __ada_nothing:
19674 #APP
19675    nop
19676 #NO_APP
19677    jmp L1
19678    .align 2,0x90
19680    ret
19681 @end group
19682 @end smallexample
19684 The assembly code you included is clearly indicated by
19685 the compiler, between the @code{#APP} and @code{#NO_APP}
19686 delimiters. The character before the 'APP' and 'NOAPP'
19687 can differ on different targets. For example, Linux uses '#APP' while
19688 on NT you will see '/APP'.
19690 If you make a mistake in your assembler code (such as using the
19691 wrong size modifier, or using a wrong operand for the instruction) GNAT
19692 will report this error in a temporary file, which will be deleted when
19693 the compilation is finished.  Generating an assembler file will help
19694 in such cases, since you can assemble this file separately using the
19695 @emph{as} assembler that comes with gcc.
19697 Assembling the file using the command
19699 @smallexample
19700 as @file{nothing.s}
19701 @end smallexample
19702 @noindent
19703 will give you error messages whose lines correspond to the assembler
19704 input file, so you can easily find and correct any mistakes you made.
19705 If there are no errors, @emph{as} will generate an object file @file{nothing.out}.
19707 @c ---------------------------------------------------------------------------
19708 @node Output Variables in Inline Assembler
19709 @section Output Variables in Inline Assembler
19711 @noindent
19712 The examples in this section, showing how to access the processor flags, illustrate how to specify the destination operands for assembly language statements.
19714 @smallexample
19715 @group
19716 with Interfaces; use Interfaces;
19717 with Ada.Text_IO; use Ada.Text_IO;
19718 with System.Machine_Code; use System.Machine_Code;
19719 procedure Get_Flags is
19720    Flags : Unsigned_32;
19721    use ASCII;
19722 begin
19723    Asm ("pushfl"          & LF & HT & -- push flags on stack
19724         "popl %%eax"      & LF & HT & -- load eax with flags
19725         "movl %%eax, %0",             -- store flags in variable
19726         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
19727    Put_Line ("Flags register:" & Flags'Img);
19728 end Get_Flags;
19729 @end group
19730 @end smallexample
19732 In order to have a nicely aligned assembly listing, we have separated
19733 multiple assembler statements in the Asm template string with linefeed (ASCII.LF)
19734 and horizontal tab (ASCII.HT) characters.  The resulting section of the
19735 assembly output file is:
19737 @smallexample
19738 @group
19739 #APP
19740    pushfl
19741    popl %eax
19742    movl %eax, -40(%ebp)
19743 #NO_APP
19744 @end group
19745 @end smallexample
19747 It would have been legal to write the Asm invocation as:
19749 @smallexample
19750 Asm ("pushfl popl %%eax movl %%eax, %0")
19751 @end smallexample
19753 but in the generated assembler file, this would come out as:
19755 @smallexample
19756 #APP
19757    pushfl popl %eax movl %eax, -40(%ebp)
19758 #NO_APP
19759 @end smallexample
19761 which is not so convenient for the human reader.
19763 We use Ada comments
19764 at the end of each line to explain what the assembler instructions
19765 actually do.  This is a useful convention.
19767 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.
19769 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}.
19770 An output variable is illustrated in
19771 the third statement in the Asm template string:
19772 @smallexample
19773 movl %%eax, %0
19774 @end smallexample
19775 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.
19777 Information about the output variable is supplied in the @code{Outputs} parameter to @code{Asm}:
19778 @smallexample
19779 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
19780 @end smallexample
19782 The output is defined by the @code{Asm_Output} attribute of the target type; the general format is
19783 @smallexample
19784 Type'Asm_Output (constraint_string, variable_name)
19785 @end smallexample
19787 The constraint string directs the compiler how
19788 to store/access the associated variable.  In the example
19789 @smallexample
19790 Unsigned_32'Asm_Output ("=m", Flags);
19791 @end smallexample
19792 the @code{"m"} (memory) constraint tells the compiler that the variable
19793 @code{Flags} should be stored in a memory variable, thus preventing
19794 the optimizer from keeping it in a register.  In contrast,
19795 @smallexample
19796 Unsigned_32'Asm_Output ("=r", Flags);
19797 @end smallexample
19798 uses the @code{"r"} (register) constraint, telling the compiler to
19799 store the variable in a register.
19801 If the constraint is preceded by the equal character (@strong{=}), it tells the
19802 compiler that the variable will be used to store data into it.
19804 In the @code{Get_Flags} example, we used the "g" (global) constraint, allowing the optimizer
19805 to choose whatever it deems best.
19807 There are a fairly large number of constraints, but the ones that are most useful (for the Intel x86 processor) are the following:
19809 @table @code
19810 @item =
19811 output constraint
19812 @item g
19813 global (i.e. can be stored anywhere)
19814 @item m
19815 in memory
19816 @item I
19817 a constant
19818 @item a
19819 use eax
19820 @item b
19821 use ebx
19822 @item c
19823 use ecx
19824 @item d
19825 use edx
19826 @item S
19827 use esi
19828 @item D
19829 use edi
19830 @item r
19831 use one of eax, ebx, ecx or edx
19832 @item q
19833 use one of eax, ebx, ecx, edx, esi or edi
19834 @end table
19836 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.
19838 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
19839 @smallexample
19840 @group
19841 Asm ("pushfl"          & LF & HT & -- push flags on stack
19842      "popl %%eax"      & LF & HT & -- load eax with flags
19843      "movl %%eax, %0",             -- store flags in variable
19844      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
19845 @end group
19846 @end smallexample
19847 @noindent
19848 @code{%0} will be replaced in the expanded code by the appropriate operand,
19849 whatever
19850 the compiler decided for the @code{Flags} variable.
19852 In general, you may have any number of output variables:
19853 @itemize @bullet
19854 @item
19855 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
19856 @item
19857 Specify the @code{Outputs} parameter as a parenthesized comma-separated list of @code{Asm_Output} attributes
19858 @end itemize
19860 For example:
19861 @smallexample
19862 @group
19863 Asm ("movl %%eax, %0" & LF & HT &
19864      "movl %%ebx, %1" & LF & HT &
19865      "movl %%ecx, %2",
19866      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
19867                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
19868                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
19869 @end group
19870 @end smallexample
19871 @noindent
19872 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables in the Ada program.
19874 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:
19876 @smallexample
19877 @group
19878 with Interfaces; use Interfaces;
19879 with Ada.Text_IO; use Ada.Text_IO;
19880 with System.Machine_Code; use System.Machine_Code;
19881 procedure Get_Flags_2 is
19882    Flags : Unsigned_32;
19883    use ASCII;
19884 begin
19885    Asm ("pushfl"      & LF & HT & -- push flags on stack
19886         "popl %%eax",             -- save flags in eax
19887         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
19888    Put_Line ("Flags register:" & Flags'Img);
19889 end Get_Flags_2;
19890 @end group
19891 @end smallexample
19893 @noindent
19894 The @code{"a"} constraint tells the compiler that the @code{Flags}
19895 variable will come from the eax register. Here is the resulting code:
19897 @smallexample
19898 @group
19899 #APP
19900    pushfl
19901    popl %eax
19902 #NO_APP
19903    movl %eax,-40(%ebp)
19904 @end group
19905 @end smallexample
19907 @noindent
19908 The compiler generated the store of eax into Flags after
19909 expanding the assembler code.
19911 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:
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 Get_Flags_3 is
19919    Flags : Unsigned_32;
19920    use ASCII;
19921 begin
19922    Asm ("pushfl"  & LF & HT & -- push flags on stack
19923         "pop %0",             -- save flags in Flags
19924         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
19925    Put_Line ("Flags register:" & Flags'Img);
19926 end Get_Flags_3;
19927 @end group
19928 @end smallexample
19930 @c ---------------------------------------------------------------------------
19931 @node Input Variables in Inline Assembler
19932 @section Input Variables in Inline Assembler
19934 @noindent
19935 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:
19937 @smallexample
19938 @group
19939 with Interfaces; use Interfaces;
19940 with Ada.Text_IO; use Ada.Text_IO;
19941 with System.Machine_Code; use System.Machine_Code;
19942 procedure Increment is
19944    function Incr (Value : Unsigned_32) return Unsigned_32 is
19945       Result : Unsigned_32;
19946    begin
19947       Asm ("incl %0",
19948            Inputs  => Unsigned_32'Asm_Input ("a", Value),
19949            Outputs => Unsigned_32'Asm_Output ("=a", Result));
19950       return Result;
19951    end Incr;
19953    Value : Unsigned_32;
19955 begin
19956    Value := 5;
19957    Put_Line ("Value before is" & Value'Img);
19958    Value := Incr (Value);
19959    Put_Line ("Value after is" & Value'Img);
19960 end Increment;
19961 @end group
19962 @end smallexample
19964 The @code{Outputs} parameter to @code{Asm} specifies
19965 that the result will be in the eax register and that it is to be stored in the @code{Result}
19966 variable.
19968 The @code{Inputs} parameter looks much like the @code{Outputs} parameter, but with an
19969 @code{Asm_Input} attribute. The
19970 @code{"="} constraint, indicating an output value, is not present.
19972 You can have multiple input variables, in the same way that you can have more
19973 than one output variable.
19975 The parameter count (%0, %1) etc, now starts at the first input
19976 statement, and continues with the output statements.
19977 When both parameters use the same variable, the
19978 compiler will treat them as the same %n operand, which is the case here.
19980 Just as the @code{Outputs} parameter causes the register to be stored into the
19981 target variable after execution of the assembler statements, so does the
19982 @code{Inputs} parameter cause its variable to be loaded into the register before execution
19983 of the
19984 assembler statements.
19986 Thus the effect of the @code{Asm} invocation is:
19987 @enumerate
19988 @item load the 32-bit value of @code{Value} into eax
19989 @item execute the @code{incl %eax} instruction
19990 @item store the contents of eax into the @code{Result} variable
19991 @end enumerate
19993 The resulting assembler file (with @code{-O2} optimization) contains:
19994 @smallexample
19995 @group
19996 _increment__incr.1:
19997    subl $4,%esp
19998    movl 8(%esp),%eax
19999 #APP
20000    incl %eax
20001 #NO_APP
20002    movl %eax,%edx
20003    movl %ecx,(%esp)
20004    addl $4,%esp
20005    ret
20006 @end group
20007 @end smallexample
20009 @c ---------------------------------------------------------------------------
20010 @node Inlining Inline Assembler Code
20011 @section Inlining Inline Assembler Code
20013 @noindent
20014 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)
20015 can be significant, compared to the amount of code in the subprogram body.
20016 A solution is to apply Ada's @code{Inline} pragma to the subprogram,
20017 which directs the compiler to expand invocations of the subprogram at the point(s)
20018 of call, instead of setting up a stack frame for out-of-line calls.
20019 Here is the resulting program:
20021 @smallexample
20022 @group
20023 with Interfaces; use Interfaces;
20024 with Ada.Text_IO; use Ada.Text_IO;
20025 with System.Machine_Code; use System.Machine_Code;
20026 procedure Increment_2 is
20028    function Incr (Value : Unsigned_32) return Unsigned_32 is
20029       Result : Unsigned_32;
20030    begin
20031       Asm ("incl %0",
20032            Inputs  => Unsigned_32'Asm_Input ("a", Value),
20033            Outputs => Unsigned_32'Asm_Output ("=a", Result));
20034       return Result;
20035    end Incr;
20036    pragma Inline (Increment);
20038    Value : Unsigned_32;
20040 begin
20041    Value := 5;
20042    Put_Line ("Value before is" & Value'Img);
20043    Value := Increment (Value);
20044    Put_Line ("Value after is" & Value'Img);
20045 end Increment_2;
20046 @end group
20047 @end smallexample
20049 Compile the program with both optimization (@code{-O2}) and inlining
20050 enabled (@option{-gnatpn} instead of @option{-gnatp}).
20052 The @code{Incr} function is still compiled as usual, but at the
20053 point in @code{Increment} where our function used to be called:
20055 @smallexample
20056 @group
20057 pushl %edi
20058 call _increment__incr.1
20059 @end group
20060 @end smallexample
20062 @noindent
20063 the code for the function body directly appears:
20065 @smallexample
20066 @group
20067 movl %esi,%eax
20068 #APP
20069    incl %eax
20070 #NO_APP
20071    movl %eax,%edx
20072 @end group
20073 @end smallexample
20075 @noindent
20076 thus saving the overhead of stack frame setup and an out-of-line call.
20078 @c ---------------------------------------------------------------------------
20079 @node Other Asm Functionality
20080 @section Other @code{Asm} Functionality
20082 @noindent
20083 This section describes two important parameters to the @code{Asm} procedure: @code{Clobber}, which identifies register usage; and @code{Volatile}, which inhibits unwanted optimizations.
20085 @menu
20086 * The Clobber Parameter::
20087 * The Volatile Parameter::
20088 @end menu
20090 @c ---------------------------------------------------------------------------
20091 @node The Clobber Parameter
20092 @subsection The @code{Clobber} Parameter
20094 @noindent
20095 One of the dangers of intermixing assembly language and a compiled language such as Ada is
20096 that the compiler needs to be aware of which registers are being used by the assembly code.
20097 In some cases, such as the earlier examples, the constraint string is sufficient to
20098 indicate register usage (e.g. "a" for the eax register).  But more generally, the
20099 compiler needs an explicit identification of the registers that are used by the Inline
20100 Assembly statements.
20102 Using a register that the compiler doesn't know about
20103 could be a side effect of an instruction (like @code{mull}
20104 storing its result in both eax and edx).
20105 It can also arise from explicit register usage in your
20106 assembly code; for example:
20107 @smallexample
20108 @group
20109 Asm ("movl %0, %%ebx" & LF & HT &
20110      "movl %%ebx, %1",
20111      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
20112      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
20113 @end group
20114 @end smallexample
20115 @noindent
20116 where the compiler (since it does not analyze the @code{Asm} template string)
20117 does not know you are using the ebx register.
20119 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
20120 to identify the registers that will be used by your assembly code:
20122 @smallexample
20123 @group
20124 Asm ("movl %0, %%ebx" & LF & HT &
20125      "movl %%ebx, %1",
20126      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
20127      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
20128      Clobber => "ebx");
20129 @end group
20130 @end smallexample
20132 The Clobber parameter is a static string expression specifying the
20133 register(s) you are using.  Note that register names are @emph{not} prefixed by a percent sign.
20134 Also, if more than one register is used then their names are separated by commas; e.g., @code{"eax, ebx"}
20136 The @code{Clobber} parameter has several additional uses:
20137 @enumerate
20138 @item Use the "register" name @code{cc} to indicate that flags might have changed
20139 @item Use the "register" name @code{memory} if you changed a memory location
20140 @end enumerate
20142 @c ---------------------------------------------------------------------------
20143 @node The Volatile Parameter
20144 @subsection The @code{Volatile} Parameter
20145 @cindex Volatile parameter
20147 @noindent
20148 Compiler optimizations in the presence of Inline Assembler may sometimes have unwanted effects.
20149 For example, when
20150 an @code{Asm} invocation with an input variable is inside a loop, the compiler might move
20151 the loading of the input variable outside the loop, regarding it as a
20152 one-time initialization.
20154 If this effect is not desired, you can disable such optimizations by setting the
20155 @code{Volatile} parameter to @code{True}; for example:
20157 @smallexample
20158 @group
20159 Asm ("movl %0, %%ebx" & LF & HT &
20160      "movl %%ebx, %1",
20161      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
20162      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
20163      Clobber  => "ebx",
20164      Volatile => True);
20165 @end group
20166 @end smallexample
20168 By default, @code{Volatile} is set to @code{False} unless there is no @code{Outputs}
20169 parameter.
20171 Although setting @code{Volatile} to @code{True} prevents unwanted optimizations,
20172 it will also disable other optimizations that might be important for efficiency.
20173 In general, you should set @code{Volatile} to @code{True} only if the compiler's
20174 optimizations have created problems.
20176 @c ---------------------------------------------------------------------------
20177 @node A Complete Example
20178 @section A Complete Example
20180 @noindent
20181 This section contains a complete program illustrating a realistic usage of GNAT's Inline Assembler
20182 capabilities.  It comprises a main procedure @code{Check_CPU} and a package @code{Intel_CPU}.
20183 The package declares a collection of functions that detect the properties of the 32-bit
20184 x86 processor that is running the program.  The main procedure invokes these functions
20185 and displays the information.
20187 The Intel_CPU package could be enhanced by adding functions to
20188 detect the type of x386 co-processor, the processor caching options and
20189 special operations such as the SIMD extensions.
20191 Although the Intel_CPU package has been written for 32-bit Intel
20192 compatible CPUs, it is OS neutral. It has been tested on DOS,
20193 Windows/NT and Linux.
20195 @menu
20196 * Check_CPU Procedure::
20197 * Intel_CPU Package Specification::
20198 * Intel_CPU Package Body::
20199 @end menu
20201 @c ---------------------------------------------------------------------------
20202 @node Check_CPU Procedure
20203 @subsection @code{Check_CPU} Procedure
20204 @cindex Check_CPU procedure
20206 @smallexample
20207 ---------------------------------------------------------------------
20208 --                                                                 --
20209 --  Uses the Intel_CPU package to identify the CPU the program is  --
20210 --  running on, and some of the features it supports.              --
20211 --                                                                 --
20212 ---------------------------------------------------------------------
20214 with Intel_CPU;                     --  Intel CPU detection functions
20215 with Ada.Text_IO;                   --  Standard text I/O
20216 with Ada.Command_Line;              --  To set the exit status
20218 procedure Check_CPU is
20220    Type_Found : Boolean := False;
20221    --  Flag to indicate that processor was identified
20223    Features   : Intel_CPU.Processor_Features;
20224    --  The processor features
20226    Signature  : Intel_CPU.Processor_Signature;
20227    --  The processor type signature
20229 begin
20231    -----------------------------------
20232    --  Display the program banner.  --
20233    -----------------------------------
20235    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
20236                          ": check Intel CPU version and features, v1.0");
20237    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
20238    Ada.Text_IO.New_Line;
20240    -----------------------------------------------------------------------
20241    --  We can safely start with the assumption that we are on at least  --
20242    --  a x386 processor. If the CPUID instruction is present, then we   --
20243    --  have a later processor type.                                     --
20244    -----------------------------------------------------------------------
20246    if Intel_CPU.Has_CPUID = False then
20248       --  No CPUID instruction, so we assume this is indeed a x386
20249       --  processor. We can still check if it has a FP co-processor.
20250       if Intel_CPU.Has_FPU then
20251          Ada.Text_IO.Put_Line
20252            ("x386-type processor with a FP co-processor");
20253       else
20254          Ada.Text_IO.Put_Line
20255            ("x386-type processor without a FP co-processor");
20256       end if;  --  check for FPU
20258       --  Program done
20259       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
20260       return;
20262    end if;  --  check for CPUID
20264    -----------------------------------------------------------------------
20265    --  If CPUID is supported, check if this is a true Intel processor,  --
20266    --  if it is not, display a warning.                                 --
20267    -----------------------------------------------------------------------
20269    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
20270       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
20271       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
20272    end if;  --  check if Intel
20274    ----------------------------------------------------------------------
20275    --  With the CPUID instruction present, we can assume at least a    --
20276    --  x486 processor. If the CPUID support level is < 1 then we have  --
20277    --  to leave it at that.                                            --
20278    ----------------------------------------------------------------------
20280    if Intel_CPU.CPUID_Level < 1 then
20282       --  Ok, this is a x486 processor. we still can get the Vendor ID
20283       Ada.Text_IO.Put_Line ("x486-type processor");
20284       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
20286       --  We can also check if there is a FPU present
20287       if Intel_CPU.Has_FPU then
20288          Ada.Text_IO.Put_Line ("Floating-Point support");
20289       else
20290          Ada.Text_IO.Put_Line ("No Floating-Point support");
20291       end if;  --  check for FPU
20293       --  Program done
20294       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
20295       return;
20297    end if;  --  check CPUID level
20299    ---------------------------------------------------------------------
20300    --  With a CPUID level of 1 we can use the processor signature to  --
20301    --  determine it's exact type.                                     --
20302    ---------------------------------------------------------------------
20304    Signature := Intel_CPU.Signature;
20306    ----------------------------------------------------------------------
20307    --  Ok, now we go into a lot of messy comparisons to get the        --
20308    --  processor type. For clarity, no attememt to try to optimize the --
20309    --  comparisons has been made. Note that since Intel_CPU does not   --
20310    --  support getting cache info, we cannot distinguish between P5    --
20311    --  and Celeron types yet.                                          --
20312    ----------------------------------------------------------------------
20314    --  x486SL
20315    if Signature.Processor_Type = 2#00#   and
20316      Signature.Family          = 2#0100# and
20317      Signature.Model           = 2#0100# then
20318       Type_Found := True;
20319       Ada.Text_IO.Put_Line ("x486SL processor");
20320    end if;
20322    --  x486DX2 Write-Back
20323    if Signature.Processor_Type = 2#00#   and
20324      Signature.Family          = 2#0100# and
20325      Signature.Model           = 2#0111# then
20326       Type_Found := True;
20327       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
20328    end if;
20330    --  x486DX4
20331    if Signature.Processor_Type = 2#00#   and
20332      Signature.Family          = 2#0100# and
20333      Signature.Model           = 2#1000# then
20334       Type_Found := True;
20335       Ada.Text_IO.Put_Line ("x486DX4 processor");
20336    end if;
20338    --  x486DX4 Overdrive
20339    if Signature.Processor_Type = 2#01#   and
20340      Signature.Family          = 2#0100# and
20341      Signature.Model           = 2#1000# then
20342       Type_Found := True;
20343       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
20344    end if;
20346    --  Pentium (60, 66)
20347    if Signature.Processor_Type = 2#00#   and
20348      Signature.Family          = 2#0101# and
20349      Signature.Model           = 2#0001# then
20350       Type_Found := True;
20351       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
20352    end if;
20354    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
20355    if Signature.Processor_Type = 2#00#   and
20356      Signature.Family          = 2#0101# and
20357      Signature.Model           = 2#0010# then
20358       Type_Found := True;
20359       Ada.Text_IO.Put_Line
20360         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
20361    end if;
20363    --  Pentium OverDrive (60, 66)
20364    if Signature.Processor_Type = 2#01#   and
20365      Signature.Family          = 2#0101# and
20366      Signature.Model           = 2#0001# then
20367       Type_Found := True;
20368       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
20369    end if;
20371    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
20372    if Signature.Processor_Type = 2#01#   and
20373      Signature.Family          = 2#0101# and
20374      Signature.Model           = 2#0010# then
20375       Type_Found := True;
20376       Ada.Text_IO.Put_Line
20377         ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
20378    end if;
20380    --  Pentium OverDrive processor for x486 processor-based systems
20381    if Signature.Processor_Type = 2#01#   and
20382      Signature.Family          = 2#0101# and
20383      Signature.Model           = 2#0011# then
20384       Type_Found := True;
20385       Ada.Text_IO.Put_Line
20386         ("Pentium OverDrive processor for x486 processor-based systems");
20387    end if;
20389    --  Pentium processor with MMX technology (166, 200)
20390    if Signature.Processor_Type = 2#00#   and
20391      Signature.Family          = 2#0101# and
20392      Signature.Model           = 2#0100# then
20393       Type_Found := True;
20394       Ada.Text_IO.Put_Line
20395         ("Pentium processor with MMX technology (166, 200)");
20396    end if;
20398    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
20399    if Signature.Processor_Type = 2#01#   and
20400      Signature.Family          = 2#0101# and
20401      Signature.Model           = 2#0100# then
20402       Type_Found := True;
20403       Ada.Text_IO.Put_Line
20404         ("Pentium OverDrive processor with MMX " &
20405          "technology for Pentium processor (75, 90, 100, 120, 133)");
20406    end if;
20408    --  Pentium Pro processor
20409    if Signature.Processor_Type = 2#00#   and
20410      Signature.Family          = 2#0110# and
20411      Signature.Model           = 2#0001# then
20412       Type_Found := True;
20413       Ada.Text_IO.Put_Line ("Pentium Pro processor");
20414    end if;
20416    --  Pentium II processor, model 3
20417    if Signature.Processor_Type = 2#00#   and
20418      Signature.Family          = 2#0110# and
20419      Signature.Model           = 2#0011# then
20420       Type_Found := True;
20421       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
20422    end if;
20424    --  Pentium II processor, model 5 or Celeron processor
20425    if Signature.Processor_Type = 2#00#   and
20426      Signature.Family          = 2#0110# and
20427      Signature.Model           = 2#0101# then
20428       Type_Found := True;
20429       Ada.Text_IO.Put_Line
20430         ("Pentium II processor, model 5 or Celeron processor");
20431    end if;
20433    --  Pentium Pro OverDrive processor
20434    if Signature.Processor_Type = 2#01#   and
20435      Signature.Family          = 2#0110# and
20436      Signature.Model           = 2#0011# then
20437       Type_Found := True;
20438       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
20439    end if;
20441    --  If no type recognized, we have an unknown. Display what
20442    --  we _do_ know
20443    if Type_Found = False then
20444       Ada.Text_IO.Put_Line ("Unknown processor");
20445    end if;
20447    -----------------------------------------
20448    --  Display processor stepping level.  --
20449    -----------------------------------------
20451    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
20453    ---------------------------------
20454    --  Display vendor ID string.  --
20455    ---------------------------------
20457    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
20459    ------------------------------------
20460    --  Get the processors features.  --
20461    ------------------------------------
20463    Features := Intel_CPU.Features;
20465    -----------------------------
20466    --  Check for a FPU unit.  --
20467    -----------------------------
20469    if Features.FPU = True then
20470       Ada.Text_IO.Put_Line ("Floating-Point unit available");
20471    else
20472       Ada.Text_IO.Put_Line ("no Floating-Point unit");
20473    end if;  --  check for FPU
20475    --------------------------------
20476    --  List processor features.  --
20477    --------------------------------
20479    Ada.Text_IO.Put_Line ("Supported features: ");
20481    --  Virtual Mode Extension
20482    if Features.VME = True then
20483       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
20484    end if;
20486    --  Debugging Extension
20487    if Features.DE = True then
20488       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
20489    end if;
20491    --  Page Size Extension
20492    if Features.PSE = True then
20493       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
20494    end if;
20496    --  Time Stamp Counter
20497    if Features.TSC = True then
20498       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
20499    end if;
20501    --  Model Specific Registers
20502    if Features.MSR = True then
20503       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
20504    end if;
20506    --  Physical Address Extension
20507    if Features.PAE = True then
20508       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
20509    end if;
20511    --  Machine Check Extension
20512    if Features.MCE = True then
20513       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
20514    end if;
20516    --  CMPXCHG8 instruction supported
20517    if Features.CX8 = True then
20518       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
20519    end if;
20521    --  on-chip APIC hardware support
20522    if Features.APIC = True then
20523       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
20524    end if;
20526    --  Fast System Call
20527    if Features.SEP = True then
20528       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
20529    end if;
20531    --  Memory Type Range Registers
20532    if Features.MTRR = True then
20533       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
20534    end if;
20536    --  Page Global Enable
20537    if Features.PGE = True then
20538       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
20539    end if;
20541    --  Machine Check Architecture
20542    if Features.MCA = True then
20543       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
20544    end if;
20546    --  Conditional Move Instruction Supported
20547    if Features.CMOV = True then
20548       Ada.Text_IO.Put_Line
20549         ("    CMOV   - Conditional Move Instruction Supported");
20550    end if;
20552    --  Page Attribute Table
20553    if Features.PAT = True then
20554       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
20555    end if;
20557    --  36-bit Page Size Extension
20558    if Features.PSE_36 = True then
20559       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
20560    end if;
20562    --  MMX technology supported
20563    if Features.MMX = True then
20564       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
20565    end if;
20567    --  Fast FP Save and Restore
20568    if Features.FXSR = True then
20569       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
20570    end if;
20572    ---------------------
20573    --  Program done.  --
20574    ---------------------
20576    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
20578 exception
20580    when others =>
20581       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
20582       raise;
20584 end Check_CPU;
20585 @end smallexample
20587 @c ---------------------------------------------------------------------------
20588 @node Intel_CPU Package Specification
20589 @subsection @code{Intel_CPU} Package Specification
20590 @cindex Intel_CPU package specification
20592 @smallexample
20593 -------------------------------------------------------------------------
20594 --                                                                     --
20595 --  file: intel_cpu.ads                                                --
20596 --                                                                     --
20597 --           *********************************************             --
20598 --           * WARNING: for 32-bit Intel processors only *             --
20599 --           *********************************************             --
20600 --                                                                     --
20601 --  This package contains a number of subprograms that are useful in   --
20602 --  determining the Intel x86 CPU (and the features it supports) on    --
20603 --  which the program is running.                                      --
20604 --                                                                     --
20605 --  The package is based upon the information given in the Intel       --
20606 --  Application Note AP-485: "Intel Processor Identification and the   --
20607 --  CPUID Instruction" as of April 1998. This application note can be  --
20608 --  found on www.intel.com.                                            --
20609 --                                                                     --
20610 --  It currently deals with 32-bit processors only, will not detect    --
20611 --  features added after april 1998, and does not guarantee proper     --
20612 --  results on Intel-compatible processors.                            --
20613 --                                                                     --
20614 --  Cache info and x386 fpu type detection are not supported.          --
20615 --                                                                     --
20616 --  This package does not use any privileged instructions, so should   --
20617 --  work on any OS running on a 32-bit Intel processor.                --
20618 --                                                                     --
20619 -------------------------------------------------------------------------
20621 with Interfaces;             use Interfaces;
20622 --  for using unsigned types
20624 with System.Machine_Code;    use System.Machine_Code;
20625 --  for using inline assembler code
20627 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
20628 --  for inserting control characters
20630 package Intel_CPU is
20632    ----------------------
20633    --  Processor bits  --
20634    ----------------------
20636    subtype Num_Bits is Natural range 0 .. 31;
20637    --  the number of processor bits (32)
20639    --------------------------
20640    --  Processor register  --
20641    --------------------------
20643    --  define a processor register type for easy access to
20644    --  the individual bits
20646    type Processor_Register is array (Num_Bits) of Boolean;
20647    pragma Pack (Processor_Register);
20648    for Processor_Register'Size use 32;
20650    -------------------------
20651    --  Unsigned register  --
20652    -------------------------
20654    --  define a processor register type for easy access to
20655    --  the individual bytes
20657    type Unsigned_Register is
20658       record
20659          L1 : Unsigned_8;
20660          H1 : Unsigned_8;
20661          L2 : Unsigned_8;
20662          H2 : Unsigned_8;
20663       end record;
20665    for Unsigned_Register use
20666       record
20667          L1 at 0 range  0 ..  7;
20668          H1 at 0 range  8 .. 15;
20669          L2 at 0 range 16 .. 23;
20670          H2 at 0 range 24 .. 31;
20671       end record;
20673    for Unsigned_Register'Size use 32;
20675    ---------------------------------
20676    --  Intel processor vendor ID  --
20677    ---------------------------------
20679    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
20680    --  indicates an Intel manufactured processor
20682    ------------------------------------
20683    --  Processor signature register  --
20684    ------------------------------------
20686    --  a register type to hold the processor signature
20688    type Processor_Signature is
20689       record
20690          Stepping       : Natural range 0 .. 15;
20691          Model          : Natural range 0 .. 15;
20692          Family         : Natural range 0 .. 15;
20693          Processor_Type : Natural range 0 .. 3;
20694          Reserved       : Natural range 0 .. 262143;
20695       end record;
20697    for Processor_Signature use
20698       record
20699          Stepping       at 0 range  0 ..  3;
20700          Model          at 0 range  4 ..  7;
20701          Family         at 0 range  8 .. 11;
20702          Processor_Type at 0 range 12 .. 13;
20703          Reserved       at 0 range 14 .. 31;
20704       end record;
20706    for Processor_Signature'Size use 32;
20708    -----------------------------------
20709    --  Processor features register  --
20710    -----------------------------------
20712    --  a processor register to hold the processor feature flags
20714    type Processor_Features is
20715       record
20716          FPU    : Boolean;                --  floating point unit on chip
20717          VME    : Boolean;                --  virtual mode extension
20718          DE     : Boolean;                --  debugging extension
20719          PSE    : Boolean;                --  page size extension
20720          TSC    : Boolean;                --  time stamp counter
20721          MSR    : Boolean;                --  model specific registers
20722          PAE    : Boolean;                --  physical address extension
20723          MCE    : Boolean;                --  machine check extension
20724          CX8    : Boolean;                --  cmpxchg8 instruction
20725          APIC   : Boolean;                --  on-chip apic hardware
20726          Res_1  : Boolean;                --  reserved for extensions
20727          SEP    : Boolean;                --  fast system call
20728          MTRR   : Boolean;                --  memory type range registers
20729          PGE    : Boolean;                --  page global enable
20730          MCA    : Boolean;                --  machine check architecture
20731          CMOV   : Boolean;                --  conditional move supported
20732          PAT    : Boolean;                --  page attribute table
20733          PSE_36 : Boolean;                --  36-bit page size extension
20734          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
20735          MMX    : Boolean;                --  MMX technology supported
20736          FXSR   : Boolean;                --  fast FP save and restore
20737          Res_3  : Natural range 0 .. 127; --  reserved for extensions
20738       end record;
20740    for Processor_Features use
20741       record
20742          FPU    at 0 range  0 ..  0;
20743          VME    at 0 range  1 ..  1;
20744          DE     at 0 range  2 ..  2;
20745          PSE    at 0 range  3 ..  3;
20746          TSC    at 0 range  4 ..  4;
20747          MSR    at 0 range  5 ..  5;
20748          PAE    at 0 range  6 ..  6;
20749          MCE    at 0 range  7 ..  7;
20750          CX8    at 0 range  8 ..  8;
20751          APIC   at 0 range  9 ..  9;
20752          Res_1  at 0 range 10 .. 10;
20753          SEP    at 0 range 11 .. 11;
20754          MTRR   at 0 range 12 .. 12;
20755          PGE    at 0 range 13 .. 13;
20756          MCA    at 0 range 14 .. 14;
20757          CMOV   at 0 range 15 .. 15;
20758          PAT    at 0 range 16 .. 16;
20759          PSE_36 at 0 range 17 .. 17;
20760          Res_2  at 0 range 18 .. 22;
20761          MMX    at 0 range 23 .. 23;
20762          FXSR   at 0 range 24 .. 24;
20763          Res_3  at 0 range 25 .. 31;
20764       end record;
20766    for Processor_Features'Size use 32;
20768    -------------------
20769    --  Subprograms  --
20770    -------------------
20772    function Has_FPU return Boolean;
20773    --  return True if a FPU is found
20774    --  use only if CPUID is not supported
20776    function Has_CPUID return Boolean;
20777    --  return True if the processor supports the CPUID instruction
20779    function CPUID_Level return Natural;
20780    --  return the CPUID support level (0, 1 or 2)
20781    --  can only be called if the CPUID instruction is supported
20783    function Vendor_ID return String;
20784    --  return the processor vendor identification string
20785    --  can only be called if the CPUID instruction is supported
20787    function Signature return Processor_Signature;
20788    --  return the processor signature
20789    --  can only be called if the CPUID instruction is supported
20791    function Features return Processor_Features;
20792    --  return the processors features
20793    --  can only be called if the CPUID instruction is supported
20795 private
20797    ------------------------
20798    --  EFLAGS bit names  --
20799    ------------------------
20801    ID_Flag : constant Num_Bits := 21;
20802    --  ID flag bit
20804 end Intel_CPU;
20805 @end smallexample
20807 @c ---------------------------------------------------------------------------
20808 @node Intel_CPU Package Body
20809 @subsection @code{Intel_CPU} Package Body
20810 @cindex Intel_CPU package body
20812 @smallexample
20813 package body Intel_CPU is
20815    ---------------------------
20816    --  Detect FPU presence  --
20817    ---------------------------
20819    --  There is a FPU present if we can set values to the FPU Status
20820    --  and Control Words.
20822    function Has_FPU return Boolean is
20824       Register : Unsigned_16;
20825       --  processor register to store a word
20827    begin
20829       --  check if we can change the status word
20830       Asm (
20832            --  the assembler code
20833            "finit"              & LF & HT &    --  reset status word
20834            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
20835            "fnstsw %0"          & LF & HT &    --  save status word
20836            "movw %%ax, %0",                    --  store status word
20838            --  output stored in Register
20839            --  register must be a memory location
20840            Outputs => Unsigned_16'Asm_output ("=m", Register),
20842            --  tell compiler that we used eax
20843            Clobber => "eax");
20845       --  if the status word is zero, there is no FPU
20846       if Register = 0 then
20847          return False;   --  no status word
20848       end if;  --  check status word value
20850       --  check if we can get the control word
20851       Asm (
20853            --  the assembler code
20854            "fnstcw %0",   --  save the control word
20856            --  output into Register
20857            --  register must be a memory location
20858            Outputs => Unsigned_16'Asm_output ("=m", Register));
20860       --  check the relevant bits
20861       if (Register and 16#103F#) /= 16#003F# then
20862          return False;   --  no control word
20863       end if;  --  check control word value
20865       --  FPU found
20866       return True;
20868    end Has_FPU;
20870    --------------------------------
20871    --  Detect CPUID instruction  --
20872    --------------------------------
20874    --  The processor supports the CPUID instruction if it is possible
20875    --  to change the value of ID flag bit in the EFLAGS register.
20877    function Has_CPUID return Boolean is
20879       Original_Flags, Modified_Flags : Processor_Register;
20880       --  EFLAG contents before and after changing the ID flag
20882    begin
20884       --  try flipping the ID flag in the EFLAGS register
20885       Asm (
20887            --  the assembler code
20888            "pushfl"               & LF & HT &     --  push EFLAGS on stack
20889            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
20890            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
20891            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
20892            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
20893            "popfl"                & LF & HT &     --  load EFLAGS register
20894            "pushfl"               & LF & HT &     --  push EFLAGS on stack
20895            "pop %1",                              --  save EFLAGS content
20897            --  output values, may be anything
20898            --  Original_Flags is %0
20899            --  Modified_Flags is %1
20900            Outputs =>
20901               (Processor_Register'Asm_output ("=g", Original_Flags),
20902                Processor_Register'Asm_output ("=g", Modified_Flags)),
20904            --  tell compiler eax is destroyed
20905            Clobber => "eax");
20907       --  check if CPUID is supported
20908       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
20909          return True;   --  ID flag was modified
20910       else
20911          return False;  --  ID flag unchanged
20912       end if;  --  check for CPUID
20914    end Has_CPUID;
20916    -------------------------------
20917    --  Get CPUID support level  --
20918    -------------------------------
20920    function CPUID_Level return Natural is
20922       Level : Unsigned_32;
20923       --  returned support level
20925    begin
20927       --  execute CPUID, storing the results in the Level register
20928       Asm (
20930            --  the assembler code
20931            "cpuid",    --  execute CPUID
20933            --  zero is stored in eax
20934            --  returning the support level in eax
20935            Inputs => Unsigned_32'Asm_input ("a", 0),
20937            --  eax is stored in Level
20938            Outputs => Unsigned_32'Asm_output ("=a", Level),
20940            --  tell compiler ebx, ecx and edx registers are destroyed
20941            Clobber => "ebx, ecx, edx");
20943       --  return the support level
20944       return Natural (Level);
20946    end CPUID_Level;
20948    --------------------------------
20949    --  Get CPU Vendor ID String  --
20950    --------------------------------
20952    --  The vendor ID string is returned in the ebx, ecx and edx register
20953    --  after executing the CPUID instruction with eax set to zero.
20954    --  In case of a true Intel processor the string returned is
20955    --  "GenuineIntel"
20957    function Vendor_ID return String is
20959       Ebx, Ecx, Edx : Unsigned_Register;
20960       --  registers containing the vendor ID string
20962       Vendor_ID : String (1 .. 12);
20963       -- the vendor ID string
20965    begin
20967       --  execute CPUID, storing the results in the processor registers
20968       Asm (
20970            --  the assembler code
20971            "cpuid",    --  execute CPUID
20973            --  zero stored in eax
20974            --  vendor ID string returned in ebx, ecx and edx
20975            Inputs => Unsigned_32'Asm_input ("a", 0),
20977            --  ebx is stored in Ebx
20978            --  ecx is stored in Ecx
20979            --  edx is stored in Edx
20980            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
20981                        Unsigned_Register'Asm_output ("=c", Ecx),
20982                        Unsigned_Register'Asm_output ("=d", Edx)));
20984       --  now build the vendor ID string
20985       Vendor_ID( 1) := Character'Val (Ebx.L1);
20986       Vendor_ID( 2) := Character'Val (Ebx.H1);
20987       Vendor_ID( 3) := Character'Val (Ebx.L2);
20988       Vendor_ID( 4) := Character'Val (Ebx.H2);
20989       Vendor_ID( 5) := Character'Val (Edx.L1);
20990       Vendor_ID( 6) := Character'Val (Edx.H1);
20991       Vendor_ID( 7) := Character'Val (Edx.L2);
20992       Vendor_ID( 8) := Character'Val (Edx.H2);
20993       Vendor_ID( 9) := Character'Val (Ecx.L1);
20994       Vendor_ID(10) := Character'Val (Ecx.H1);
20995       Vendor_ID(11) := Character'Val (Ecx.L2);
20996       Vendor_ID(12) := Character'Val (Ecx.H2);
20998       --  return string
20999       return Vendor_ID;
21001    end Vendor_ID;
21003    -------------------------------
21004    --  Get processor signature  --
21005    -------------------------------
21007    function Signature return Processor_Signature is
21009       Result : Processor_Signature;
21010       --  processor signature returned
21012    begin
21014       --  execute CPUID, storing the results in the Result variable
21015       Asm (
21017            --  the assembler code
21018            "cpuid",    --  execute CPUID
21020            --  one is stored in eax
21021            --  processor signature returned in eax
21022            Inputs => Unsigned_32'Asm_input ("a", 1),
21024            --  eax is stored in Result
21025            Outputs => Processor_Signature'Asm_output ("=a", Result),
21027            --  tell compiler that ebx, ecx and edx are also destroyed
21028            Clobber => "ebx, ecx, edx");
21030       --  return processor signature
21031       return Result;
21033    end Signature;
21035    ------------------------------
21036    --  Get processor features  --
21037    ------------------------------
21039    function Features return Processor_Features is
21041       Result : Processor_Features;
21042       --  processor features returned
21044    begin
21046       --  execute CPUID, storing the results in the Result variable
21047       Asm (
21049            --  the assembler code
21050            "cpuid",    --  execute CPUID
21052            --  one stored in eax
21053            --  processor features returned in edx
21054            Inputs => Unsigned_32'Asm_input ("a", 1),
21056            --  edx is stored in Result
21057            Outputs => Processor_Features'Asm_output ("=d", Result),
21059            --  tell compiler that ebx and ecx are also destroyed
21060            Clobber => "ebx, ecx");
21062       --  return processor signature
21063       return Result;
21065    end Features;
21067 end Intel_CPU;
21068 @end smallexample
21069 @c END OF INLINE ASSEMBLER CHAPTER
21070 @c ===============================
21072 @ifset wnt
21073 @node Microsoft Windows Topics
21074 @chapter Microsoft Windows Topics
21075 @cindex Windows NT
21076 @cindex Windows 95
21077 @cindex Windows 98
21079 @noindent
21080 This chapter describes topics that are specific to the Microsoft Windows
21081 platforms (NT, 95 and 98).
21083 @menu
21084 * Using GNAT on Windows::
21085 * GNAT Setup Tool::
21086 * CONSOLE and WINDOWS subsystems::
21087 * Temporary Files::
21088 * Mixed-Language Programming on Windows::
21089 * Windows Calling Conventions::
21090 * Introduction to Dynamic Link Libraries (DLLs)::
21091 * Using DLLs with GNAT::
21092 * Building DLLs with GNAT::
21093 * GNAT and Windows Resources::
21094 * Debugging a DLL::
21095 * GNAT and COM/DCOM Objects::
21096 @end menu
21098 @node Using GNAT on Windows
21099 @section Using GNAT on Windows
21101 @noindent
21102 One of the strengths of the GNAT technology is that its tool set
21103 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
21104 @code{gdb} debugger, etc.) is used in the same way regardless of the
21105 platform.
21107 On Windows this tool set is complemented by a number of Microsoft-specific
21108 tools that have been provided to facilitate interoperability with Windows
21109 when this is required. With these tools:
21111 @itemize @bullet
21113 @item
21114 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
21115 subsystems.
21117 @item
21118 You can use any Dynamically Linked Library (DLL) in your Ada code (both
21119 relocatable and non-relocatable DLLs are supported).
21121 @item
21122 You can build Ada DLLs for use in other applications. These applications
21123 can be written in a language other than Ada (e.g., C, C++, etc). Again both
21124 relocatable and non-relocatable Ada DLLs are supported.
21126 @item
21127 You can include Windows resources in your Ada application.
21129 @item
21130 You can use or create COM/DCOM objects.
21131 @end itemize
21133 @noindent
21134 Immediately below are listed all known general GNAT-for-Windows restrictions.
21135 Other restrictions about specific features like Windows Resources and DLLs
21136 are listed in separate sections below.
21138 @itemize @bullet
21140 @item
21141 It is not possible to use @code{GetLastError} and @code{SetLastError}
21142 when tasking, protected records, or exceptions are used. In these
21143 cases, in order to implement Ada semantics, the GNAT run-time system
21144 calls certain Win32 routines that set the last error variable to 0 upon
21145 success. It should be possible to use @code{GetLastError} and
21146 @code{SetLastError} when tasking, protected record, and exception
21147 features are not used, but it is not guaranteed to work.
21148 @end itemize
21150 @node GNAT Setup Tool
21151 @section GNAT Setup Tool
21152 @cindex GNAT Setup Tool
21153 @cindex Setup Tool
21154 @cindex gnatreg
21156 @menu
21157 * Command-line arguments::
21158 * Creating a network installation of GNAT::
21159 * Registering and unregistering additional libraries::
21160 @end menu
21162 @noindent
21163 GNAT installation on Windows is using the Windows registry in order to
21164 locate proper executables and standard libraries. GNAT setup tool, called
21165 @code{gnatreg.exe}, is provided in order to display and modify GNAT-specific
21166 registry entries, allowing to create network GNAT installations, modify the
21167 locations of GNAT components, as well as register and unregister additional
21168 libraries for use with GNAT.
21170 @node Command-line arguments
21171 @subsection Command-line arguments
21173 @noindent
21174 @code{gnatreg [switches] [parameter]}
21176 @noindent
21177 Specifying no arguments causes gnatreg to display current configuration.
21179 @noindent
21180 The switches understood by gnatreg are:
21181 @table @asis
21182 @item  -h
21183        print the help message
21184 @item  -a
21185        add a standard library
21186 @item  -r
21187        remove a standard library
21188 @item  -f
21189        force creation of keys if they don't exist
21190 @item  -q
21191        be quiet/terse
21192 @end table
21194 @node Creating a network installation of GNAT
21195 @subsection Creating a network installation of GNAT
21197 @noindent
21198 Make sure the system on which GNAT is installed is accessible from the
21199 current machine.
21201 Use the command
21203 @code{@ @ @ gnatreg -f \\server\sharename\path}
21205 in order to setup the registry entries on a current machine.
21207 For example, if GNAT is installed in @file{\GNAT} directory of a share location
21208 called @file{c-drive} on a machine @file{LOKI}, the command that can be used on
21209 other machines to allow the remote use of GNAT is,
21211 @code{@ @ @ gnatreg -f \\loki\c-drive\gnat}
21213 Remember to also add @file{\\loki\c-drive\gnat\bin} in front of your PATH variable.
21215 Be aware that every compilation using the network installation results in the
21216 transfer of large amounts of data across the network and may cause serious
21217 performance penalty.
21219 @node Registering and unregistering additional libraries
21220 @subsection Registering and unregistering additional libraries
21222 @noindent
21223 To register a standard library use a command:
21225 @code{@ @ @ gnatreg -a <library_name>=<path>}
21227 For example:
21229 @code{@ @ @ gnatreg -a WIN32ADA=c:\Win32Ada}
21231 The libraries registered in this manner will be treated like standard libraries
21232 by the compiler (i.e. they don't have to be specified in -I and -l switches to
21233 various GNAT tools).
21235 To unregister a library, enter
21236 @code{   gnatreg -r <library_name>}
21238 e.g.,
21239 @code{   gnatreg -r WIN32ADA}
21241 @node CONSOLE and WINDOWS subsystems
21242 @section CONSOLE and WINDOWS subsystems
21243 @cindex CONSOLE Subsystem
21244 @cindex WINDOWS Subsystem
21245 @cindex -mwindows
21247 @noindent
21248 Under Windows there is two main subsystems. The @code{CONSOLE} subsystem
21249 (which is the default subsystem) will always create a console when
21250 launching the application. This is not something desirable when the
21251 application has a Windows GUI. To get rid of this console the
21252 application must be using the @code{WINDOWS} subsystem. To do so
21253 the @code{-mwindows} linker option must be specified.
21255 @smallexample
21256 $ gnatmake winprog -largs -mwindows
21257 @end smallexample
21259 @node Temporary Files
21260 @section Temporary Files
21261 @cindex Temporary files
21263 @noindent
21264 It is possible to control where temporary files gets created by setting
21265 the TMP environment variable. The file will be created:
21267 @itemize
21268 @item Under the directory pointed to by the TMP environment variable if
21269 this directory exists.
21271 @item Under c:\temp, if the TMP environment variable is not set (or not
21272 pointing to a directory) and if this directory exists.
21274 @item Under the current working directory otherwise.
21275 @end itemize
21277 @noindent
21278 This allows you to determine exactly where the temporary
21279 file will be created. This is particularly useful in networked
21280 environments where you may not have write access to some
21281 directories.
21283 @node Mixed-Language Programming on Windows
21284 @section Mixed-Language Programming on Windows
21286 @noindent
21287 Developing pure Ada applications on Windows is no different than on
21288 other GNAT-supported platforms. However, when developing or porting an
21289 application that contains a mix of Ada and C/C++, the choice of your
21290 Windows C/C++ development environment conditions your overall
21291 interoperability strategy.
21293 If you use @code{gcc} to compile the non-Ada part of your application,
21294 there are no Windows-specific restrictions that affect the overall
21295 interoperability with your Ada code. If you plan to use
21296 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
21297 the following limitations:
21299 @itemize @bullet
21300 @item
21301 You cannot link your Ada code with an object or library generated with
21302 Microsoft tools if these use the @code{.tls} section (Thread Local
21303 Storage section) since the GNAT linker does not yet support this section.
21305 @item
21306 You cannot link your Ada code with an object or library generated with
21307 Microsoft tools if these use I/O routines other than those provided in
21308 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
21309 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
21310 libraries can cause a conflict with @code{msvcrt.dll} services. For
21311 instance Visual C++ I/O stream routines conflict with those in
21312 @code{msvcrt.dll}.
21313 @end itemize
21315 @noindent
21316 If you do want to use the Microsoft tools for your non-Ada code and hit one
21317 of the above limitations, you have two choices:
21319 @enumerate
21320 @item
21321 Encapsulate your non Ada code in a DLL to be linked with your Ada
21322 application. In this case, use the Microsoft or whatever environment to
21323 build the DLL and use GNAT to build your executable
21324 (@pxref{Using DLLs with GNAT}).
21326 @item
21327 Or you can encapsulate your Ada code in a DLL to be linked with the
21328 other part of your application. In this case, use GNAT to build the DLL
21329 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
21330 environment to build your executable.
21331 @end enumerate
21333 @node Windows Calling Conventions
21334 @section Windows Calling Conventions
21335 @findex Stdcall
21336 @findex APIENTRY
21338 @menu
21339 * C Calling Convention::
21340 * Stdcall Calling Convention::
21341 * DLL Calling Convention::
21342 @end menu
21344 @noindent
21345 When a subprogram @code{F} (caller) calls a subprogram @code{G}
21346 (callee), there are several ways to push @code{G}'s parameters on the
21347 stack and there are several possible scenarios to clean up the stack
21348 upon @code{G}'s return. A calling convention is an agreed upon software
21349 protocol whereby the responsibilities between the caller (@code{F}) and
21350 the callee (@code{G}) are clearly defined. Several calling conventions
21351 are available for Windows:
21353 @itemize @bullet
21354 @item
21355 @code{C} (Microsoft defined)
21357 @item
21358 @code{Stdcall} (Microsoft defined)
21360 @item
21361 @code{DLL} (GNAT specific)
21362 @end itemize
21364 @node C Calling Convention
21365 @subsection @code{C} Calling Convention
21367 @noindent
21368 This is the default calling convention used when interfacing to C/C++
21369 routines compiled with either @code{gcc} or Microsoft Visual C++.
21371 In the @code{C} calling convention subprogram parameters are pushed on the
21372 stack by the caller from right to left. The caller itself is in charge of
21373 cleaning up the stack after the call. In addition, the name of a routine
21374 with @code{C} calling convention is mangled by adding a leading underscore.
21376 The name to use on the Ada side when importing (or exporting) a routine
21377 with @code{C} calling convention is the name of the routine. For
21378 instance the C function:
21380 @smallexample
21381 int get_val (long);
21382 @end smallexample
21384 @noindent
21385 should be imported from Ada as follows:
21387 @smallexample
21388 @group
21389 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
21390 @b{pragma} Import (C, Get_Val, External_Name => "get_val");
21391 @end group
21392 @end smallexample
21394 @noindent
21395 Note that in this particular case the @code{External_Name} parameter could
21396 have been omitted since, when missing, this parameter is taken to be the
21397 name of the Ada entity in lower case. When the @code{Link_Name} parameter
21398 is missing, as in the above example, this parameter is set to be the
21399 @code{External_Name} with a leading underscore.
21401 When importing a variable defined in C, you should always use the @code{C}
21402 calling convention unless the object containing the variable is part of a
21403 DLL (in which case you should use the @code{DLL} calling convention,
21404 @pxref{DLL Calling Convention}).
21406 @node Stdcall Calling Convention
21407 @subsection @code{Stdcall} Calling Convention
21409 @noindent
21410 This convention, which was the calling convention used for Pascal
21411 programs, is used by Microsoft for all the routines in the Win32 API for
21412 efficiency reasons. It must be used to import any routine for which this
21413 convention was specified.
21415 In the @code{Stdcall} calling convention subprogram parameters are pushed
21416 on the stack by the caller from right to left. The callee (and not the
21417 caller) is in charge of cleaning the stack on routine exit. In addition,
21418 the name of a routine with @code{Stdcall} calling convention is mangled by
21419 adding a leading underscore (as for the @code{C} calling convention) and a
21420 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
21421 bytes) of the parameters passed to the routine.
21423 The name to use on the Ada side when importing a C routine with a
21424 @code{Stdcall} calling convention is the name of the C routine. The leading
21425 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
21426 the compiler. For instance the Win32 function:
21428 @smallexample
21429 @b{APIENTRY} int get_val (long);
21430 @end smallexample
21432 @noindent
21433 should be imported from Ada as follows:
21435 @smallexample
21436 @group
21437 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
21438 @b{pragma} Import (Stdcall, Get_Val);
21439 --  @i{On the x86 a long is 4 bytes, so the Link_Name is }"_get_val@@4"
21440 @end group
21441 @end smallexample
21443 @noindent
21444 As for the @code{C} calling convention, when the @code{External_Name}
21445 parameter is missing, it is taken to be the name of the Ada entity in lower
21446 case. If instead of writing the above import pragma you write:
21448 @smallexample
21449 @group
21450 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
21451 @b{pragma} Import (Stdcall, Get_Val, External_Name => "retrieve_val");
21452 @end group
21453 @end smallexample
21455 @noindent
21456 then the imported routine is @code{_retrieve_val@@4}. However, if instead
21457 of specifying the @code{External_Name} parameter you specify the
21458 @code{Link_Name} as in the following example:
21460 @smallexample
21461 @group
21462 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
21463 @b{pragma} Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
21464 @end group
21465 @end smallexample
21467 @noindent
21468 then the imported routine is @code{retrieve_val@@4}, that is, there is no
21469 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
21470 added at the end of the @code{Link_Name} by the compiler.
21472 @noindent
21473 Note, that in some special cases a DLL's entry point name lacks a trailing
21474 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
21475 The @code{gnatdll} tool, which creates the import library for the DLL, is able
21476 to handle those cases (see the description of the switches in
21477 @pxref{Using gnatdll} section).
21479 @node DLL Calling Convention
21480 @subsection @code{DLL} Calling Convention
21482 @noindent
21483 This convention, which is GNAT-specific, must be used when you want to
21484 import in Ada a variables defined in a DLL. For functions and procedures
21485 this convention is equivalent to the @code{Stdcall} convention. As an
21486 example, if a DLL contains a variable defined as:
21488 @smallexample
21489 int my_var;
21490 @end smallexample
21492 @noindent
21493 then, to access this variable from Ada you should write:
21495 @smallexample
21496 @group
21497 My_Var : Interfaces.C.int;
21498 @b{pragma} Import (DLL, My_Var);
21499 @end group
21500 @end smallexample
21502 The remarks concerning the @code{External_Name} and @code{Link_Name}
21503 parameters given in the previous sections equally apply to the @code{DLL}
21504 calling convention.
21506 @node Introduction to Dynamic Link Libraries (DLLs)
21507 @section Introduction to Dynamic Link Libraries (DLLs)
21508 @findex DLL
21510 @noindent
21511 A Dynamically Linked Library (DLL) is a library that can be shared by
21512 several applications running under Windows. A DLL can contain any number of
21513 routines and variables.
21515 One advantage of DLLs is that you can change and enhance them without
21516 forcing all the applications that depend on them to be relinked or
21517 recompiled. However, you should be aware than all calls to DLL routines are
21518 slower since, as you will understand below, such calls are indirect.
21520 To illustrate the remainder of this section, suppose that an application
21521 wants to use the services of a DLL @file{API.dll}. To use the services
21522 provided by @file{API.dll} you must statically link against an import
21523 library which contains a jump table with an entry for each routine and
21524 variable exported by the DLL. In the Microsoft world this import library is
21525 called @file{API.lib}. When using GNAT this import library is called either
21526 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
21528 After you have statically linked your application with the import library
21529 and you run your application, here is what happens:
21531 @enumerate
21532 @item
21533 Your application is loaded into memory.
21535 @item
21536 The DLL @file{API.dll} is mapped into the address space of your
21537 application. This means that:
21539 @itemize @bullet
21540 @item
21541 The DLL will use the stack of the calling thread.
21543 @item
21544 The DLL will use the virtual address space of the calling process.
21546 @item
21547 The DLL will allocate memory from the virtual address space of the calling
21548 process.
21550 @item
21551 Handles (pointers) can be safely exchanged between routines in the DLL
21552 routines and routines in the application using the DLL.
21553 @end itemize
21555 @item
21556 The entries in the @file{libAPI.a} or @file{API.lib} jump table which is
21557 part of your application are initialized with the addresses of the routines
21558 and variables in @file{API.dll}.
21560 @item
21561 If present in @file{API.dll}, routines @code{DllMain} or
21562 @code{DllMainCRTStartup} are invoked. These routines typically contain
21563 the initialization code needed for the well-being of the routines and
21564 variables exported by the DLL.
21565 @end enumerate
21567 @noindent
21568 There is an additional point which is worth mentioning. In the Windows
21569 world there are two kind of DLLs: relocatable and non-relocatable
21570 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
21571 in the target application address space. If the addresses of two
21572 non-relocatable DLLs overlap and these happen to be used by the same
21573 application, a conflict will occur and the application will run
21574 incorrectly. Hence, when possible, it is always preferable to use and
21575 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
21576 supported by GNAT.
21578 As a side note, an interesting difference between Microsoft DLLs and
21579 Unix shared libraries, is the fact that on most Unix systems all public
21580 routines are exported by default in a Unix shared library, while under
21581 Windows the exported routines must be listed explicitly in a definition
21582 file (@pxref{The Definition File}).
21584 @node Using DLLs with GNAT
21585 @section Using DLLs with GNAT
21587 @menu
21588 * Creating an Ada Spec for the DLL Services::
21589 * Creating an Import Library::
21590 @end menu
21592 @noindent
21593 To use the services of a DLL, say @file{API.dll}, in your Ada application
21594 you must have:
21596 @enumerate
21597 @item
21598 The Ada spec for the routines and/or variables you want to access in
21599 @file{API.dll}. If not available this Ada spec must be built from the C/C++
21600 header files provided with the DLL.
21602 @item
21603 The import library (@file{libAPI.a} or @file{API.lib}). As previously
21604 mentioned an import library is a statically linked library containing the
21605 import table which will be filled at load time to point to the actual
21606 @file{API.dll} routines. Sometimes you don't have an import library for the
21607 DLL you want to use. The following sections will explain how to build one.
21609 @item
21610 The actual DLL, @file{API.dll}.
21611 @end enumerate
21613 @noindent
21614 Once you have all the above, to compile an Ada application that uses the
21615 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
21616 you simply issue the command
21618 @smallexample
21619 $ gnatmake my_ada_app -largs -lAPI
21620 @end smallexample
21622 @noindent
21623 The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
21624 tells the GNAT linker to look first for a library named @file{API.lib}
21625 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
21626 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
21627 contains the following pragma
21629 @smallexample
21630 @b{pragma} Linker_Options ("-lAPI");
21631 @end smallexample
21633 @noindent
21634 you do not have to add @code{-largs -lAPI} at the end of the @code{gnatmake}
21635 command.
21637 If any one of the items above is missing you will have to create it
21638 yourself. The following sections explain how to do so using as an
21639 example a fictitious DLL called @file{API.dll}.
21641 @node Creating an Ada Spec for the DLL Services
21642 @subsection Creating an Ada Spec for the DLL Services
21644 @noindent
21645 A DLL typically comes with a C/C++ header file which provides the
21646 definitions of the routines and variables exported by the DLL. The Ada
21647 equivalent of this header file is a package spec that contains definitions
21648 for the imported entities. If the DLL you intend to use does not come with
21649 an Ada spec you have to generate one such spec yourself. For example if
21650 the header file of @file{API.dll} is a file @file{api.h} containing the
21651 following two definitions:
21653 @smallexample
21654 @group
21655 @cartouche
21656 int some_var;
21657 int get (char *);
21658 @end cartouche
21659 @end group
21660 @end smallexample
21662 @noindent
21663 then the equivalent Ada spec could be:
21665 @smallexample
21666 @group
21667 @cartouche
21668 @b{with} Interfaces.C.Strings;
21669 @b{package} API @b{is}
21670    @b{use} Interfaces;
21672    Some_Var : C.int;
21673    @b{function} Get (Str : C.Strings.Chars_Ptr) @b{return} C.int;
21675 @b{private}
21676    @b{pragma} Import (C, Get);
21677    @b{pragma} Import (DLL, Some_Var);
21678 @b{end} API;
21679 @end cartouche
21680 @end group
21681 @end smallexample
21683 @noindent
21684 Note that a variable is @strong{always imported with a DLL convention}. A
21685 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
21686 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
21687 (@pxref{Windows Calling Conventions}).
21689 @node Creating an Import Library
21690 @subsection Creating an Import Library
21691 @cindex Import library
21693 @menu
21694 * The Definition File::
21695 * GNAT-Style Import Library::
21696 * Microsoft-Style Import Library::
21697 @end menu
21699 @noindent
21700 If a Microsoft-style import library @file{API.lib} or a GNAT-style
21701 import library @file{libAPI.a} is available with @file{API.dll} you
21702 can skip this section. Otherwise read on.
21704 @node The Definition File
21705 @subsubsection The Definition File
21706 @cindex Definition file
21707 @findex .def
21709 @noindent
21710 As previously mentioned, and unlike Unix systems, the list of symbols
21711 that are exported from a DLL must be provided explicitly in Windows.
21712 The main goal of a definition file is precisely that: list the symbols
21713 exported by a DLL. A definition file (usually a file with a @code{.def}
21714 suffix) has the following structure:
21716 @smallexample
21717 @group
21718 @cartouche
21719 [LIBRARY @i{name}]
21720 [DESCRIPTION @i{string}]
21721 EXPORTS
21722    @i{symbol1}
21723    @i{symbol2}
21724    ...
21725 @end cartouche
21726 @end group
21727 @end smallexample
21729 @table @code
21730 @item LIBRARY @i{name}
21731 This section, which is optional, gives the name of the DLL.
21733 @item DESCRIPTION @i{string}
21734 This section, which is optional, gives a description string that will be
21735 embedded in the import library.
21737 @item EXPORTS
21738 This section gives the list of exported symbols (procedures, functions or
21739 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
21740 section of @file{API.def} looks like:
21742 @smallexample
21743 @group
21744 @cartouche
21745 EXPORTS
21746    some_var
21747    get
21748 @end cartouche
21749 @end group
21750 @end smallexample
21751 @end table
21753 @noindent
21754 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
21755 (@pxref{Windows Calling Conventions}) for a Stdcall
21756 calling convention function in the exported symbols list.
21758 @noindent
21759 There can actually be other sections in a definition file, but these
21760 sections are not relevant to the discussion at hand.
21762 @node GNAT-Style Import Library
21763 @subsubsection GNAT-Style Import Library
21765 @noindent
21766 To create a static import library from @file{API.dll} with the GNAT tools
21767 you should proceed as follows:
21769 @enumerate
21770 @item
21771 Create the definition file @file{API.def} (@pxref{The Definition File}).
21772 For that use the @code{dll2def} tool as follows:
21774 @smallexample
21775 $ dll2def API.dll > API.def
21776 @end smallexample
21778 @noindent
21779 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
21780 to standard output the list of entry points in the DLL. Note that if
21781 some routines in the DLL have the @code{Stdcall} convention
21782 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
21783 suffix then you'll have to edit @file{api.def} to add it.
21785 @noindent
21786 Here are some hints to find the right @code{@@}@i{nn} suffix.
21788 @enumerate
21789 @item
21790 If you have the Microsoft import library (.lib), it is possible to get
21791 the right symbols by using Microsoft @code{dumpbin} tool (see the
21792 corresponding Microsoft documentation for further details).
21794 @smallexample
21795 $ dumpbin /exports api.lib
21796 @end smallexample
21798 @item
21799 If you have a message about a missing symbol at link time the compiler
21800 tells you what symbol is expected. You just have to go back to the
21801 definition file and add the right suffix.
21802 @end enumerate
21804 @item
21805 Build the import library @code{libAPI.a}, using @code{gnatdll}
21806 (@pxref{Using gnatdll}) as follows:
21808 @smallexample
21809 $ gnatdll -e API.def -d API.dll
21810 @end smallexample
21812 @noindent
21813 @code{gnatdll} takes as input a definition file @file{API.def} and the
21814 name of the DLL containing the services listed in the definition file
21815 @file{API.dll}. The name of the static import library generated is
21816 computed from the name of the definition file as follows: if the
21817 definition file name is @i{xyz}@code{.def}, the import library name will
21818 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
21819 @code{-e} could have been removed because the name of the definition
21820 file (before the "@code{.def}" suffix) is the same as the name of the
21821 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
21822 @end enumerate
21824 @node Microsoft-Style Import Library
21825 @subsubsection Microsoft-Style Import Library
21827 @noindent
21828 With GNAT you can either use a GNAT-style or Microsoft-style import
21829 library. A Microsoft import library is needed only if you plan to make an
21830 Ada DLL available to applications developed with Microsoft
21831 tools (@pxref{Mixed-Language Programming on Windows}).
21833 To create a Microsoft-style import library for @file{API.dll} you
21834 should proceed as follows:
21836 @enumerate
21837 @item
21838 Create the definition file @file{API.def} from the DLL. For this use either
21839 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
21840 tool (see the corresponding Microsoft documentation for further details).
21842 @item
21843 Build the actual import library using Microsoft's @code{lib} utility:
21845 @smallexample
21846 $ lib -machine:IX86 -def:API.def -out:API.lib
21847 @end smallexample
21849 @noindent
21850 If you use the above command the definition file @file{API.def} must
21851 contain a line giving the name of the DLL:
21853 @smallexample
21854 LIBRARY      "API"
21855 @end smallexample
21857 @noindent
21858 See the Microsoft documentation for further details about the usage of
21859 @code{lib}.
21860 @end enumerate
21862 @node Building DLLs with GNAT
21863 @section Building DLLs with GNAT
21864 @cindex DLLs, building
21866 @menu
21867 * Limitations When Using Ada DLLs from Ada::
21868 * Exporting Ada Entities::
21869 * Ada DLLs and Elaboration::
21870 * Ada DLLs and Finalization::
21871 * Creating a Spec for Ada DLLs::
21872 * Creating the Definition File::
21873 * Using gnatdll::
21874 @end menu
21876 @noindent
21877 This section explains how to build DLLs containing Ada code. These DLLs
21878 will be referred to as Ada DLLs in the remainder of this section.
21880 The steps required to build an Ada DLL that is to be used by Ada as well as
21881 non-Ada applications are as follows:
21883 @enumerate
21884 @item
21885 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
21886 @code{Stdcall} calling convention to avoid any Ada name mangling for the
21887 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
21888 skip this step if you plan to use the Ada DLL only from Ada applications.
21890 @item
21891 Your Ada code must export an initialization routine which calls the routine
21892 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
21893 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
21894 routine exported by the Ada DLL must be invoked by the clients of the DLL
21895 to initialize the DLL.
21897 @item
21898 When useful, the DLL should also export a finalization routine which calls
21899 routine @code{adafinal} generated by @code{gnatbind} to perform the
21900 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
21901 The finalization routine exported by the Ada DLL must be invoked by the
21902 clients of the DLL when the DLL services are no further needed.
21904 @item
21905 You must provide a spec for the services exported by the Ada DLL in each
21906 of the programming languages to which you plan to make the DLL available.
21908 @item
21909 You must provide a definition file listing the exported entities
21910 (@pxref{The Definition File}).
21912 @item
21913 Finally you must use @code{gnatdll} to produce the DLL and the import
21914 library (@pxref{Using gnatdll}).
21915 @end enumerate
21917 @node Limitations When Using Ada DLLs from Ada
21918 @subsection Limitations When Using Ada DLLs from Ada
21920 @noindent
21921 When using Ada DLLs from Ada applications there is a limitation users
21922 should be aware of. Because on Windows the GNAT run time is not in a DLL of
21923 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
21924 each Ada DLL includes the services of the GNAT run time that are necessary
21925 to the Ada code inside the DLL. As a result, when an Ada program uses an
21926 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
21927 one in the main program.
21929 It is therefore not possible to exchange GNAT run-time objects between the
21930 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
21931 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
21932 types, etc.
21934 It is completely safe to exchange plain elementary, array or record types,
21935 Windows object handles, etc.
21937 @node Exporting Ada Entities
21938 @subsection Exporting Ada Entities
21939 @cindex Export table
21941 @noindent
21942 Building a DLL is a way to encapsulate a set of services usable from any
21943 application. As a result, the Ada entities exported by a DLL should be
21944 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
21945 any Ada name mangling. Please note that the @code{Stdcall} convention
21946 should only be used for subprograms, not for variables. As an example here
21947 is an Ada package @code{API}, spec and body, exporting two procedures, a
21948 function, and a variable:
21950 @smallexample
21951 @group
21952 @cartouche
21953 @b{with} Interfaces.C; @b{use} Interfaces;
21954 @b{package} API @b{is}
21955    Count : C.int := 0;
21956    @b{function} Factorial (Val : C.int) @b{return} C.int;
21958    @b{procedure} Initialize_API;
21959    @b{procedure} Finalize_API;
21960    --  @i{Initialization & Finalization routines. More in the next section.}
21961 @b{private}
21962    @b{pragma} Export (C, Initialize_API);
21963    @b{pragma} Export (C, Finalize_API);
21964    @b{pragma} Export (C, Count);
21965    @b{pragma} Export (C, Factorial);
21966 @b{end} API;
21967 @end cartouche
21968 @end group
21969 @end smallexample
21971 @smallexample
21972 @group
21973 @cartouche
21974 @b{package body} API @b{is}
21975    @b{function} Factorial (Val : C.int) @b{return} C.int @b{is}
21976       Fact : C.int := 1;
21977    @b{begin}
21978       Count := Count + 1;
21979       @b{for} K @b{in} 1 .. Val @b{loop}
21980          Fact := Fact * K;
21981       @b{end loop};
21982       @b{return} Fact;
21983    @b{end} Factorial;
21985    @b{procedure} Initialize_API @b{is}
21986       @b{procedure} Adainit;
21987       @b{pragma} Import (C, Adainit);
21988    @b{begin}
21989       Adainit;
21990    @b{end} Initialize_API;
21992    @b{procedure} Finalize_API @b{is}
21993       @b{procedure} Adafinal;
21994       @b{pragma} Import (C, Adafinal);
21995    @b{begin}
21996       Adafinal;
21997    @b{end} Finalize_API;
21998 @b{end} API;
21999 @end cartouche
22000 @end group
22001 @end smallexample
22003 @noindent
22004 If the Ada DLL you are building will only be used by Ada applications
22005 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
22006 convention. As an example, the previous package could be written as
22007 follows:
22009 @smallexample
22010 @group
22011 @cartouche
22012 @b{package} API @b{is}
22013    Count : Integer := 0;
22014    @b{function} Factorial (Val : Integer) @b{return} Integer;
22016    @b{procedure} Initialize_API;
22017    @b{procedure} Finalize_API;
22018    --  @i{Initialization and Finalization routines.}
22019 @b{end} API;
22020 @end cartouche
22021 @end group
22022 @end smallexample
22024 @smallexample
22025 @group
22026 @cartouche
22027 @b{package body} API @b{is}
22028    @b{function} Factorial (Val : Integer) @b{return} Integer @b{is}
22029       Fact : Integer := 1;
22030    @b{begin}
22031       Count := Count + 1;
22032       @b{for} K @b{in} 1 .. Val @b{loop}
22033          Fact := Fact * K;
22034       @b{end loop};
22035       @b{return} Fact;
22036       @b{end} Factorial;
22038    ...
22039    --  @i{The remainder of this package body is unchanged.}
22040 @b{end} API;
22041 @end cartouche
22042 @end group
22043 @end smallexample
22045 @noindent
22046 Note that if you do not export the Ada entities with a @code{C} or
22047 @code{Stdcall} convention you will have to provide the mangled Ada names
22048 in the definition file of the Ada DLL
22049 (@pxref{Creating the Definition File}).
22051 @node Ada DLLs and Elaboration
22052 @subsection Ada DLLs and Elaboration
22053 @cindex DLLs and elaboration
22055 @noindent
22056 The DLL that you are building contains your Ada code as well as all the
22057 routines in the Ada library that are needed by it. The first thing a
22058 user of your DLL must do is elaborate the Ada code
22059 (@pxref{Elaboration Order Handling in GNAT}).
22061 To achieve this you must export an initialization routine
22062 (@code{Initialize_API} in the previous example), which must be invoked
22063 before using any of the DLL services. This elaboration routine must call
22064 the Ada elaboration routine @code{adainit} generated by the GNAT binder
22065 (@pxref{Binding with Non-Ada Main Programs}). See the body of
22066 @code{Initialize_Api} for an example. Note that the GNAT binder is
22067 automatically invoked during the DLL build process by the @code{gnatdll}
22068 tool (@pxref{Using gnatdll}).
22070 When a DLL is loaded, Windows systematically invokes a routine called
22071 @code{DllMain}. It would therefore be possible to call @code{adainit}
22072 directly from @code{DllMain} without having to provide an explicit
22073 initialization routine. Unfortunately, it is not possible to call
22074 @code{adainit} from the @code{DllMain} if your program has library level
22075 tasks because access to the @code{DllMain} entry point is serialized by
22076 the system (that is, only a single thread can execute "through" it at a
22077 time), which means that the GNAT run time will deadlock waiting for the
22078 newly created task to complete its initialization.
22080 @node Ada DLLs and Finalization
22081 @subsection Ada DLLs and Finalization
22082 @cindex DLLs and finalization
22084 @noindent
22085 When the services of an Ada DLL are no longer needed, the client code should
22086 invoke the DLL finalization routine, if available. The DLL finalization
22087 routine is in charge of releasing all resources acquired by the DLL. In the
22088 case of the Ada code contained in the DLL, this is achieved by calling
22089 routine @code{adafinal} generated by the GNAT binder
22090 (@pxref{Binding with Non-Ada Main Programs}).
22091 See the body of @code{Finalize_Api} for an
22092 example. As already pointed out the GNAT binder is automatically invoked
22093 during the DLL build process by the @code{gnatdll} tool
22094 (@pxref{Using gnatdll}).
22096 @code{-g}
22097 @cindex @code{-g} (@code{gnatdll})
22099 Generate debugging information. This information is stored in the object
22100 file and copied from there to the final DLL file by the linker,
22101 where it can be read by the debugger. You must use the
22102 @code{-g} switch if you plan on using the debugger or the symbolic
22103 stack traceback.
22105 @node Creating a Spec for Ada DLLs
22106 @subsection Creating a Spec for Ada DLLs
22108 @noindent
22109 To use the services exported by the Ada DLL from another programming
22110 language (e.g. C), you have to translate the specs of the exported Ada
22111 entities in that language. For instance in the case of @code{API.dll},
22112 the corresponding C header file could look like:
22114 @smallexample
22115 @group
22116 @cartouche
22117 extern int *__imp__count;
22118 #define count (*__imp__count)
22119 int factorial (int);
22120 @end cartouche
22121 @end group
22122 @end smallexample
22124 @noindent
22125 It is important to understand that when building an Ada DLL to be used by
22126 other Ada applications, you need two different specs for the packages
22127 contained in the DLL: one for building the DLL and the other for using
22128 the DLL. This is because the @code{DLL} calling convention is needed to
22129 use a variable defined in a DLL, but when building the DLL, the variable
22130 must have either the @code{Ada} or @code{C} calling convention. As an
22131 example consider a DLL comprising the following package @code{API}:
22133 @smallexample
22134 @group
22135 @cartouche
22136 @b{package} API @b{is}
22137    Count : Integer := 0;
22138    ...
22139    --  @i{Remainder of the package omitted.}
22140 @b{end} API;
22141 @end cartouche
22142 @end group
22143 @end smallexample
22145 @noindent
22146 After producing a DLL containing package @code{API}, the spec that
22147 must be used to import @code{API.Count} from Ada code outside of the
22148 DLL is:
22150 @smallexample
22151 @group
22152 @cartouche
22153 @b{package} API @b{is}
22154    Count : Integer;
22155    @b{pragma} Import (DLL, Count);
22156 @b{end} API;
22157 @end cartouche
22158 @end group
22159 @end smallexample
22161 @node Creating the Definition File
22162 @subsection Creating the Definition File
22164 @noindent
22165 The definition file is the last file needed to build the DLL. It lists
22166 the exported symbols. As an example, the definition file for a DLL
22167 containing only package @code{API} (where all the entities are exported
22168 with a @code{C} calling convention) is:
22170 @smallexample
22171 @group
22172 @cartouche
22173 EXPORTS
22174     count
22175     factorial
22176     finalize_api
22177     initialize_api
22178 @end cartouche
22179 @end group
22180 @end smallexample
22182 @noindent
22183 If the @code{C} calling convention is missing from package @code{API},
22184 then the definition file contains the mangled Ada names of the above
22185 entities, which in this case are:
22187 @smallexample
22188 @group
22189 @cartouche
22190 EXPORTS
22191     api__count
22192     api__factorial
22193     api__finalize_api
22194     api__initialize_api
22195 @end cartouche
22196 @end group
22197 @end smallexample
22199 @node Using gnatdll
22200 @subsection Using @code{gnatdll}
22201 @findex gnatdll
22203 @menu
22204 * gnatdll Example::
22205 * gnatdll behind the Scenes::
22206 * Using dlltool::
22207 @end menu
22209 @noindent
22210 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
22211 and non-Ada sources that make up your DLL have been compiled.
22212 @code{gnatdll} is actually in charge of two distinct tasks: build the
22213 static import library for the DLL and the actual DLL. The form of the
22214 @code{gnatdll} command is
22216 @smallexample
22217 @cartouche
22218 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
22219 @end cartouche
22220 @end smallexample
22222 @noindent
22223 where @i{list-of-files} is a list of ALI and object files. The object
22224 file list must be the exact list of objects corresponding to the non-Ada
22225 sources whose services are to be included in the DLL. The ALI file list
22226 must be the exact list of ALI files for the corresponding Ada sources
22227 whose services are to be included in the DLL. If @i{list-of-files} is
22228 missing, only the static import library is generated.
22230 @noindent
22231 You may specify any of the following switches to @code{gnatdll}:
22233 @table @code
22234 @item -a[@var{address}]
22235 @cindex @code{-a} (@code{gnatdll})
22236 Build a non-relocatable DLL at @var{address}. If @var{address} is not
22237 specified the default address @var{0x11000000} will be used. By default,
22238 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
22239 advise the reader to build relocatable DLL.
22241 @item -b @var{address}
22242 @cindex @code{-b} (@code{gnatdll})
22243 Set the relocatable DLL base address. By default the address is
22244 @var{0x11000000}.
22246 @item -d @var{dllfile}
22247 @cindex @code{-d} (@code{gnatdll})
22248 @var{dllfile} is the name of the DLL. This switch must be present for
22249 @code{gnatdll} to do anything. The name of the generated import library is
22250 obtained algorithmically from @var{dllfile} as shown in the following
22251 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
22252 @code{libxyz.a}. The name of the definition file to use (if not specified
22253 by option @code{-e}) is obtained algorithmically from @var{dllfile} as shown in
22254 the following example: if @var{dllfile} is @code{xyz.dll}, the definition
22255 file used is @code{xyz.def}.
22257 @item -e @var{deffile}
22258 @cindex @code{-e} (@code{gnatdll})
22259 @var{deffile} is the name of the definition file.
22261 @item -h
22262 @cindex @code{-h} (@code{gnatdll})
22263 Help mode. Displays @code{gnatdll} switch usage information.
22265 @item -Idir
22266 Direct @code{gnatdll} to search the @var{dir} directory for source and
22267 object files needed to build the DLL.
22268 (@pxref{Search Paths and the Run-Time Library (RTL)}).
22270 @item -k
22271 Removes the @code{@@}@i{nn} suffix from the import library's exported
22272 names. You must specified this option if you want to use a
22273 @code{Stdcall} function in a DLL for which the @code{@@}@i{nn} suffix
22274 has been removed. This is the case for most of the Windows NT DLL for
22275 example. This option has no effect when @code{-n} option is specified.
22277 @item -l @var{file}
22278 @cindex @code{-l} (@code{gnatdll})
22279 The list of ALI and object files used to build the DLL are listed in
22280 @var{file}, instead of being given in the command line. Each line in
22281 @var{file} contains the name of an ALI or object file.
22283 @item -n
22284 @cindex @code{-n} (@code{gnatdll})
22285 No Import. Do not create the import library.
22287 @item -q
22288 @cindex @code{-q} (@code{gnatdll})
22289 Quiet mode. Do not display unnecessary messages.
22291 @item -v
22292 @cindex @code{-v} (@code{gnatdll})
22293 Verbose mode. Display extra information.
22295 @item -largs @var{opts}
22296 @cindex @code{-largs} (@code{gnatdll})
22297 Linker options. Pass @var{opts} to the linker.
22298 @end table
22300 @node gnatdll Example
22301 @subsubsection @code{gnatdll} Example
22303 @noindent
22304 As an example the command to build a relocatable DLL from @file{api.adb}
22305 once @file{api.adb} has been compiled and @file{api.def} created is
22307 @smallexample
22308 $ gnatdll -d api.dll api.ali
22309 @end smallexample
22311 @noindent
22312 The above command creates two files: @file{libapi.a} (the import
22313 library) and @file{api.dll} (the actual DLL). If you want to create
22314 only the DLL, just type:
22316 @smallexample
22317 $ gnatdll -d api.dll -n api.ali
22318 @end smallexample
22320 @noindent
22321 Alternatively if you want to create just the import library, type:
22323 @smallexample
22324 $ gnatdll -d api.dll
22325 @end smallexample
22327 @node gnatdll behind the Scenes
22328 @subsubsection @code{gnatdll} behind the Scenes
22330 @noindent
22331 This section details the steps involved in creating a DLL. @code{gnatdll}
22332 does these steps for you. Unless you are interested in understanding what
22333 goes on behind the scenes, you should skip this section.
22335 We use the previous example of a DLL containing the Ada package @code{API},
22336 to illustrate the steps necessary to build a DLL. The starting point is a
22337 set of objects that will make up the DLL and the corresponding ALI
22338 files. In the case of this example this means that @file{api.o} and
22339 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
22340 the following:
22342 @enumerate
22343 @item
22344 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
22345 the information necessary to generate relocation information for the
22346 DLL.
22348 @smallexample
22349 @group
22350 $ gnatbind -n api
22351 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
22352 @end group
22353 @end smallexample
22355 @noindent
22356 In addition to the base file, the @code{gnatlink} command generates an
22357 output file @file{api.jnk} which can be discarded. The @code{-mdll} switch
22358 asks @code{gnatlink} to generate the routines @code{DllMain} and
22359 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
22360 is loaded into memory.
22362 @item
22363 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
22364 export table (@file{api.exp}). The export table contains the relocation
22365 information in a form which can be used during the final link to ensure
22366 that the Windows loader is able to place the DLL anywhere in memory.
22368 @smallexample
22369 @group
22370 $ dlltool --dllname api.dll --def api.def --base-file api.base \
22371           --output-exp api.exp
22372 @end group
22373 @end smallexample
22375 @item
22376 @code{gnatdll} builds the base file using the new export table. Note that
22377 @code{gnatbind} must be called once again since the binder generated file
22378 has been deleted during the previous call to @code{gnatlink}.
22380 @smallexample
22381 @group
22382 $ gnatbind -n api
22383 $ gnatlink api -o api.jnk api.exp -mdll
22384       -Wl,--base-file,api.base
22385 @end group
22386 @end smallexample
22388 @item
22389 @code{gnatdll} builds the new export table using the new base file and
22390 generates the DLL import library @file{libAPI.a}.
22392 @smallexample
22393 @group
22394 $ dlltool --dllname api.dll --def api.def --base-file api.base \
22395           --output-exp api.exp --output-lib libAPI.a
22396 @end group
22397 @end smallexample
22399 @item
22400 Finally @code{gnatdll} builds the relocatable DLL using the final export
22401 table.
22403 @smallexample
22404 @group
22405 $ gnatbind -n api
22406 $ gnatlink api api.exp -o api.dll -mdll
22407 @end group
22408 @end smallexample
22409 @end enumerate
22411 @node Using dlltool
22412 @subsubsection Using @code{dlltool}
22414 @noindent
22415 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
22416 DLLs and static import libraries. This section summarizes the most
22417 common @code{dlltool} switches. The form of the @code{dlltool} command
22420 @smallexample
22421 $ dlltool [@var{switches}]
22422 @end smallexample
22424 @noindent
22425 @code{dlltool} switches include:
22427 @table @code
22428 @item --base-file @var{basefile}
22429 Read the base file @var{basefile} generated by the linker. This switch
22430 is used to create a relocatable DLL.
22432 @item --def @var{deffile}
22433 Read the definition file.
22435 @item --dllname @var{name}
22436 Gives the name of the DLL. This switch is used to embed the name of the
22437 DLL in the static import library generated by @code{dlltool} with switch
22438 @code{--output-lib}.
22440 @item -k
22441 Kill @code{@@}@i{nn} from exported names
22442 (@pxref{Windows Calling Conventions}
22443 for a discussion about @code{Stdcall}-style symbols.
22445 @item --help
22446 Prints the @code{dlltool} switches with a concise description.
22448 @item --output-exp @var{exportfile}
22449 Generate an export file @var{exportfile}. The export file contains the
22450 export table (list of symbols in the DLL) and is used to create the DLL.
22452 @item --output-lib @i{libfile}
22453 Generate a static import library @var{libfile}.
22455 @item -v
22456 Verbose mode.
22458 @item --as @i{assembler-name}
22459 Use @i{assembler-name} as the assembler. The default is @code{as}.
22460 @end table
22462 @node GNAT and Windows Resources
22463 @section GNAT and Windows Resources
22464 @cindex Resources, windows
22466 @menu
22467 * Building Resources::
22468 * Compiling Resources::
22469 * Using Resources::
22470 * Limitations::
22471 @end menu
22473 @noindent
22474 Resources are an easy way to add Windows specific objects to your
22475 application. The objects that can be added as resources include:
22477 @itemize @bullet
22478 @item
22479 menus
22481 @item
22482 accelerators
22484 @item
22485 dialog boxes
22487 @item
22488 string tables
22490 @item
22491 bitmaps
22493 @item
22494 cursors
22496 @item
22497 icons
22499 @item
22500 fonts
22501 @end itemize
22503 @noindent
22504 This section explains how to build, compile and use resources.
22506 @node Building Resources
22507 @subsection Building Resources
22508 @cindex Resources, building
22510 @noindent
22511 A resource file is an ASCII file. By convention resource files have an
22512 @file{.rc} extension.
22513 The easiest way to build a resource file is to use Microsoft tools
22514 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
22515 @code{dlgedit.exe} to build dialogs.
22516 It is always possible to build an @file{.rc} file yourself by writing a
22517 resource script.
22519 It is not our objective to explain how to write a resource file. A
22520 complete description of the resource script language can be found in the
22521 Microsoft documentation.
22523 @node Compiling Resources
22524 @subsection Compiling Resources
22525 @findex rc
22526 @findex rcl
22527 @findex res2coff
22528 @cindex Resources, compiling
22530 @noindent
22531 This section describes how to build a GNAT-compatible (COFF) object file
22532 containing the resources. This is done using the Resource Compiler
22533 @code{rcl} as follows:
22535 @smallexample
22536 $ rcl -i myres.rc -o myres.o
22537 @end smallexample
22539 @noindent
22540 By default @code{rcl} will run @code{gcc} to preprocess the @file{.rc}
22541 file. You can specify an alternate preprocessor (usually named
22542 @file{cpp.exe}) using the @code{rcl} @code{-cpp} parameter. A list of
22543 all possible options may be obtained by entering the command @code{rcl}
22544 with no parameters.
22546 It is also possible to use the Microsoft resource compiler @code{rc.exe}
22547 to produce a @file{.res} file (binary resource file). See the
22548 corresponding Microsoft documentation for further details. In this case
22549 you need to use @code{res2coff} to translate the @file{.res} file to a
22550 GNAT-compatible object file as follows:
22552 @smallexample
22553 $ res2coff -i myres.res -o myres.o
22554 @end smallexample
22556 @node Using Resources
22557 @subsection Using Resources
22558 @cindex Resources, using
22560 @noindent
22561 To include the resource file in your program just add the
22562 GNAT-compatible object file for the resource(s) to the linker
22563 arguments. With @code{gnatmake} this is done by using the @code{-largs}
22564 option:
22566 @smallexample
22567 $ gnatmake myprog -largs myres.o
22568 @end smallexample
22570 @node Limitations
22571 @subsection Limitations
22572 @cindex Resources, limitations
22574 @noindent
22575 In this section we describe the current limitations together with
22576 suggestions for workarounds.
22578 @itemize @bullet
22579 @item
22580 @code{rcl} does not handle the @code{RCINCLUDE} directive.
22582 Workaround: replace @code{RCINCLUDE} by an @code{#include} directive.
22584 @item
22585 @code{rcl} does not handle the brackets as block delimiters.
22587 Workaround: replace character '@{' by @code{BEGIN} and '@}' by
22588 @code{END}. Note that Microsoft's @code{rc} handles both forms of block
22589 delimiters.
22591 @item
22592 @code{rcl} does not handle @code{TypeLib} resources. This type of
22593 resource is used to build COM, DCOM or ActiveX objects.
22595 Workaround: use @code{rc}, the Microsoft resource compiler.
22597 @item
22598 It is not possible to use @code{strip} to remove the debugging symbols
22599 from a program with resources.
22601 Workaround: use linker option @code{-s} to strip debugging symbols from
22602 the final executable.
22603 @end itemize
22605 @node Debugging a DLL
22606 @section Debugging a DLL
22607 @cindex DLL debugging
22609 @menu
22610 * The Program and the DLL Are Built with GCC/GNAT::
22611 * The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT::
22612 @end menu
22614 @noindent
22615 Debugging a DLL is similar to debugging a standard program. But
22616 we have to deal with two different executable parts: the DLL and the
22617 program that uses it. We have the following four possibilities:
22619 @enumerate 1
22620 @item
22621 The program and the DLL are built with @code{GCC/GNAT}.
22622 @item
22623 The program is built with foreign tools and the DLL is built with
22624 @code{GCC/GNAT}.
22625 @item
22626 The program is built with @code{GCC/GNAT} and the DLL is built with
22627 foreign tools.
22628 @item
22629 @end enumerate
22631 @noindent
22632 In this section we address only cases one and two above.
22633 There is no point in trying to debug
22634 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
22635 information in it. To do so you must use a debugger compatible with the
22636 tools suite used to build the DLL.
22638 @node The Program and the DLL Are Built with GCC/GNAT
22639 @subsection The Program and the DLL Are Built with GCC/GNAT
22641 @noindent
22642 This is the simplest case. Both the DLL and the program have @code{GDB}
22643 compatible debugging information. It is then possible to break anywhere in
22644 the process. Let's suppose here that the main procedure is named
22645 @code{ada_main} and that in the DLL there is an entry point named
22646 @code{ada_dll}.
22648 @noindent
22649 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
22650 program must have been built with the debugging information (see GNAT -g
22651 switch). Here are the step-by-step instructions for debugging it:
22653 @enumerate 1
22654 @item Launch @code{GDB} on the main program.
22656 @smallexample
22657 $ gdb -nw ada_main
22658 @end smallexample
22660 @item Break on the main procedure and run the program.
22662 @smallexample
22663 (gdb) break ada_main
22664 (gdb) run
22665 @end smallexample
22667 @noindent
22668 This step is required to be able to set a breakpoint inside the DLL. As long
22669 as the program is not run, the DLL is not loaded. This has the
22670 consequence that the DLL debugging information is also not loaded, so it is not
22671 possible to set a breakpoint in the DLL.
22673 @item Set a breakpoint inside the DLL
22675 @smallexample
22676 (gdb) break ada_dll
22677 (gdb) run
22678 @end smallexample
22680 @end enumerate
22682 @noindent
22683 At this stage a breakpoint is set inside the DLL. From there on
22684 you can use the standard approach to debug the whole program
22685 (@pxref{Running and Debugging Ada Programs}).
22687 @node The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT
22688 @subsection The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT
22690 @menu
22691 * Debugging the DLL Directly::
22692 * Attaching to a Running Process::
22693 @end menu
22695 @noindent
22696 In this case things are slightly more complex because it is not possible to
22697 start the main program and then break at the beginning to load the DLL and the
22698 associated DLL debugging information. It is not possible to break at the
22699 beginning of the program because there is no @code{GDB} debugging information,
22700 and therefore there is no direct way of getting initial control. This
22701 section addresses this issue by describing some methods that can be used
22702 to break somewhere in the DLL to debug it.
22704 @noindent
22705 First suppose that the main procedure is named @code{main} (this is for
22706 example some C code built with Microsoft Visual C) and that there is a
22707 DLL named @code{test.dll} containing an Ada entry point named
22708 @code{ada_dll}.
22710 @noindent
22711 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
22712 been built with debugging information (see GNAT -g option).
22714 @node Debugging the DLL Directly
22715 @subsubsection Debugging the DLL Directly
22717 @enumerate 1
22718 @item
22719 Launch the debugger on the DLL.
22721 @smallexample
22722 $ gdb -nw test.dll
22723 @end smallexample
22725 @item Set a breakpoint on a DLL subroutine.
22727 @smallexample
22728 (gdb) break ada_dll
22729 @end smallexample
22731 @item
22732 Specify the executable file to @code{GDB}.
22734 @smallexample
22735 (gdb) exec-file main.exe
22736 @end smallexample
22738 @item
22739 Run the program.
22741 @smallexample
22742 (gdb) run
22743 @end smallexample
22745 @noindent
22746 This will run the program until it reaches the breakpoint that has been
22747 set. From that point you can use the standard way to debug a program
22748 as described in (@pxref{Running and Debugging Ada Programs}).
22750 @end enumerate
22752 @noindent
22753 It is also possible to debug the DLL by attaching to a running process.
22755 @node Attaching to a Running Process
22756 @subsubsection Attaching to a Running Process
22757 @cindex DLL debugging, attach to process
22759 @noindent
22760 With @code{GDB} it is always possible to debug a running process by
22761 attaching to it. It is possible to debug a DLL this way. The limitation
22762 of this approach is that the DLL must run long enough to perform the
22763 attach operation. It may be useful for instance to insert a time wasting
22764 loop in the code of the DLL to meet this criterion.
22766 @enumerate 1
22768 @item Launch the main program @file{main.exe}.
22770 @smallexample
22771 $ main
22772 @end smallexample
22774 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
22775 that the process PID for @file{main.exe} is 208.
22777 @item Launch gdb.
22779 @smallexample
22780 $ gdb -nw
22781 @end smallexample
22783 @item Attach to the running process to be debugged.
22785 @smallexample
22786 (gdb) attach 208
22787 @end smallexample
22789 @item Load the process debugging information.
22791 @smallexample
22792 (gdb) symbol-file main.exe
22793 @end smallexample
22795 @item Break somewhere in the DLL.
22797 @smallexample
22798 (gdb) break ada_dll
22799 @end smallexample
22801 @item Continue process execution.
22803 @smallexample
22804 (gdb) continue
22805 @end smallexample
22807 @end enumerate
22809 @noindent
22810 This last step will resume the process execution, and stop at
22811 the breakpoint we have set. From there you can use the standard
22812 approach to debug a program as described in
22813 (@pxref{Running and Debugging Ada Programs}).
22815 @node GNAT and COM/DCOM Objects
22816 @section GNAT and COM/DCOM Objects
22817 @findex COM
22818 @findex DCOM
22820 @noindent
22821 This section is temporarily left blank.
22823 @ignore
22824 @reread
22825 ???????????? WE NEED TO DECIDE WHETHER TO DISTRIBUTE IT ??????????????????????
22827 @node gnatreg : Registry Tool for NT
22828 @section @code{gnatreg} : Registry Tool for NT
22829 @findex gnatreg
22830 @cindex Registry
22832 @menu
22833 * Changing the GNAT compiler to Use::
22834 * Adding/Changing a Library Path::
22835 * Removing a Library Path::
22836 * List Current Configuration::
22837 @end menu
22839 @noindent
22840 This tool can be used to switch from one compiler to another and to manage
22841 the list of directories where GNAT must look to find packages. It is
22842 also a convenient way to do network installation of GNAT.
22844 The form of the @code{gnatreg} command is
22846 @smallexample
22847 $ gnatreg [@var{-hqcarf}] parameter
22848 @end smallexample
22850 @noindent
22851 Commons options are
22853 @table @code
22855 @item -h
22856 print a usage message.
22858 @item -q
22859 quiet/terse - display nothing, just do the job.
22861 @item -f
22862 force mode - create the registry keys if they do not
22863 exist. @code{gnatreg} will exit with an error if this option is omitted
22864 and some registry keys are not setup correctly.
22866 @end table
22868 @subsection Changing the GNAT compiler to use
22870 @smallexample
22871 $ gnatreg c:\gnatpro
22872 @end smallexample
22874 @noindent
22875 This will setup the registry to use the GNAT compiler that has been
22876 installed under c:\gnatpro. @code{gnatreg} check that this directory contain
22877 effectively a GNAT compiler. If you want to setup a network installation
22878 and if GNAT has never been installed on this computer you'll have to use
22879 the -f option.
22881 @subsection Adding/Changing a library path
22883 @smallexample
22884 $ gnatreg -a COMPNT=c:\ada\components
22885 @end smallexample
22887 @noindent
22888 Add the directory c:\ada\components to the list of standards libraries. When
22889 running gnatmake the option -Ic:\ada\components is added automatically to the
22890 command line.
22892 The directory c:\ada\components is associated with the name COMPNT. This
22893 name will be used to remove the library path.
22895 @subsection Removing a library path
22897 @smallexample
22898 $ gnatreg -r COMPNT
22899 @end smallexample
22901 @noindent
22902 Remove the library path named COMPNT.
22904 @subsection List current configuration
22906 @smallexample
22907 $ gnatreg -c
22908 @end smallexample
22910 @noindent
22911 @code{gnatreg} will display the GNAT and AdaGIDE path used and
22912 all the standards libraries and their associated names that have been set.
22914 @end ignore
22915 @end ifset
22917 @ifset vxworks
22918 @node VxWorks Topics
22919 @chapter VxWorks Topics
22921 @noindent
22922 This chapter describes topics that are specific to the GNAT for VxWorks
22923 configurations.
22925 @menu
22926 * Kernel Configuration for VxWorks::
22927 * Kernel Compilation Issues for VxWorks::
22928 * Handling Relocation Issues for PowerPc Targets::
22929 * Support for Software Floating Point on PowerPC Processors::
22930 * Interrupt Handling for VxWorks::
22931 * Simulating Command Line Arguments for VxWorks::
22932 * Debugging Issues for VxWorks::
22933 * Using GNAT from the Tornado 2 Project Facility::
22934 * Frequently Asked Questions for VxWorks::
22935 @end menu
22937 @node Kernel Configuration for VxWorks
22938 @section Kernel Configuration for VxWorks
22940 @noindent
22941 When configuring your VxWorks kernel we recommend including the target
22942 shell. If you omit it from the configuration, you may get undefined
22943 symbols at load time, e.g.
22945 @smallexample
22946 -> ld < hello.exe
22947 Loading hello.exe
22948 Undefined symbols:
22949 mkdir
22950 @end smallexample
22952 @noindent
22953 Generally, such undefined symbols are harmless since these are used by
22954 optional parts of the GNAT run time. However if running your application
22955 generates a VxWorks exception or illegal instruction, you should reconfigure
22956 your kernel to resolve these symbols.
22958 @node Kernel Compilation Issues for VxWorks
22959 @section Kernel Compilation Issues for VxWorks
22961 @noindent
22962 If you plan to link an Ada module with a Tornado 2 Kernel, follow these steps.
22963 (Note that these recommendations apply to @file{cygnus-2.7.2-960126},
22964 shipped with Tornado 2 as the C compiler toolchain.)
22966 @itemize @bullet
22967 @item
22968 Compile your Ada module without linking it with the VxWorks Library:
22969 @smallexample
22970 gnatmake foo.adb -largs -nostdlib
22971 @end smallexample
22973 @item
22974 Edit your makefile and add on the @code{LIBS} line the exact path and name
22975 of the GCC library file provided with GNAT.
22976 @smallexample
22977 LIBS             = $(WIND_BASE)/target/lib/libPPC604gnuvx.a \
22978 /opt/gnu/gnat/lib/gcc-lib/powerpc-wrs-vxworks/2.8.1/libgcc.a
22979 @end smallexample
22981 @noindent
22982 To know the exact name and location of this file, type
22983 @code{<arch>-gcc -print-libgcc-file-name} in a console. Note that this version of GCC is the
22984 one provided with GNAT.
22985 @smallexample
22986 ~ >powerpc-wrs-vxworks-gcc -print-libgcc-file-name
22987 /opt/gnu/gnat/lib/gcc-lib/powerpc-wrs-vxworks/2.8.1/libgcc.a
22988 @end smallexample
22989 @end itemize
22992 @node Handling Relocation Issues for PowerPc Targets
22993 @section Handling Relocation Issues for PowerPc Targets
22994 @cindex Relocation issues for PowerPc VxWorks targets
22995 @cindex PowerPc VxWorks, relocation issues
22996 @cindex VxWorks PowerPc, relocation issues
22998 @noindent
22999 Under certain circumstances, loading a program onto a PowerPC
23000 board will fail with the message
23001 @emph{Relocation value does not fit in 24 bits}.
23003 For some background on this issue, please refer to WRS' SPRs
23004 6040, 20257, and 22767.
23005 In summary,
23006 VxWorks on the PowerPC follows the variation of the SVR4 ABI known
23007 as the Embedded ABI (@emph{EABI}).
23008 @cindex Embedded ABI (for VxWorks on PowerPc)
23009 @cindex EABI (for VxWorks on PowerPc)
23010 In order to save space and time in
23011 embedded applications, the EABI specifies that the default for
23012 subprogram calls should be the branch instruction with relative
23013 addressing using an immediate operand.  The immediate operand
23014 to this instruction (relative address) is 24 bits wide.  It
23015 is sign extended and 2#00# is appended for the last 2 bits (all
23016 instructions must be on a 4 byte boundary).
23017 The resulting
23018 26 bit offset means that the target of the branch must be within
23019 +/- 32 Mbytes of the relative branch instruction.  When VxWorks
23020 is loading a program it completes the linking phase by
23021 resolving all of the unresolved references in the object being
23022 loaded.  When one of those references is a relative address in
23023 a branch instruction, and the linker determines that the target
23024 is more than 32 Mbytes away from the branch, the error occurs.
23026 This only happens when the BSP is configured to use
23027 more than 32 MBytes of memory.  The VxWorks kernel is loaded into
23028 low memory addresses, and the error usually occurs when the target
23029 loader is used (because it loads objects into high memory, and thus
23030 calls from the program to the VxWorks kernel can be too far).
23031 @cindex VxWorks kernel (relocation issues on PowerPc)
23033 One way to solve this problem is to use the Tornado
23034 host loader; this will place programs in low memory, close to the kernel.
23036 Another approach is to make use of the @code{-mlongcall} option to the
23037 compiler;
23038 @cindex @code{-mlongcall} (gcc)
23039 GNAT has incorporated WRS'
23040 gcc modification that implements this option.
23041 If a subprogram call is
23042 compiled with the @code{-mlongcall} option, then the generated code
23043 constructs an absolute address in a register and uses a branch
23044 instruction with absolute addressing mode.
23046 Starting with release 3.15, the GNAT runtime libraries that are
23047 distributed are compiled with the @code{-mlongcall} option.  In many
23048 cases the use of these libraries is sufficient to avoid the
23049 relocation problem, since it is the runtime library that contains
23050 calls to the VxWorks kernel that need to span the address space gap.
23051 If you are using an earlier GNAT release or a manually-built runtime,
23052 you should recompile the GNAT runtime library with @code{-mlongcall};
23053 you can use the
23054 @file{Makefile.adalib} file from the @file{adalib} directory.
23056 Application code may need to be compiled with @code{-mlongcall} if there
23057 are calls directly to the kernel, the application is very large,
23058 or in some specialized linking/loading scenarios.
23060 You can compile individual files with @code{-mlongcall} by placing this
23061 option on the @code{gcc} command line (for brevity we are omitting the
23062 @code{powerpc-wrs-vxworks-} prefix on the commands shown in this
23063 paragraph).
23064 If you provide @code{-mlongcall} as an option for @code{gnatmake}, it will be
23065 passed to all invocations of @code{gcc} that @code{gnatmake} directly performs.
23066 Note that one other compilation is made by @code{gnatlink}, on the file created
23067 by @code{gnatbind} for the elaboration package body
23068 (see @ref{Binding Using gnatbind}).
23069 Passing @code{-mlongcall} to @code{gnatlink}, either directly
23070 on the @code{gnatlink} command line or by including @code{-mlongcall} in the
23071 @code{-largs} list of @code{gnatmake}, will direct @code{gnatlink} to compile the
23072 binder file with the @code{-mlongcall} option.
23074 To see the effect of @code{-mlongcall}, consider the following small example:
23076 @smallexample
23077    procedure Proc is
23078       procedure Imported_Proc;
23079       pragma Import (Ada, Imported_Proc);
23080    begin
23081       Imported_Proc;
23082    end;
23083 @end smallexample
23085 @noindent
23086 If you compile @code{Proc} with the default options (no @code{-mlongcall}), the following code is generated:
23088 @smallexample
23089    _ada_proc:
23090            ...
23091            bl imported_proc
23092            ...
23093 @end smallexample
23095 @noindent
23096 In contrast, here is the result with the @code{-mlongcall} option:
23098 @smallexample
23099    _ada_proc:
23100            ...
23101            addis 9,0,imported_proc@@ha
23102            addi 0,9,imported_proc@@l
23103            mtlr 0
23104            blrl
23105            ...
23106 @end smallexample
23109 @node Support for Software Floating Point on PowerPC Processors
23110 @section Support for Software Floating Point on PowerPC Processors
23112 @noindent
23113 The PowerPC 860 processor does not have hardware floating-point support.
23114 In order to build and run GNAT modules properly, you need to install and
23115 invoke software-emulated floating-point support as follows:
23117 @itemize @bullet
23118 @item
23119 At installation time:
23120 @itemize @bullet
23121 @item
23122 Create a file @file{ada_object_path} under the directory
23123 @file{BASE\lib\gcc-lib\powerpc-wrs-vxworks\2.8.1}
23124 (by default @file{BASE}=@file{c:\gnatpro})
23125 containing the following line:
23126 @smallexample
23127 rts-soft-float\adalib
23128 @end smallexample
23130 @item
23131 Create a file @file{ada_source_path} under the directory
23132 @file{BASE\lib\gcc-lib\powerpc-wrs-vxworks\2.8.1}
23133 (by default @file{BASE}=@file{c:\gnatpro})
23134 containing the following line:
23135 @smallexample
23136 rts-soft-float\adainclude
23137 @end smallexample
23138 @end itemize
23140 @item
23141 When using the compiler, specify @option{-msoft-float}
23142 as a compiler and a linker option, e.g.:
23143 @smallexample
23144 $powerpc-wrs-vxworks-gnatmake -msoft-float module -largs -msoft-float
23145 @end smallexample
23146 @end itemize
23149 @node Interrupt Handling for VxWorks
23150 @section Interrupt Handling for VxWorks
23152 @noindent
23153 GNAT offers a range of options for hardware interrupt handling. In rough
23154 order of latency and lack of restrictions:
23156 @itemize @bullet
23157 @item Directly vectored interrupt procedure handlers
23158 @item Directly vectored interrupt procedures that signal a task using
23159 a suspension object
23160 @item Ada 95 protected procedure handlers for interrupts
23161 @item Ada 83 style interrupt entry handlers for interrupts
23162 @end itemize
23164 @noindent
23165 In general, the range of possible solutions trades off latency versus
23166 restrictions in the handler code.  Restrictions in direct vectored
23167 interrupt handlers  are documented in the @cite{VxWorks Programmer's Guide}.
23168 Protected procedure handlers have only the
23169 restriction that no potentially blocking operations are performed within
23170 the handler.  Interrupt entries have no restrictions.  We recommend the
23171 use of the protected procedure mechanism as providing the best balance
23172 of these considerations for most applications.
23174 All handler types must explicitly perform any required hardware cleanups,
23175 such as issuing an end-of-interrupt if necessary.
23177 For VxWorks/AE, applications that handle interrupts must be loaded into
23178 the kernel protection domain.
23180 @itemize @bullet
23181 @item Direct Vectored Interrupt Routines
23183 @noindent
23184 This approach provides the lowest interrupt latency, but has the most
23185 restrictions on what VxWorks and Ada runtime calls can be made, as well
23186 as on what Ada entities are accessible to the handler code.  Such handlers
23187 are most useful when there are stringent latency requirements, and very
23188 little processing is to be performed in the handler.   Access to the
23189 necessary VxWorks routines for setting up such handlers is provided in
23190 the package @code{Interfaces.VxWorks}.
23192 VxWorks restrictions are described in the @cite{VxWorks Programmer's Manual}.
23193 Note in particular that floating point context is not automatically saved and
23194 restored when interrupts are vectored to the handler.  If the handler is
23195 to execute floating point instructions, the statements involved must be
23196 bracketed by a pair of calls to @code{fppSave} and @code{fppRestore} defined
23197 in @code{Interfaces.VxWorks}.
23199 In general, it is a good idea to save and restore the handler that was
23200 installed prior to application startup.  The routines @code{intVecGet}
23201 and @code{intVecSet} are used for this purpose.  The Ada handler code
23202 is installed into the vector table using routine @code{intConnect},
23203 which generates wrapper code to save and restore registers.
23205 Example:
23207 @smallexample
23208 with Interfaces.VxWorks; use Interfaces.VxWorks;
23209 with System;
23211 package P is
23213    Count : Natural := 0;
23214    pragma Atomic (Count);
23216    --  Interrupt level used by this example
23217    Level : constant := 1;
23219    --  Be sure to use a reasonable interrupt number for the target
23220    --  board!  Refer to the BSP for details.
23221    Interrupt : constant := 16#14#;
23223    procedure Handler (Parameter : System.Address);
23225 end P;
23227 package body P is
23229    procedure Handler (parameter : System.Address) is
23230       S : Status;
23231    begin
23232       Count := Count + 1;
23233       --  Acknowledge interrupt.  Not necessary for all interrupts.
23234       S := sysBusIntAck (intLevel => Level);
23235    end Handler;
23236 end P;
23238 with Interfaces.VxWorks; use Interfaces.VxWorks;
23239 with Ada.Text_IO; use Ada.Text_IO;
23241 with P; use P;
23242 procedure Useint is
23243    task T;
23245    S : Status;
23247    task body T is
23248    begin
23249       for I in 1 .. 10 loop
23250          Put_Line ("Generating an interrupt...");
23251          delay 1.0;
23253          --  Generate interrupt, using interrupt number
23254          S := sysBusIntGen (Level, Interrupt);
23255       end loop;
23256    end T;
23258    --  Save old handler
23259    Old_Handler : VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interrupt));
23260 begin
23261    S := intConnect (INUM_TO_IVEC (Interrupt), Handler'Access);
23262    S := sysIntEnable (intLevel => Level);
23264    for I in 1 .. 10 loop
23265       delay 2.0;
23266       Put_Line ("value of count:" & P.Count'Img);
23267    end loop;
23269    --  Restore previous handler
23270    S := sysIntDisable (intLevel => Level);
23271    intVecSet (INUM_TO_IVEC (Interrupt), Old_Handler);
23272 end Useint;
23273 @end smallexample
23275 @item Direct Vectored Interrupt Routines
23277 @noindent
23278 A variation on the direct vectored routine that allows for less restrictive
23279 handler code is to separate the interrupt processing into two levels.
23281 The first level is the same as in the previous section.  Here we perform
23282 simple hardware actions and signal a task pending on a Suspension_Object
23283 (defined in @code{Ada.Synchronous_Task_Control}) to perform the more complex
23284 and time-consuming operations.  The routine @code{Set_True} signals a task
23285 whose body loops and pends on the suspension object using @code{Suspend_Until_True}.
23286 The suspension object is declared in a scope global to both the handler and
23287 the task. This approach can be thought of as a slightly higher-level
23288 application of the @code{C} example using a binary semaphore given in the
23289 VxWorks Programmer's Manual.  In fact, the implementation of
23290 @code{Ada.Synchronous_Task_Control} is a very thin wrapper around a VxWorks
23291 binary semaphore.
23293 This approach has a latency between the direct vectored approach and the
23294 protected procedure approach.  There are no restrictions in the Ada task
23295 code, while the handler code has the same restrictions as any other
23296 direct interrupt handler.
23298 Example:
23300 @smallexample
23301 with System;
23302 package Sem_Handler is
23304    Count : Natural := 0;
23305    pragma Atomic (Count);
23307    --  Interrupt level used by this example
23308    Level : constant := 1;
23309    Interrupt : constant := 16#14#;
23311    --  Interrupt handler providing "immediate" handling
23312    procedure Handler (Param : System.Address);
23314    --  Task whose body provides "deferred" handling
23315    task Receiver is
23316        pragma Interrupt_Priority
23317           (System.Interrupt_Priority'First + Level + 1);
23318     end Receiver;
23320 end Sem_Handler;
23322 with Ada.Synchronous_Task_Control; use Ada.Synchronous_Task_Control;
23323 with Interfaces.VxWorks; use Interfaces.VxWorks;
23324 package body Sema_Handler is
23326    SO : Suspension_Object;
23328    task body Receiver is
23329    begin
23330       loop
23331          --  Wait for notification from immediate handler
23332          Suspend_Until_True (SO);
23334          --  Interrupt processing
23335          Count := Count + 1;
23336       end loop;
23337    end Receiver;
23339    procedure Handler (Param : System.Address) is
23340       S : STATUS;
23341    begin
23342       --  Hardware cleanup, if necessary
23343       S := sysBusIntAck (Level);
23345       --  Signal the task
23346       Set_True (SO);
23347    end Handler;
23349 end Sem_Handler;
23351 with Interfaces.VxWorks; use Interfaces.VxWorks;
23352 with Ada.Text_IO; use Ada.Text_IO;
23353 with Sem_Handler; use Sem_Handler;
23354 procedure Useint is
23356    S : STATUS;
23358    task T;
23360    task body T is
23361    begin
23362       for I in 1 .. 10 loop
23363          Put_Line ("Generating an interrupt...");
23364          delay 1.0;
23366          --  Generate interrupt, using interrupt number
23367          S := sysBusIntGen (Level, Interrupt);
23368       end loop;
23369    end T;
23371    --  Save old handler
23372    Old_Handler : VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interrupt));
23373 begin
23374    S := intConnect (INUM_TO_IVEC (Interrupt), Handler'Access);
23375    S := sysIntEnable (intLevel => Level);
23377    for I in 1 .. 10 loop
23378       delay 2.0;
23379       Put_Line ("value of Count:" & Sem_Handler.Count'Img);
23380    end loop;
23382    --  Restore handler
23383    S := sysIntDisable (intLevel => Level);
23384    intVecSet (INUM_TO_IVEC (Interrupt), Old_Handler);
23385    abort Receiver;
23386 end Useint;
23387 @end smallexample
23389 @item Protected Procedure Handlers for Interrupts
23391 @noindent
23392 This is the recommended default mechanism for interrupt handling.
23393 It essentially wraps the hybrid handler / task mechanism in a higher-level
23394 abstraction, and provides a good balance between latency and capability.
23396 Vectored interrupts are designated by their interrupt number, starting from
23397 0 and ranging to the number of entries in the interrupt vector table - 1.
23399 In the GNAT VxWorks implementation, the following priority mappings are used:
23400 @itemize @bullet
23401 @item Normal task priorities are in the range 0 .. 245.
23402 @item Interrupt priority 246 is used by the GNAT @code{Interrupt_Manager}
23403 task.
23404 @item Interrupt priority 247 is used for vectored interrupts
23405 that do not correspond to those generated via an interrupt controller.
23406 @item Interrupt priorities 248 .. 255 correspond to PIC interrupt levels
23407 0 .. 7.
23408 @item Priority 256 is reserved to the VxWorks kernel.
23409 @end itemize
23411 Except for reserved priorities, the above are recommendations for setting the
23412 ceiling priority of a protected object that handles interrupts, or the
23413 priority of a task with interrupt entries.  It's a very good idea to follow
23414 these recommendations for vectored interrupts that come in through the PIC
23415 as it will determine the priority of execution of the code in the protected
23416 procedure or interrupt entry.
23418 No vectored interrupt numbers are reserved in this implementation, because
23419 dedicated interrupts are determined by the board support package. Obviously,
23420 careful consideration of the hardware is necessary when handling interrupts.
23421 The VxWorks BSP for the board is the definitive reference for interrupt
23422 assignments.
23424 Example:
23426 @smallexample
23427 package PO_Handler is
23429    --  Interrupt level used by this example
23430    Level : constant := 1;
23432    Interrupt : constant := 16#14#;
23434    protected Protected_Handler is
23435       procedure Handler;
23436       pragma Attach_Handler (Handler, Interrupt);
23438       function Count return Natural;
23440       pragma Interrupt_Priority (248);
23441    private
23442       The_Count : Natural := 0;
23443    end Protected_Handler;
23445 end PO_Handler;
23447 with Interfaces.VxWorks; use Interfaces.VxWorks;
23448 package body PO_Handler is
23450    protected body Protected_Handler is
23452       procedure Handler is
23453          S : Status;
23454       begin
23455          --  Hardware cleanup if necessary
23456          S := sysBusIntAck (Level);
23458          --  Interrupt processing
23459          The_Count := The_Count + 1;
23460       end Handler;
23462       function Count return Natural is
23463       begin
23464          return The_Count;
23465       end Count;
23466    end Protected_Handler;
23468 end PO_Handler;
23470 with Interfaces.VxWorks; use Interfaces.VxWorks;
23471 with Ada.Text_IO; use Ada.Text_IO;
23473 with PO_Handler; use PO_Handler;
23474 procedure Useint is
23476    task T;
23478    S : STATUS;
23480    task body T is
23481    begin
23482       for I in 1 .. 10 loop
23483          Put_Line ("Generating an interrupt...");
23484          delay 1.0;
23486          --  Generate interrupt, using interrupt number
23487          S := sysBusIntGen (Level, Interrupt);
23488       end loop;
23489    end T;
23491 begin
23492    S := sysIntEnable (intLevel => Level);
23494    for I in 1 .. 10 loop
23495       delay 2.0;
23496       Put_Line ("value of count:" & Protected_Handler.Count'Img);
23497    end loop;
23499    S := sysIntDisable (intLevel => Level);
23500 end Useint;
23501 @end smallexample
23503 @noindent
23504 This is obviously significantly higher-level and easier to write than the
23505 previous examples.
23507 @item Ada 83 Style Interrupt Entries
23509 GNAT provides a full implementation of the Ada 83 interrupt entry mechanism
23510 for vectored interrupts.  However, due to latency issues,
23511 we only recommend using these for backward compatibility.  The comments in
23512 the previous section regarding interrupt priorities and reserved interrupts
23513 apply here.
23515 In order to associate an interrupt with an entry, GNAT provides the
23516 standard Ada convenience routine @code{Ada.Interrupts.Reference}.  It is used
23517 as follows:
23519 @smallexample
23520 Interrupt_Address : constant System.Address :=
23521    Ada.Interrupts.Reference (Int_Num);
23523 task Handler_Task is
23524    pragma Interrupt_Priority (248);  -- For instance
23525    entry Handler;
23526    for Handler'Address use Interrupt_Address;
23527 end Handler_Task;
23528 @end smallexample
23530 @noindent
23531 Since there is no restriction within an interrupt entry on blocking operations,
23532 be sure to perform any hardware interrupt controller related operations before
23533 executing a call that could block within the entry's accept statements.  It
23534 is assumed that interrupt entries are always open alternatives when they
23535 appear within a selective wait statement.  The presence of a guard gives
23536 undefined behavior.
23538 Example:
23540 @smallexample
23541 with Ada.Interrupts;
23542 with System;
23543 package Task_Handler is
23545    --  Interrupt level used by this example
23546    Level : constant := 1;
23548    Interrupt : constant := 16#14#;
23550    Interrupt_Address : constant System.Address :=
23551       Ada.Interrupts.Reference (Int_Num);
23553    task Handler_Task is
23554       pragma Interrupt_Priority (248);  -- For instance
23555       entry Handler;
23556       for Handler'Address use Interrupt_Address;
23558       entry Count (Value : out Natural);
23559    end Handler_Task;
23560 end Task_Handler;
23562 with Interfaces.VxWorks; use Interfaces.VxWorks;
23563 package body Task_Handler is
23565    task body Handler_Task is
23566       The_Count : Natural := 0;
23567       S : STATUS;
23568    begin
23569       loop
23570          select
23571             accept Handler do
23572                --  Hardware cleanup if necessary
23573                S := sysBusIntAck (Level);
23575                --  Interrupt processing
23576                The_Count := The_Count + 1;
23577             end Handler;
23578          or
23579             accept Count (Value : out Natural) do
23580                Value := The_Count;
23581             end Count;
23582          end select;
23583       end loop;
23584    end Handler_Task;
23586 end Handler_Task;
23588 with Interfaces.VxWorks; use Interfaces.VxWorks;
23589 with Ada.Text_IO; use Ada.Text_IO;
23591 with Handler_Task; use Handler_Task;
23592 procedure Useint is
23594    task T;
23596    S : STATUS;
23597    Current_Count : Natural := 0;
23599    task body T is
23600    begin
23601       for I in 1 .. 10 loop
23602          Put_Line ("Generating an interrupt...");
23603          delay 1.0;
23605          --  Generate interrupt, using interrupt number
23606          S := sysBusIntGen (Level, Interrupt);
23607       end loop;
23608    end T;
23610 begin
23611    S := sysIntEnable (intLevel => Level);
23613    for I in 1 .. 10 loop
23614       delay 2.0;
23615       Handler_Task.Count (Current_Count);
23616       Put_Line ("value of count:" & Current_Count'Img);
23617    end loop;
23619    S := sysIntDisable (intLevel => Level);
23620    abort Handler_Task;
23621 end Useint;
23622 @end smallexample
23623 @end itemize
23626 @node Simulating Command Line Arguments for VxWorks
23627 @section Simulating Command Line Arguments for VxWorks
23629 @noindent
23630 The GNAT implementation of @code{Ada.Command_Line} relies on the standard C
23631 symbols @code{argv} and @code{argc}.  The model for invoking "programs" under
23632 VxWorks does not provide these symbols.  The typical method for invoking a
23633 program under VxWorks is to call the @code{sp} function in order to spawn a
23634 thread in which to execute a designated function (in GNAT, this is the implicit
23635 main generated by gnatbind. @code{sp} provides the capability to push a variable
23636 number of arguments onto the stack when the function is invoked.  But this does
23637 not work for the implicit Ada main, because it has no way of knowing how many
23638 arguments might be required.  This eliminates the possibility to use
23639 @code{Ada.Command_Line}.
23641 One way to solve this problem is to define symbols in the VxWorks environment,
23642 then import them into the Ada application.  For example, we could define the
23643 following package that imports two symbols, one an int and the other a string:
23645 @smallexample
23646 with Interfaces.C.Strings;
23647 use Interfaces.C.Strings;
23648 package Args is
23649    --  Define and import a variable for each argument
23650    Int_Arg : Interfaces.C.Int;
23651    String_Arg : Chars_Ptr;
23652 private
23653    pragma Import (C, Int_Arg, "intarg");
23654    pragma Import (C, String_Arg, "stringarg");
23655 end Args;
23656 @end smallexample
23658 @noindent
23659 An Ada unit could then use the two imported variables @code{Int_Arg} and
23660 @code{String_Arg} as follows:
23662 @smallexample
23663 with Args; use Args;
23664 with Interfaces.C.Strings;
23665 use Interfaces.C, Interfaces.C.Strings;
23666 with Ada.Text_IO; use Ada.Text_IO;
23667 procedure Argtest is
23668 begin
23669    Put_Line (Int'Image (Int_Arg));
23670    Put_Line (Value (String_Arg));
23671 end Argtest;
23672 @end smallexample
23674 @noindent
23675 When invoking the application from the shell, one will then set the values
23676 to be imported, and spawn the application, as follows:
23678 @smallexample
23679 -> intarg=10
23680 -> stringarg="Hello"
23681 -> sp (argtest)
23682 @end smallexample
23685 @node Debugging Issues for VxWorks
23686 @section Debugging Issues for VxWorks
23688 @noindent
23689 The debugger can be launched directly from the Tornado environment or from @code{glide}
23690 through its graphical interface: @code{gvd}. It can also be used
23691 directly in text mode as shown below:
23692 @noindent
23693 The command to run @code{GDB} in text mode is
23695 @smallexample
23696 $ @i{target}-gdb
23697 @end smallexample
23699 @noindent
23700 where @i{target} is the name of target of the cross GNAT
23701 compiler. In contrast with native @code{gdb}, it is not useful to give the name of
23702 the program to debug on the command line. Before starting a debugging
23703 session, one needs to connect to the VxWorks-configured board and load
23704 the relocatable object produced by @code{gnatlink}. This can be achieved
23705 by the following commands:
23707 @smallexample
23708 (vxgdb) target wtx myboard
23709 (vxgdb) load program
23710 @end smallexample
23712 @noindent
23713 where @code{myboard} is the host name or IP number of the target board, and
23714 @code{wtx} is the name of debugging protocol used to communicate
23715 with the VxWorks board. Early versions of VxWorks, up tp 5.2, only
23716 support the @code{<vxworks>} protocol whereas starting with VxWorks 5.3
23717 and Tornado, another protocol called  @code{<wtx>} was made available. The
23718 choice of the protocol can be made when configuring the VxWorks
23719 kernel itself. When available, the @code{<wtx>} is greatly preferable
23720 and actually the only supported protocol with GNAT. When the debugger
23721 is  launched directly from Tornado, the proper @code{target} command
23722 is automatically generated by the environment.
23724 The GNAT debugger can be used for debugging multitasking programs in two
23725 different modes and some minimal understanding of these modes is
23726 necessary in order to use the debugger effectively. The two modes are:
23728 @itemize @bullet
23729 @item Monotask mode: attach to, and debug, a single task.
23730 This mode is equivalent to the capabilities offered by CrossWind. The
23731 debugger interacts with a single task, while not affecting other tasks
23732 (insofar as possible). This is the DEFAULT mode.
23734 @item Multitask mode:
23735 The debugger has control over all Ada tasks in an application. It is
23736 possible to gather information about all application tasks, and to
23737 switch from one to another within a single debugging session.
23738 @end itemize
23740 @noindent
23741 It is not advised to switch between the two modes within a debugging
23742 session. A third mode called System mode is also available and can be
23743 used in place of the Multitask mode. Consult the Tornado documentation
23744 for this.
23746 Among the criteria for selecting the appropriate mode is the effect of
23747 task synchronization on the application's behavior. Debugging a
23748 tasking application affects the timing of the application; minimizing
23749 such effects may be critical in certain situations. The two modes have
23750 different effects: monotask mode only affects the attached task:
23751 others will run normally (if possible). Multitask mode stops all tasks
23752 at each breakpoint and restarts them on single-step, next, finish or
23753 continue; this may help avoid deadlocks in the presence of task
23754 synchronization despite the inherent latency of stopping and
23755 restarting the tasks.
23757 @subsection Using the debugger in monotask mode
23759 @noindent
23760 There are two ways to begin your debugging session:
23762 @itemize @bullet
23763 @item The program is already running on the board.
23765 @noindent
23766 The sequence of commands to use this mode is:
23767 @itemize @bullet
23768 @item Launch GVD (possibly from the Tornado menu)
23770 @noindent
23771 Verify that the debugger has access to the debug information of both
23772 your program and the kernel. The Console window should have a message
23773 "Looking for all loaded modules:" followed by the names of the modules
23774 on the board and "ok". If you have some error messages here instead of
23775 "ok", the debugging session may not work as expected.
23777 @item Attach to the desired task using
23778 @smallexample
23779         File --> Attach...
23780 @end smallexample
23781 @noindent
23782 This task is stopped by the debugger. Other tasks continue to operate
23783 normally (unless they are blocked by synchronization with the stopped
23784 task). The source window should display the code on which the task has
23785 been stopped, and if the stack display is enabled, it should reflect
23786 the stack of the task.
23787 @end itemize
23789 @item The program hasn't been loaded yet on the board
23790 @itemize @bullet
23791 @item Launch GVD (possibly from the Tornado menu)
23792 @item Load your program to the board:
23793 @smallexample
23794 File --> Open Program...
23795 @end smallexample
23797 @noindent
23798 GVD should display:
23799 @smallexample
23800 Downloading your_program ...done.
23801 Reading symbols from your_program...expanding to full symbols...done.
23802 @end smallexample
23804 @item Set breakpoints in your program.
23806 @noindent
23807 WARNING: they must be set in the main task (if your program runs
23808 several tasks)
23810 @item Run your program using one of the three methods below:
23811 @itemize @bullet
23812 @item
23813 Click on button <run> or <start>
23815 @item Menu
23816 @smallexample
23817 Program --> Run/Start
23818 @end smallexample
23820 @item
23821 Type in GVD's Console window
23822 @smallexample
23823 (gdb) run your_program
23824 @end smallexample
23825 @end itemize
23826 @end itemize
23828 @item Whichever method you chose to start your debugging session,
23829 you can use the following commands at this point:
23830 @itemize @bullet
23831 @item  Browse sources and set breakpoints
23832 @item  Examine the call stack (Data --> call stack)
23833 @item  Go "up" and "down" in the call stack ("up" & "down" buttons)
23834 @item  Examine data
23835 (Data --> Display local variables, or any of the other methods for viewing data in GVD)
23836 @item Continue/finish
23837 @end itemize
23839 Next/step/finish will only work if the top frame in the call stack has
23840 debug information.  This is almost never the case when first attaching
23841 to the task since the task is usually stopped by the attach operation
23842 in the GNAT runtime. You can verify which frames of the call stack
23843 have debug information by:
23844 @smallexample
23845 Data --> call stack
23846 <right Button> (contextual menu inside the call stack window)
23847  add "file location"
23848 @end smallexample
23850 @noindent
23851 If the current frame does not have a "file location", then there is no
23852 debug information for the frame.  We strongly recommended that you set
23853 breakpoints in the source where debug information can be found and
23854 "continue" until a breakpoint is reached before using
23855 "next/step". Another convenient possibility is to use the "continue
23856 until" capability available from the contextual menu of the Source
23857 window.
23859 You can also examine the state of other tasks using
23860 @smallexample
23861 Data -> tasks
23862 @end smallexample
23864 @noindent
23865 but you can't "switch" to another task by clicking on the
23866 elements of the task list. If you try to, you will get an error
23867 message in GVD's console:
23868 @smallexample
23869 "Task switching is not allowed when multi-tasks mode is not active"
23870 @end smallexample
23872 @noindent
23873 Once you have completed your debugging session on the attached
23874 task, you can detach from the task:
23875 @smallexample
23876 File --> detach
23877 @end smallexample
23879 @noindent
23880 The task resumes normal execution at this stage.  WARNING: when you
23881 detach from a task, be sure that you are in a frame where there is
23882 debug information. Otherwise, the task won't resume properly. You can
23883 then start another attach/detach cycle if you wish.
23885 Note that it is possible to launch several GVD sessions and
23886 simultaneously attach each to a distinct task in monotask mode:
23887 @smallexample
23888 File --> New Debugger...  (uncheck the box: Replace Current Debugger)
23889 File --> Attach...     (in the new window)
23890 File --> detach
23891 @end smallexample
23892 @end itemize
23895 @subsection Using the debugger in Multitask mode
23897 @noindent
23898 The steps are as follows
23900 @itemize @bullet
23901 @item
23902 Launch GVD (possibly from the Tornado menu)
23904 @noindent
23905 There are two possibilities:
23906 @itemize @bullet
23907 @item
23908 If the program is already loaded on the target board, you need only verify
23909 that debug information has been found by the debugger as described
23910 above.
23912 @item
23913 Otherwise, load the program on the board using
23914 @smallexample
23915 File --> Open program
23916 @end smallexample
23917 @end itemize
23919 @item Set breakpoints in the desired parts of the program
23921 @item Start the program
23923 @noindent
23924 The simplest way to start the debugger in multitask mode is to use the
23925 menu
23926 @smallexample
23927 Program --> Run/Start
23928 @end smallexample
23930 @noindent
23931 and check the box "enable vxWorks multi-tasks mode".
23932 You can also use the following gdb commands in the console window
23933 @smallexample
23934         (gdb) set multi-tasks-mode on
23935         (gdb) run your_program
23936 @end smallexample
23938 @item Debug the stopped program
23940 @noindent
23941 Once stopped at a breakpoint
23942 (or if you pressed the "stop" button), you can use all the standard
23943 commands listed for monotask mode + task switching (using Data -->
23944 tasks). Using next/step under this mode is possible with the same
23945 restrictions as for monotask mode, but is not recommended because all
23946 tasks are restarted, leading to the possibility that a different task
23947 hits a breakpoint before the stepping operation has completed.  Such
23948 an occurrence can result in a confusing state for both the user and
23949 the debugger. So we strongly suggest the use of only breakpoints and
23950 "continue" in this mode.
23951 @end itemize
23953 A final reminder: whatever the mode, whether you are debugging or not,
23954 the program has to be reloaded before each new execution, so that data
23955 initialized by the loader is set correctly. For instance, if you wish
23956 to restart the same execution of the same program, you can use the
23957 following sequence of gdb commands in the console window:
23958 @smallexample
23959 (gdb) detach
23960 (gdb) unload your_program(.exe)
23961 (gdb) load your_program(.exe)
23962 (gdb) run your_program
23963 @end smallexample
23966 @node Using GNAT from the Tornado 2 Project Facility
23967 @section Using GNAT from the Tornado 2 Project Facility
23968 @cindex Tornado II Project
23970 @menu
23971 * The GNAT Toolchain as Used from the Tornado 2 Project Facility::
23972 * Building a Simple Application::
23973 * Mixing C and Ada Code in a Tornado 2 Project::
23974 * Compilation Switches::
23975 * Autoscale and Minimal Kernel Configuration::
23976 * Adapting BSPs to GNAT::
23977 * Using GNAT Project Files in a Tornado 2 Project::
23978 @end menu
23980 @noindent
23981 This section describes how to add an Ada module in a Tornado project
23982 using the Tornado 2 Project facility described in
23983 @cite{Tornado User's Guide}, Chapter 4.
23984 All recommendations apply for both 'Downloadable Modules' and 'Kernel'
23985 project types.
23988 @node The GNAT Toolchain as Used from the Tornado 2 Project Facility
23989 @subsection The GNAT Toolchain as Used from the Tornado 2 Project Facility
23991 @noindent
23992 Tornado 2 allows you to integrate third-party C toolchains.
23993 (@cite{Tornado 2 API Programmer's Guide}, Chapter 7).
23994 Thus the GNAT toolchain will be seen as a new C toolchain when used from
23995 the Tornado 2 Project Facility. For each processor you can compile for,
23996 you will find a <proc>gnat toolchain, e.g. PPC604gnat. These toolchains will
23997 allow you to include Ada modules into your projects, and simply build them.
23999 The name of the so-called C compiler is @emph{cc_gnat_<arch>}, the name
24000 of the 'linker' is @emph{ld_gnat_<arch>}, where <arch> is an architecture; e.g.,
24001 PPC. These scripts will call the correct executables during the compilation or
24002 link processes, thus the C compiler, the C linker, or the GNAT toolchain,
24003 depending on the context.
24006 @node  Building a Simple Application
24007 @subsection  Building a Simple Application
24009 @noindent
24010 First, create a new project, using one of the gnat toolchains.
24012 To add an Ada source file to the current project, just click on
24013 @code{Project -> Add/Include}, browse to the relevant file, and include it.
24014 The Ada source file included should be the Ada entry point. Only
24015 one Ada entry point is allowed in a project. Any other required Ada source
24016 files will be automatically compiled and linked by the underlying tools.
24018 You can now compile the project, @code{Build->Rebuild all}.
24019 A log of the compilation process can be found in the build directory, in
24020 @file{gnatbuild.log}. It contains all the calls executed by the scripts, and
24021 associated information.
24024 @node Mixing C and Ada Code in a Tornado 2 Project
24025 @subsection Mixing C and Ada Code in a Tornado 2 Project
24027 @noindent
24028 You can mix C and Ada code in your projects. Your source files and the build
24029 options should comply with the recommendations from the section
24030 @cite{Interfacing to C}.
24031 This means that you can have several or no C source files, and one or no Ada entry
24032 point in your Tornado 2 Project.
24035 @node Compilation Switches
24036 @subsection Compilation Switches
24037 @noindent
24038 Once you have included all your source files, you may modify some compilation
24039 and linking options.
24040 To pass specific options to the GNAT toolchain, go to the Project's build
24041 settings, on the @code{C/C++ Compiler} tab, and add your arguments in the
24042 input window.
24044 You must comply with several rules to pass arguments to GNAT.
24045 Arguments to be passed should be
24047 @itemize @bullet
24049 @item after any arguments passed to the C toolchain.
24051 @item prefixed depending on the tool that uses them, with the following syntax
24053 @itemize @bullet
24054 @item @code{-cargs @emph{gnatmake-options}} to pass arguments to gnatmake
24055 @item @code{-bargs @emph{gnatbind-options}} to pass arguments to gnatbind
24056 @item @code{-largs @emph{gnatlink-options}} to pass arguments to gnatlink
24057 @end itemize
24058 @end itemize
24060 @noindent
24061 You will find more information on the compilation process of Ada source files
24062 in the section @cite{The GNAT Compilation Model}.
24063 For a list of all available switches, refer to the sections describing
24064 @code{gnatmake}, @code{gnatbind} and @code{gnatlink}.
24066 Here is an example that passes the option @code{-v} to the GNAT compiler :
24067 @smallexample
24068 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
24069 -fvolatile -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
24070 -cargs -v
24071 @end smallexample
24073 @noindent
24074 Here is an example that passes the option @code{-v} to the GNAT compiler, binder and linker,
24075 and @code{-v} and @code{-g} to the compiler :
24076 @smallexample
24077 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
24078 -fvolatile -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
24079 -cargs -v -g -O2 -bargs -v -largs -v
24080 @end smallexample
24082 @noindent
24083 In both examples, the following arguments have been automatically added by the Project
24084 Facility, and will be used by the C compiler.
24085 @smallexample
24086 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
24087 -fvolatile -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
24088 @end smallexample
24090 @noindent
24091 Note: The @code{-prjtype $(PRJ_TYPE)} option present in a few input
24092 boxes is used by the GNAT toolchain. It is required for the compilation
24093 process. You should not remove it from any input box.
24096 @node Autoscale and Minimal Kernel Configuration
24097 @subsection Autoscale and Minimal Kernel Configuration
24099 @noindent
24100 The Autoscale feature, present in the Project Facility  can be used on your
24101 VxWorks Kernel projects to determine the minimum set of components required
24102 for your kernel to work.
24103 (Please refer to the @cite{Tornado II User's Guide} Section 4.4 for more details.)
24104 This feature is also available for projects involving Ada code. Just click on
24105 @code{Project->Autoscale} to launch a check and determine the minimal kernel
24106 configuration.
24109 @node Adapting BSPs to GNAT
24110 @subsection Adapting BSPs to GNAT
24112 @noindent
24113 To use your Board Support Packages with the GNAT toolchain, you will have to adapt them,
24114 either manually or using the @code{adaptbsp4gnat} script.
24115 This procedure is described in the @cite{Tornado API Programmer's Guide},
24116 Chapter 7.
24117 Here is a summary of this setup, depending on the context.
24119 @itemize @bullet
24120 @item To do the adaptation manually:
24122 @itemize @bullet
24124 @item Copy your BSP directory contents into a new directory
24126 @item Go to this directory
24128 @item Edit the file @file{Makefile},
24130 @itemize @bullet
24131 @item Set tool to gnat, @code{TOOL=gnat}
24133 @item Reverse the order of the following lines
24134 @itemize @bullet
24135 @item @code{include $(TGT_DIR)/h/make/make.$(CPU)$(TOOL)}
24136 @item @code{include $(TGT_DIR)/h/make/defs.$(WIND_HOST_TYPE)}
24137 @end itemize
24139 @end itemize
24141 @end itemize
24143 @item To do the adaptation automatically, you may use the @code{adaptbsp4gnat}
24144 script. Its syntax is @code{adaptbsp4gnat <path_to_bsp>}.
24146 @noindent
24147 This script follows the different steps described above to perform the
24148 adaptation.
24149 The name of the new bsp is given after the modification.  By default, if
24150 @file{<bsp>} is the name of your BSP, @file{<bsp>-gnat}, will be the name of
24151 the BSP created.
24152 @end itemize
24155 @node Using GNAT Project Files in a Tornado 2 Project
24156 @subsection Using GNAT Project Files in a Tornado 2 Project
24158 @noindent
24159 You can use GNAT Project files to compile your Ada files.
24160 To do so, you need to use the @option{-Pproject_file.gpr} option from @command{gnatmake}.
24161 The path to the project file can be either absolute, or relative to the build
24162 directory, i.e. where the executable will be placed (e.g. @file{~/myproject/PPC604gnat}).
24163 Your project file should set the @code{Object_Dir} variable to a specific
24164 value.
24165 @smallexample
24166 project Sample is
24168    Target := external ("TARGET_DIR");
24169    for Object_Dir use Target;
24171 end Sample;
24172 @end smallexample
24175 @node Frequently Asked Questions for VxWorks
24176 @section Frequently Asked Questions for VxWorks
24178 @itemize @bullet
24180 @item
24181 When I run my program twice on the board, it does not work, why?
24183 @noindent
24184 Usually, Ada programs require elaboration and finalization, so the
24185 compiler creates a wrapper procedure whose name is the same as the Ada
24186 name of the main subprogram, which takes care of calling the elaboration
24187 and finalization routines before and after your program. But the static
24188 part of the elaboration is taken care of while loading the program
24189 itself and thus if you launch it twice this part of the elaboration will
24190 not be performed. This affects the proper elaboration of the
24191 GNAT runtime and thus it is mandatory to reload your program before
24192 relaunching it.
24194 @item
24195 Can I load a collection of subprograms rather than a standalone program?
24197 @noindent
24198 It is possible to write Ada programs with multiple entry points which
24199 can be called from the VxWorks shell; you just need to consider your
24200 main program as the VxWorks shell itself and generate an Ada subsystem
24201 callable from outside @xref{Binding with Non-Ada Main Programs}. If you
24202 use this method, you need to call @code{adainit} manually before calling
24203 any Ada entry point.
24205 @item
24206 When I use the @code{break exception} command, I get the message
24207 @code{"exception" is not a function}, why?
24209 You are not in the proper language mode. Issue the command:
24210 @smallexample
24211 (vxgdb) set language ada
24212 @end smallexample
24214 @item
24215 When I load a large application from the VxWorks shell using the "ld"
24216 command, the load hangs and never finishes. How can I load large
24217 executables?
24219 This is a classic VxWorks problem when using the default "rsh" communication
24220 method. Using NFS instead should work. Use the @code{nfsShowMount} command to
24221 verify that your program is in a NFS mounted directory.
24223 @item
24224 When I load a large application from the debugger using the wtx target
24225 connection, the load never finishes, why?
24227 Make sure that the memory cache size parameter of the target server is
24228 large enough. (@code{target -m big_enough_size}, or Memory cache size box in GUI.)
24229 See @cite{Tornado 1.01 API Programming Guide}, Section 3.6.2.
24231 @item
24232 When I spawn my program under the VxWorks shell, interactive input does
24233 not work, why?
24235 Only programs directly launched from the shell can have interactive
24236 input. For a program spawned with the @code{sp} or @code{taskSpawn}
24237 command, you need to have file redirection for input:
24238 @smallexample
24239 ->    # here you can have interactive input
24240 -> main
24241 ->    # here you cannot
24242 -> sp main
24243 ->    # neither here
24244 -> taskSpawn("ess",100,0,8000000,main)
24245 ->    # but you can input from a file:
24246 -> taskSpawn("Bae",100,0,8000000,main) < input_file
24247 @end smallexample
24248 @end itemize
24251 @node LynxOS Topics
24252 @chapter LynxOS Topics
24253 @noindent
24254 This chapter describes topics that are specific to the GNAT for LynxOS
24255 cross configurations.
24257 @menu
24258 * Getting Started with GNAT on LynxOS::
24259 * Kernel Configuration for LynxOS::
24260 * Patch Level Issues for LynxOS::
24261 * Debugging Issues for LynxOS::
24262 * An Example Debugging Session for LynxOS::
24263 @end menu
24265 @node Getting Started with GNAT on LynxOS
24266 @section Getting Started with GNAT on LynxOS
24268 @noindent
24269 This section is a starting point for using GNAT to develop and
24270 execute Ada 95 programs for LynuxWorks' LynxOS target environment from a
24271 Unix host environment.
24272 We assume that you know how to use GNAT in a native environment
24273 and how to start a telnet or other login session to connect to your LynxOS board.
24275 To compile code for a LynxOS system running on a PowerPC
24276 board, the basic compiler command is
24277 @command{powerpc-xcoff-lynxos-gcc}.
24279 With GNAT, the easiest way to build the basic @code{Hello World} program is
24280 with @code{gnatmake}. For the LynxOS PowerPC target this would look
24281 like:
24283 @smallexample
24284 $ powerpc-xcoff-lynxos-gnatmake hello
24285 @i{powerpc-xcoff-lynxos-gcc -c hello.adb
24286 powerpc-xcoff-lynxos-gnatbind -x hello.ali
24287 powerpc-xcoff-lynxos-gnatlink hello.ali}
24288 @end smallexample
24290 @noindent
24291 (The first line is the command entered by the user -- the subseqent three
24292 are the programs run by @code{gnatmake}.)
24294 This creates the executable @command{hello}" which you then need to load on the
24295 board (using ftp or an NFS directory for example) to run it.
24298 @node Kernel Configuration for LynxOS
24299 @section Kernel Configuration for LynxOS
24301 @noindent
24302 The appropriate configuration for your LynxOS kernel depends
24303 on the target system and the requirements of your application. GNAT itself
24304 adds no additional demands; however in some situations it may be appropriate
24305 to increase the conservative
24306 resource assumptions made by the default configuration.
24308 Kernel parameters limiting the maximum number of file descriptors,
24309 kernel and user threads, synchronization objects, etc., may be set in the
24310 file @file{uparam.h}. You may also wish to modify the file
24311 @file{/etc/starttab}, which places limits on data, stack, and core file
24312 size. See the documentation provided by LynuxWorks for more information.
24315 @node Patch Level Issues for LynxOS
24316 @section Patch Level Issues for LynxOS
24318 @noindent
24319 The GNAT runtime requires that your system run at patch level 040 or
24320 later. Please see the file @file{PatchCompatibility.txt} from the
24321 distribution for more information.
24324 @node Debugging Issues for LynxOS
24325 @section Debugging Issues for LynxOS
24327 @noindent
24328 GNAT's debugger is based on the same GNU gdb technology as the debugger
24329 provided by LynxOS, though with a great number of extensions and
24330 enhancements to support the Ada language and GNAT. The LynxOS
24331 documentation is relevant to understanding how to get the debugger
24332 started if you run into difficulties.
24334 To demonstrate a debugging session, we will use a slightly more complex
24335 program called @file{demo1.adb}, which can be found in the @file{examples}
24336 directory of the GNAT distribution. This program is compiled with
24337 debugging information as follows:
24339 @smallexample
24340 $ powerpc-xcoff-lynxos-gnatmake -g demo1
24341 powerpc-xcoff-lynxos-gcc -c -g demo1.adb
24342 powerpc-xcoff-lynxos-gcc -c -g gen_list.adb
24343 powerpc-xcoff-lynxos-gcc -c -g instr.adb
24344 powerpc-xcoff-lynxos-gnatbind -x demo1.ali
24345 powerpc-xcoff-lynxos-gnatlink -g demo1.ali
24346 @end smallexample
24348 @noindent
24349 Once the executable is created, copy it to your working directory on the
24350 board. In this directory, you will have to launch the gdb server and
24351 choose a free port number on your TCP/IP socket. Presuming the Internet
24352 hostname of the board is @file{myboard} and the port chosen is 2345,
24353 issue the following command:
24355 @smallexample
24356 myboard> gdbserver myboard:2345 demo1
24357 @end smallexample
24359 @noindent
24360 Then return to your host environment.
24362 The graphical debugger interface, @command{gvd}, supports both native
24363 and cross environments at the same time. @command{gvd} can be launched from
24364 @command{Glide} (see @file{README.Glide} for more information on customizing
24365 @command{Glide} for LynxOS) or it can be launched from the command line as
24366 follows:
24368 @smallexample
24369 $ gvd --debugger powerpc-xcoff-lynxos-gdb
24370 @end smallexample
24372 @noindent
24373 Then to attach to the target, enter in @command{gvd}'s command line window:
24375 @smallexample
24376 (gdb) target remote myboard:2345
24377 @end smallexample
24379 @noindent
24380 For more information see the GVD documentation.
24382 The comments below concern debugging directly from the command line but
24383 they also apply to @command{gvd}, though in most cases an equivalent
24384 graphical command is also available.
24386 To run the cross debugger from the command line without the visual
24387 interface use the command @code{powerpc-xcoff-lynxos-gdb}.
24389 You will see something like:
24391 @smallexample
24392 GNU gdb 4.17.gnat.3.14a1
24393 Copyright 1998 Free Software Foundation, Inc.
24394 GDB is free software, covered by the GNU General Public License, and you are
24395 welcome to change it and/or distribute copies of it under certain conditions.
24396 Type "show copying" to see the conditions.
24397 There is absolutely no warranty for GDB.  Type "show warranty" for details.
24398 This GDB was configured as "--host=sparc-sun-solaris2.5.1 --target=powerpc-xc
24399 off-lynxos".
24400 (gdb)
24401 @end smallexample
24403 @noindent
24404 Where @command{(gdb)} is the debugger's prompt. The first thing to do at the
24405 prompt from within @command{gdb} is to load the symbol table from the
24406 executable:
24408 @smallexample
24409 (gdb) file demo1
24410 Reading symbols from demo1...done.
24411 (gdb)
24412 @end smallexample
24414 @noindent
24415 You then have to attach to the server running on the board. Issue the command:
24417 @smallexample
24418 (gdb) target remote myboard:2345
24419 @end smallexample
24421 @noindent
24422 After the server has been started and attached from the host, the program is
24423 running on the target but has halted execution at the very beginning.
24424 The following commands set a breakpoint and continue execution:
24426 @smallexample
24427 (gdb) break demo1.adb:37
24428 Breakpoint 1 at 0x100064d0: file demo1.adb, line 37.
24429 (gdb) cont
24430 Continuing.
24432 Breakpoint 1, demo1 () at demo1.adb:37
24433 37         Set_Name (Fuel, "Fuel");
24434 (gdb)
24435 @end smallexample
24437 @noindent
24438 Here the execution has stopped at the breakpoint set above. Now
24439 you can use the standard @code{gdb} commands to examine the stack and
24440 program variables.
24442 Note that once execution has completed, the server on the board must be
24443 restarted before a new debugging session may begin.
24445 @node An Example Debugging Session for LynxOS
24446 @section An Example Debugging Session for LynxOS
24448 @noindent
24449 Carrying on a little further with the debugging session, the following
24450 example illustrates some of the usual debugging commands for moving
24451 around and seeing where you are:
24453 @smallexample
24454 (gdb) next
24455 38         Set_Name (Water, "Water");
24456 (gdb) bt
24457 #0  demo1 () at demo1.adb:38
24458 #1  0x10001218 in main (argc=1, argv=2147483640, envp=2147483520) at
24459 b~demo1.adb:118
24460 #2  0x10017538 in runmainthread ()
24461 #3  0x10001048 in __start ()
24462 (gdb) up
24463 #1  0x10001218 in main (argc=1, argv=2147483640, envp=2147483520) at
24464 b~demo1.adb:118
24465 118       Ada_Main_Program;
24466 (gdb) down
24467 #0  demo1 () at demo1.adb:38
24468 38         Set_Name (Water, "Water");
24469 (gdb)
24470 @end smallexample
24472 @noindent
24473 To examine and modify variables (of a tagged type here):
24475 @smallexample
24476 (gdb) print speed
24477 $1 = (name => "Speed         ", value => -286331154)
24478 (gdb) ptype speed
24479 type = new instr.instrument with record
24480     value: instr.speed;
24481 end record
24482 (gdb) speed.value := 3
24483 $2 = 3
24484 (gdb) print speed
24485 $3 = (name => "Speed         ", value => 3)
24486 (gdb) info local
24487 speed = (name => "Speed         ", value => 3)
24488 fuel = (name => "Fuel          ", value => -286331154)
24489 oil = (name => ' ' <repeats 14 times>, value => -286331154, size => 20,
24490   fill => 42 '*', empty => 46 '.')
24491 water = (name => ' ' <repeats 14 times>, value => -286331154, size => 20,
24492   fill => 42 '*', empty => 46 '.')
24493 time = (name => ' ' <repeats 14 times>, seconds => 0, minutes => 0, hours =>
24495 chrono = (name => ' ' <repeats 14 times>, seconds => 0, minutes => 0,
24496   hours => 0)
24497 db = (access demo1.dash_board.internal) 0x0
24498 (gdb)
24499 @end smallexample
24501 @noindent
24502 And finally letting the program it run to completion:
24504 @smallexample
24505 (gdb) c
24506 Continuing.
24508 Program exited normally.
24509 (gdb)
24510 @end smallexample
24511 @end ifset
24514 @node Performance Considerations
24515 @chapter Performance Considerations
24516 @cindex Performance
24518 @noindent
24519 The GNAT system provides a number of options that allow a trade-off
24520 between
24522 @itemize @bullet
24523 @item
24524 performance of the generated code
24526 @item
24527 speed of compilation
24529 @item
24530 minimization of dependences and recompilation
24532 @item
24533 the degree of run-time checking.
24534 @end itemize
24536 @noindent
24537 The defaults (if no options are selected) aim at improving the speed
24538 of compilation and minimizing dependences, at the expense of performance
24539 of the generated code:
24541 @itemize @bullet
24542 @item
24543 no optimization
24545 @item
24546 no inlining of subprogram calls
24548 @item
24549 all run-time checks enabled except overflow and elaboration checks
24550 @end itemize
24552 @noindent
24553 These options are suitable for most program development purposes. This
24554 chapter describes how you can modify these choices, and also provides
24555 some guidelines on debugging optimized code.
24557 @menu
24558 * Controlling Run-Time Checks::
24559 * Optimization Levels::
24560 * Debugging Optimized Code::
24561 * Inlining of Subprograms::
24562 @ifset vms
24563 * Coverage Analysis::
24564 @end ifset
24565 @end menu
24567 @node Controlling Run-Time Checks
24568 @section Controlling Run-Time Checks
24570 @noindent
24571 By default, GNAT generates all run-time checks, except arithmetic overflow
24572 checking for integer operations and checks for access before elaboration on
24573 subprogram calls. The latter are not required in default mode, because all
24574 necessary checking is done at compile time.
24575 @cindex @option{-gnatp} (@code{gcc})
24576 @cindex @option{-gnato} (@code{gcc})
24577 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
24578 be modified. @xref{Run-Time Checks}.
24580 Our experience is that the default is suitable for most development
24581 purposes.
24583 We treat integer overflow specially because these
24584 are quite expensive and in our experience are not as important as other
24585 run-time checks in the development process. Note that division by zero
24586 is not considered an overflow check, and divide by zero checks are
24587 generated where required by default.
24589 Elaboration checks are off by default, and also not needed by default, since
24590 GNAT uses a static elaboration analysis approach that avoids the need for
24591 run-time checking. This manual contains a full chapter discussing the issue
24592 of elaboration checks, and if the default is not satisfactory for your use,
24593 you should read this chapter.
24595 For validity checks, the minimal checks required by the Ada Reference
24596 Manual (for case statements and assignments to array elements) are on
24597 by default. These can be suppressed by use of the @option{-gnatVn} switch.
24598 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
24599 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
24600 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
24601 are also suppressed entirely if @option{-gnatp} is used.
24603 @cindex Overflow checks
24604 @cindex Checks, overflow
24605 @findex Suppress
24606 @findex Unsuppress
24607 @cindex pragma Suppress
24608 @cindex pragma Unsuppress
24609 Note that the setting of the switches controls the default setting of
24610 the checks. They may be modified using either @code{pragma Suppress} (to
24611 remove checks) or @code{pragma Unsuppress} (to add back suppressed
24612 checks) in the program source.
24614 @node Optimization Levels
24615 @section Optimization Levels
24616 @cindex @code{^-O^/OPTIMIZE^} (@code{gcc})
24618 @noindent
24619 The default is optimization off. This results in the fastest compile
24620 times, but GNAT makes absolutely no attempt to optimize, and the
24621 generated programs are considerably larger and slower than when
24622 optimization is enabled. You can use the
24623 @ifclear vms
24624 @code{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
24625 @end ifclear
24626 @ifset vms
24627 @code{^-O^/OPTIMIZE^}
24628 @end ifset
24629 on the @code{gcc} command line to control the optimization level:
24631 @table @code
24632 @item -O0
24633 no optimization (the default)
24635 @item -O1
24636 medium level optimization
24638 @item -O2
24639 full optimization
24641 @item -O3
24642 full optimization, and also attempt automatic inlining of small
24643 subprograms within a unit (@pxref{Inlining of Subprograms}).
24644 @end table
24646 Higher optimization levels perform more global transformations on the
24647 program and apply more expensive analysis algorithms in order to generate
24648 faster and more compact code. The price in compilation time, and the
24649 resulting improvement in execution time,
24650 both depend on the particular application and the hardware environment.
24651 You should experiment to find the best level for your application.
24653 Note: Unlike some other compilation systems, @code{gcc} has
24654 been tested extensively at all optimization levels. There are some bugs
24655 which appear only with optimization turned on, but there have also been
24656 bugs which show up only in @emph{unoptimized} code. Selecting a lower
24657 level of optimization does not improve the reliability of the code
24658 generator, which in practice is highly reliable at all optimization
24659 levels.
24661 Note regarding the use of @code{-O3}: The use of this optimization level
24662 is generally discouraged with GNAT, since it often results in larger
24663 executables which run more slowly. See further discussion of this point
24664 in @pxref{Inlining of Subprograms}.
24666 @node Debugging Optimized Code
24667 @section Debugging Optimized Code
24669 @noindent
24670 Since the compiler generates debugging tables for a compilation unit before
24671 it performs optimizations, the optimizing transformations may invalidate some
24672 of the debugging data.  You therefore need to anticipate certain
24673 anomalous situations that may arise while debugging optimized code.  This
24674 section describes the most common cases.
24676 @enumerate
24677 @item
24678 @i{The "hopping Program Counter":}  Repeated 'step' or 'next' commands show the PC
24679 bouncing back and forth in the code.  This may result from any of the following
24680 optimizations:
24682 @itemize @bullet
24683 @item
24684 @i{Common subexpression elimination:} using a single instance of code for a
24685 quantity that the source computes several times.  As a result you
24686 may not be able to stop on what looks like a statement.
24688 @item
24689 @i{Invariant code motion:} moving an expression that does not change within a
24690 loop, to the beginning of the loop.
24692 @item
24693 @i{Instruction scheduling:} moving instructions so as to
24694 overlap loads and stores (typically) with other code, or in
24695 general to move computations of values closer to their uses. Often
24696 this causes you to pass an assignment statement without the assignment
24697 happening and then later bounce back to the statement when the
24698 value is actually needed.  Placing a breakpoint on a line of code
24699 and then stepping over it may, therefore, not always cause all the
24700 expected side-effects.
24701 @end itemize
24703 @item
24704 @i{The "big leap":} More commonly known as @i{cross-jumping}, in which two
24705 identical pieces of code are merged and the program counter suddenly
24706 jumps to a statement that is not supposed to be executed, simply because
24707 it (and the code following) translates to the same thing as the code
24708 that @emph{was} supposed to be executed.  This effect is typically seen in
24709 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
24710 a @code{break} in a C @code{switch} statement.
24712 @item
24713 @i{The "roving variable":} The symptom is an unexpected value in a variable.
24714 There are various reasons for this effect:
24716 @itemize @bullet
24717 @item
24718 In a subprogram prologue, a parameter may not yet have been moved to its
24719 "home".
24721 @item
24722 A variable may be dead, and its register re-used.  This is
24723 probably the most common cause.
24725 @item
24726 As mentioned above, the assignment of a value to a variable may
24727 have been moved.
24729 @item
24730 A variable may be eliminated entirely by value propagation or
24731 other means.  In this case, GCC may incorrectly generate debugging
24732 information for the variable
24733 @end itemize
24735 @noindent
24736 In general, when an unexpected value appears for a local variable or parameter
24737 you should first ascertain if that value was actually computed by
24738 your program, as opposed to being incorrectly reported by the debugger.
24739 Record fields or
24740 array elements in an object designated by an access value
24741 are generally less of a problem, once you have ascertained that the access value
24742 is sensible.
24743 Typically, this means checking variables in the preceding code and in the
24744 calling subprogram to verify that the value observed is explainable from other
24745 values (one must apply the procedure recursively to those
24746 other values); or re-running the code and stopping a little earlier
24747 (perhaps before the call) and stepping to better see how the variable obtained
24748 the value in question; or continuing to step @emph{from} the point of the
24749 strange value to see if code motion had simply moved the variable's
24750 assignments later.
24751 @end enumerate
24753 @node Inlining of Subprograms
24754 @section Inlining of Subprograms
24756 @noindent
24757 A call to a subprogram in the current unit is inlined if all the
24758 following conditions are met:
24760 @itemize @bullet
24761 @item
24762 The optimization level is at least @code{-O1}.
24764 @item
24765 The called subprogram is suitable for inlining: It must be small enough
24766 and not contain nested subprograms or anything else that @code{gcc}
24767 cannot support in inlined subprograms.
24769 @item
24770 The call occurs after the definition of the body of the subprogram.
24772 @item
24773 @cindex pragma Inline
24774 @findex Inline
24775 Either @code{pragma Inline} applies to the subprogram or it is
24776 small and automatic inlining (optimization level @code{-O3}) is
24777 specified.
24778 @end itemize
24780 @noindent
24781 Calls to subprograms in @code{with}'ed units are normally not inlined.
24782 To achieve this level of inlining, the following conditions must all be
24783 true:
24785 @itemize @bullet
24786 @item
24787 The optimization level is at least @code{-O1}.
24789 @item
24790 The called subprogram is suitable for inlining: It must be small enough
24791 and not contain nested subprograms or anything else @code{gcc} cannot
24792 support in inlined subprograms.
24794 @item
24795 The call appears in a body (not in a package spec).
24797 @item
24798 There is a @code{pragma Inline} for the subprogram.
24800 @item
24801 @cindex @option{-gnatn} (@code{gcc})
24802 The @code{^-gnatn^/INLINE^} switch
24803 is used in the @code{gcc} command line
24804 @end itemize
24806 Note that specifying the @option{-gnatn} switch causes additional
24807 compilation dependencies. Consider the following:
24809 @smallexample
24810 @group
24811 @cartouche
24812 @b{package} R @b{is}
24813    @b{procedure} Q;
24814    @b{pragma} Inline (Q);
24815 @b{end} R;
24816 @b{package body} R @b{is}
24817    ...
24818 @b{end} R;
24820 @b{with} R;
24821 @b{procedure} Main @b{is}
24822 @b{begin}
24823    ...
24824    R.Q;
24825 @b{end} Main;
24826 @end cartouche
24827 @end group
24828 @end smallexample
24830 @noindent
24831 With the default behavior (no @option{-gnatn} switch specified), the
24832 compilation of the @code{Main} procedure depends only on its own source,
24833 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
24834 means that editing the body of @code{R} does not require recompiling
24835 @code{Main}.
24837 On the other hand, the call @code{R.Q} is not inlined under these
24838 circumstances. If the @option{-gnatn} switch is present when @code{Main}
24839 is compiled, the call will be inlined if the body of @code{Q} is small
24840 enough, but now @code{Main} depends on the body of @code{R} in
24841 @file{r.adb} as well as on the spec. This means that if this body is edited,
24842 the main program must be recompiled. Note that this extra dependency
24843 occurs whether or not the call is in fact inlined by @code{gcc}.
24845 The use of front end inlining with @option{-gnatN} generates similar
24846 additional dependencies.
24848 @cindex @code{^-fno-inline^/INLINE=SUPPRESS^} (@code{gcc})
24849 Note: The @code{^-fno-inline^/INLINE=SUPPRESS^} switch
24850 can be used to prevent
24851 all inlining. This switch overrides all other conditions and ensures
24852 that no inlining occurs. The extra dependences resulting from
24853 @option{-gnatn} will still be active, even if
24854 this switch is used to suppress the resulting inlining actions.
24856 Note regarding the use of @code{-O3}: There is no difference in inlining
24857 behavior between @code{-O2} and @code{-O3} for subprograms with an explicit
24858 pragma @code{Inline} assuming the use of @option{-gnatn}
24859 or @option{-gnatN} (the switches that activate inlining). If you have used
24860 pragma @code{Inline} in appropriate cases, then it is usually much better
24861 to use @code{-O2} and @option{-gnatn} and avoid the use of @code{-O3} which
24862 in this case only has the effect of inlining subprograms you did not
24863 think should be inlined. We often find that the use of @code{-O3} slows
24864 down code by performing excessive inlining, leading to increased instruction
24865 cache pressure from the increased code size. So the bottom line here is
24866 that you should not automatically assume that @code{-O3} is better than
24867 @code{-O2}, and indeed you should use @code{-O3} only if tests show that
24868 it actually improves performance.
24870 @ifset vms
24871 @node Coverage Analysis
24872 @section Coverage Analysis
24874 @noindent
24875 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
24876 the user to determine the distribution of execution time across a program,
24877 @pxref{Profiling} for details of usage.
24878 @end ifset
24880 @include fdl.texi
24881 @c GNU Free Documentation License
24883 @node Index,,GNU Free Documentation License, Top
24884 @unnumbered Index
24886 @printindex cp
24888 @contents
24890 @bye