* builtins.def (BUILT_IN_STACK_ALLOC): Remove.
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blob640f74d3399ea0e3539e4aca646b6e39b9e2f9b3
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c          Copyright (C) 1992-2004 Ada Core Technologies, Inc.               o
11 @c                                                                            o
12 @c  GNAT is free software;  you can  redistribute it  and/or modify it under  o
13 @c  terms of the  GNU General Public License as published  by the Free Soft-  o
14 @c  ware  Foundation;  either version 2,  or (at your option) any later ver-  o
15 @c  sion.  GNAT is distributed in the hope that it will be useful, but WITH-  o
16 @c  OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY  o
17 @c  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License  o
18 @c  for  more details.  You should have  received  a copy of the GNU General  o
19 @c  Public License  distributed with GNAT;  see file COPYING.  If not, write  o
20 @c  to  the Free Software Foundation,  59 Temple Place - Suite 330,  Boston,  o
21 @c  MA 02111-1307, USA.                                                       o
22 @c                                                                            o
23 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
25 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
27 @c                           GNAT_UGN Style Guide
29 @c  1. Always put a @noindent on the line before the first paragraph
30 @c     after any of these commands:
32 @c          @chapter
33 @c          @section
34 @c          @subsection
35 @c          @subsubsection
36 @c          @subsubsubsection
38 @c          @end smallexample
39 @c          @end itemize
40 @c          @end enumerate
42 @c  2. DO NOT use @example. Use @smallexample instead.
43 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
44 @c        context.  These can interfere with the readability of the texi
45 @c        source file.  Instead, use one of the following annotated
46 @c        @smallexample commands, and preprocess the texi file with the
47 @c        ada2texi tool (which generates appropriate highlighting):
48 @c        @smallexample @c ada
49 @c        @smallexample @c adanocomment
50 @c        @smallexample @c projectfile
51 @c     b) The "@c ada" markup will result in boldface for reserved words
52 @c        and italics for comments
53 @c     c) The "@c adanocomment" markup will result only in boldface for
54 @c        reserved words (comments are left alone)
55 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
56 @c        of reserved words include the new reserved words for project files
58 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
59 @c     command must be preceded by two empty lines
61 @c  4. The @item command should be on a line of its own if it is in an
62 @c     @itemize or @enumerate command.
64 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
65 @c     or "ali".
67 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
68 @c     cause the document build to fail.
70 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
71 @c     This command inhibits page breaks, so long examples in a @cartouche can
72 @c     lead to large, ugly patches of empty space on a page.
74 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
75 @c        or the unw flag set.  The unw flag covers topics for both Unix and
76 @c        Windows.
78 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
80 @ifset vms
81 @setfilename gnat_ugn_vms.info
82 @end ifset
84 @ifset unw
85 @setfilename gnat_ugn_unw.info
86 @end ifset
88 @set FSFEDITION
89 @set EDITION GNAT
91 @ifset unw
92 @set PLATFORM Unix and Windows
93 @set FILE gnat_ugn_unw
94 @end ifset
96 @ifset vms
97 @set PLATFORM OpenVMS Alpha
98 @set FILE gnat_ugn_vms
99 @end ifset
103 @settitle @value{EDITION} User's Guide for Native Platforms / @value{PLATFORM}
104 @dircategory GNU Ada tools
105 @direntry
106 * @value{EDITION} User's Guide (@value{FILE}) for Native Platforms / @value{PLATFORM}
107 @end direntry
109 @include gcc-common.texi
111 @setchapternewpage odd
112 @syncodeindex fn cp
113 @c %**end of header
115 @copying
116 Copyright @copyright{} 1995-2004, Free Software Foundation
118 Permission is granted to copy, distribute and/or modify this document
119 under the terms of the GNU Free Documentation License, Version 1.2
120 or any later version published by the Free Software Foundation;
121 with the Invariant Sections being ``GNU Free Documentation License'', with the
122 Front-Cover Texts being
123 ``GNAT User's Guide for Native Platforms / @value{PLATFORM}'',
124 and with no Back-Cover Texts.
125 A copy of the license is included in the section entitled
126 ``GNU Free Documentation License''.
127 @end copying
129 @titlepage
131 @title @value{EDITION} User's Guide
132 @center @titlefont{for Native Platforms}
133 @sp 1
135 @flushright
136 @titlefont{@i{@value{PLATFORM}}}
137 @end flushright
138 @sp 2
140 @subtitle GNAT, The GNU Ada 95 Compiler
141 @subtitle GCC version @value{version-GCC}
143 @author Ada Core Technologies, Inc.
145 @page
146 @vskip 0pt plus 1filll
148 @insertcopying
150 @end titlepage
153 @ifnottex
154 @node Top, About This Guide, (dir), (dir)
155 @top @value{EDITION} User's Guide
157 @noindent
158 @value{EDITION} User's Guide for Native Platforms / @value{PLATFORM}
160 @noindent
161 GNAT, The GNU Ada 95 Compiler@*
162 GCC version @value{version-GCC}@*
164 @noindent
165 Ada Core Technologies, Inc.@*
167 @menu
168 * About This Guide::
169 * Getting Started with GNAT::
170 * The GNAT Compilation Model::
171 * Compiling Using gcc::
172 * Binding Using gnatbind::
173 * Linking Using gnatlink::
174 * The GNAT Make Program gnatmake::
175 * Improving Performance::
176 * Renaming Files Using gnatchop::
177 * Configuration Pragmas::
178 * Handling Arbitrary File Naming Conventions Using gnatname::
179 * GNAT Project Manager::
180 * The Cross-Referencing Tools gnatxref and gnatfind::
181 * The GNAT Pretty-Printer gnatpp::
182 * File Name Krunching Using gnatkr::
183 * Preprocessing Using gnatprep::
184 @ifset vms
185 * The GNAT Run-Time Library Builder gnatlbr::
186 @end ifset
187 * The GNAT Library Browser gnatls::
188 * Cleaning Up Using gnatclean::
189 @ifclear vms
190 * GNAT and Libraries::
191 * Using the GNU make Utility::
192 @end ifclear
193 * Finding Memory Problems::
194 * Creating Sample Bodies Using gnatstub::
195 * Other Utility Programs::
196 * Running and Debugging Ada Programs::
197 @ifset vms
198 * Compatibility with DEC Ada::
199 @end ifset
200 * Platform-Specific Information for the Run-Time Libraries::
201 * Example of Binder Output File::
202 * Elaboration Order Handling in GNAT::
203 * Inline Assembler::
204 * Compatibility and Porting Guide::
205 @ifset unw
206 * Microsoft Windows Topics::
207 @end ifset
208 * GNU Free Documentation License::
209 * Index::
211  --- The Detailed Node Listing ---
213 About This Guide
215 * What This Guide Contains::
216 * What You Should Know before Reading This Guide::
217 * Related Information::
218 * Conventions::
220 Getting Started with GNAT
222 * Running GNAT::
223 * Running a Simple Ada Program::
224 * Running a Program with Multiple Units::
225 * Using the gnatmake Utility::
226 @ifset vms
227 * Editing with Emacs::
228 @end ifset
229 @ifclear vms
230 * Introduction to GPS::
231 * Introduction to Glide and GVD::
232 @end ifclear
234 The GNAT Compilation Model
236 * Source Representation::
237 * Foreign Language Representation::
238 * File Naming Rules::
239 * Using Other File Names::
240 * Alternative File Naming Schemes::
241 * Generating Object Files::
242 * Source Dependencies::
243 * The Ada Library Information Files::
244 * Binding an Ada Program::
245 * Mixed Language Programming::
246 * Building Mixed Ada & C++ Programs::
247 * Comparison between GNAT and C/C++ Compilation Models::
248 * Comparison between GNAT and Conventional Ada Library Models::
249 @ifset vms
250 * Placement of temporary files::
251 @end ifset
253 Foreign Language Representation
255 * Latin-1::
256 * Other 8-Bit Codes::
257 * Wide Character Encodings::
259 Compiling Ada Programs With gcc
261 * Compiling Programs::
262 * Switches for gcc::
263 * Search Paths and the Run-Time Library (RTL)::
264 * Order of Compilation Issues::
265 * Examples::
267 Switches for gcc
269 * Output and Error Message Control::
270 * Warning Message Control::
271 * Debugging and Assertion Control::
272 * Validity Checking::
273 * Style Checking::
274 * Run-Time Checks::
275 * Stack Overflow Checking::
276 * Using gcc for Syntax Checking::
277 * Using gcc for Semantic Checking::
278 * Compiling Ada 83 Programs::
279 * Character Set Control::
280 * File Naming Control::
281 * Subprogram Inlining Control::
282 * Auxiliary Output Control::
283 * Debugging Control::
284 * Exception Handling Control::
285 * Units to Sources Mapping Files::
286 * Integrated Preprocessing::
287 @ifset vms
288 * Return Codes::
289 @end ifset
291 Binding Ada Programs With gnatbind
293 * Running gnatbind::
294 * Switches for gnatbind::
295 * Command-Line Access::
296 * Search Paths for gnatbind::
297 * Examples of gnatbind Usage::
299 Switches for gnatbind
301 * Consistency-Checking Modes::
302 * Binder Error Message Control::
303 * Elaboration Control::
304 * Output Control::
305 * Binding with Non-Ada Main Programs::
306 * Binding Programs with No Main Subprogram::
308 Linking Using gnatlink
310 * Running gnatlink::
311 * Switches for gnatlink::
312 * Setting Stack Size from gnatlink::
313 * Setting Heap Size from gnatlink::
315 The GNAT Make Program gnatmake
317 * Running gnatmake::
318 * Switches for gnatmake::
319 * Mode Switches for gnatmake::
320 * Notes on the Command Line::
321 * How gnatmake Works::
322 * Examples of gnatmake Usage::
325 Improving Performance
326 * Performance Considerations::
327 * Reducing the Size of Ada Executables with gnatelim::
329 Performance Considerations
330 * Controlling Run-Time Checks::
331 * Use of Restrictions::
332 * Optimization Levels::
333 * Debugging Optimized Code::
334 * Inlining of Subprograms::
335 * Optimization and Strict Aliasing::
336 @ifset vms
337 * Coverage Analysis::
338 @end ifset
340 Reducing the Size of Ada Executables with gnatelim
341 * About gnatelim::
342 * Running gnatelim::
343 * Correcting the List of Eliminate Pragmas::
344 * Making Your Executables Smaller::
345 * Summary of the gnatelim Usage Cycle::
347 Renaming Files Using gnatchop
349 * Handling Files with Multiple Units::
350 * Operating gnatchop in Compilation Mode::
351 * Command Line for gnatchop::
352 * Switches for gnatchop::
353 * Examples of gnatchop Usage::
355 Configuration Pragmas
357 * Handling of Configuration Pragmas::
358 * The Configuration Pragmas Files::
360 Handling Arbitrary File Naming Conventions Using gnatname
362 * Arbitrary File Naming Conventions::
363 * Running gnatname::
364 * Switches for gnatname::
365 * Examples of gnatname Usage::
367 GNAT Project Manager
369 * Introduction::
370 * Examples of Project Files::
371 * Project File Syntax::
372 * Objects and Sources in Project Files::
373 * Importing Projects::
374 * Project Extension::
375 * External References in Project Files::
376 * Packages in Project Files::
377 * Variables from Imported Projects::
378 * Naming Schemes::
379 * Library Projects::
380 * Using Third-Party Libraries through Projects::
381 * Stand-alone Library Projects::
382 * Switches Related to Project Files::
383 * Tools Supporting Project Files::
384 * An Extended Example::
385 * Project File Complete Syntax::
388 The Cross-Referencing Tools gnatxref and gnatfind
390 * gnatxref Switches::
391 * gnatfind Switches::
392 * Project Files for gnatxref and gnatfind::
393 * Regular Expressions in gnatfind and gnatxref::
394 * Examples of gnatxref Usage::
395 * Examples of gnatfind Usage::
398 The GNAT Pretty-Printer gnatpp
400 * Switches for gnatpp::
401 * Formatting Rules::
404 File Name Krunching Using gnatkr
406 * About gnatkr::
407 * Using gnatkr::
408 * Krunching Method::
409 * Examples of gnatkr Usage::
411 Preprocessing Using gnatprep
413 * Using gnatprep::
414 * Switches for gnatprep::
415 * Form of Definitions File::
416 * Form of Input Text for gnatprep::
418 @ifset vms
419 The GNAT Run-Time Library Builder gnatlbr
421 * Running gnatlbr::
422 * Switches for gnatlbr::
423 * Examples of gnatlbr Usage::
424 @end ifset
426 The GNAT Library Browser gnatls
428 * Running gnatls::
429 * Switches for gnatls::
430 * Examples of gnatls Usage::
432 Cleaning Up Using gnatclean
434 * Running gnatclean::
435 * Switches for gnatclean::
436 * Examples of gnatclean Usage::
438 @ifclear vms
440 GNAT and Libraries
442 * Introduction to Libraries in GNAT::
443 * General Ada Libraries::
444 * Stand-alone Ada Libraries::
445 * Rebuilding the GNAT Run-Time Library::
447 Using the GNU make Utility
449 * Using gnatmake in a Makefile::
450 * Automatically Creating a List of Directories::
451 * Generating the Command Line Switches::
452 * Overcoming Command Line Length Limits::
453 @end ifclear
455 Finding Memory Problems
457 @ifclear vms
458 * The gnatmem Tool::
459 @end ifclear
460 * The GNAT Debug Pool Facility::
462 @ifclear vms
463 The gnatmem Tool
465 * Running gnatmem::
466 * Switches for gnatmem::
467 * Example of gnatmem Usage::
468 @end ifclear
470 The GNAT Debug Pool Facility
472 Creating Sample Bodies Using gnatstub
474 * Running gnatstub::
475 * Switches for gnatstub::
477 Other Utility Programs
479 * Using Other Utility Programs with GNAT::
480 * The External Symbol Naming Scheme of GNAT::
481 @ifclear vms
482 * Ada Mode for Glide::
483 @end ifclear
484 * Converting Ada Files to html with gnathtml::
486 Running and Debugging Ada Programs
488 * The GNAT Debugger GDB::
489 * Running GDB::
490 * Introduction to GDB Commands::
491 * Using Ada Expressions::
492 * Calling User-Defined Subprograms::
493 * Using the Next Command in a Function::
494 * Ada Exceptions::
495 * Ada Tasks::
496 * Debugging Generic Units::
497 * GNAT Abnormal Termination or Failure to Terminate::
498 * Naming Conventions for GNAT Source Files::
499 * Getting Internal Debugging Information::
500 * Stack Traceback::
502 @ifset vms
503 * LSE::
504 @end ifset
506 @ifset vms
507 Compatibility with DEC Ada
509 * Ada 95 Compatibility::
510 * Differences in the Definition of Package System::
511 * Language-Related Features::
512 * The Package STANDARD::
513 * The Package SYSTEM::
514 * Tasking and Task-Related Features::
515 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
516 * Pragmas and Pragma-Related Features::
517 * Library of Predefined Units::
518 * Bindings::
519 * Main Program Definition::
520 * Implementation-Defined Attributes::
521 * Compiler and Run-Time Interfacing::
522 * Program Compilation and Library Management::
523 * Input-Output::
524 * Implementation Limits::
525 * Tools::
527 Language-Related Features
529 * Integer Types and Representations::
530 * Floating-Point Types and Representations::
531 * Pragmas Float_Representation and Long_Float::
532 * Fixed-Point Types and Representations::
533 * Record and Array Component Alignment::
534 * Address Clauses::
535 * Other Representation Clauses::
537 Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
539 * Assigning Task IDs::
540 * Task IDs and Delays::
541 * Task-Related Pragmas::
542 * Scheduling and Task Priority::
543 * The Task Stack::
544 * External Interrupts::
546 Pragmas and Pragma-Related Features
548 * Restrictions on the Pragma INLINE::
549 * Restrictions on the Pragma INTERFACE::
550 * Restrictions on the Pragma SYSTEM_NAME::
552 Library of Predefined Units
554 * Changes to DECLIB::
556 Bindings
558 * Shared Libraries and Options Files::
559 * Interfaces to C::
560 @end ifset
562 Platform-Specific Information for the Run-Time Libraries
564 * Summary of Run-Time Configurations::
565 * Specifying a Run-Time Library::
566 * Choosing between Native and FSU Threads Libraries::
567 * Choosing the Scheduling Policy::
568 * Solaris-Specific Considerations::
569 * IRIX-Specific Considerations::
570 * Linux-Specific Considerations::
571 * AIX-Specific Considerations::
573 Example of Binder Output File
575 Elaboration Order Handling in GNAT
577 * Elaboration Code in Ada 95::
578 * Checking the Elaboration Order in Ada 95::
579 * Controlling the Elaboration Order in Ada 95::
580 * Controlling Elaboration in GNAT - Internal Calls::
581 * Controlling Elaboration in GNAT - External Calls::
582 * Default Behavior in GNAT - Ensuring Safety::
583 * Treatment of Pragma Elaborate::
584 * Elaboration Issues for Library Tasks::
585 * Mixing Elaboration Models::
586 * What to Do If the Default Elaboration Behavior Fails::
587 * Elaboration for Access-to-Subprogram Values::
588 * Summary of Procedures for Elaboration Control::
589 * Other Elaboration Order Considerations::
591 Inline Assembler
593 * Basic Assembler Syntax::
594 * A Simple Example of Inline Assembler::
595 * Output Variables in Inline Assembler::
596 * Input Variables in Inline Assembler::
597 * Inlining Inline Assembler Code::
598 * Other Asm Functionality::
599 * A Complete Example::
601 Compatibility and Porting Guide
603 * Compatibility with Ada 83::
604 * Implementation-dependent characteristics::
605 * Compatibility with DEC Ada 83::
606 * Compatibility with Other Ada 95 Systems::
607 * Representation Clauses::
609 @ifset unw
610 Microsoft Windows Topics
612 * Using GNAT on Windows::
613 * CONSOLE and WINDOWS subsystems::
614 * Temporary Files::
615 * Mixed-Language Programming on Windows::
616 * Windows Calling Conventions::
617 * Introduction to Dynamic Link Libraries (DLLs)::
618 * Using DLLs with GNAT::
619 * Building DLLs with GNAT::
620 * GNAT and Windows Resources::
621 * Debugging a DLL::
622 * GNAT and COM/DCOM Objects::
623 @end ifset
626 * Index::
627 @end menu
628 @end ifnottex
630 @node About This Guide
631 @unnumbered About This Guide
633 @noindent
634 @ifset vms
635 This guide describes the use of of @value{EDITION},
636 a full language compiler for the Ada
637 95 programming language, implemented on HP OpenVMS Alpha platforms.
638 @end ifset
639 @ifclear vms
640 This guide describes the use of @value{EDITION},
641 a compiler and software development
642 toolset for the full Ada 95 programming language.
643 @end ifclear
644 It describes the features of the compiler and tools, and details
645 how to use them to build Ada 95 applications.
647 @ifset PROEDITION
648 For ease of exposition, ``GNAT Pro'' will be referred to simply as
649 ``GNAT'' in the remainder of this document.
650 @end ifset
654 @menu
655 * What This Guide Contains::
656 * What You Should Know before Reading This Guide::
657 * Related Information::
658 * Conventions::
659 @end menu
661 @node What This Guide Contains
662 @unnumberedsec What This Guide Contains
664 @noindent
665 This guide contains the following chapters:
666 @itemize @bullet
668 @item
669 @ref{Getting Started with GNAT}, describes how to get started compiling
670 and running Ada programs with the GNAT Ada programming environment.
671 @item
672 @ref{The GNAT Compilation Model}, describes the compilation model used
673 by GNAT.
675 @item
676 @ref{Compiling Using gcc}, describes how to compile
677 Ada programs with @code{gcc}, the Ada compiler.
679 @item
680 @ref{Binding Using gnatbind}, describes how to
681 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
682 utility.
684 @item
685 @ref{Linking Using gnatlink},
686 describes @code{gnatlink}, a
687 program that provides for linking using the GNAT run-time library to
688 construct a program. @code{gnatlink} can also incorporate foreign language
689 object units into the executable.
691 @item
692 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
693 utility that automatically determines the set of sources
694 needed by an Ada compilation unit, and executes the necessary compilations
695 binding and link.
697 @item
698 @ref{Improving Performance}, shows various techniques for making your
699 Ada program run faster or take less space.
700 It discusses the effect of the compiler's optimization switch and
701 also describes the @command{gnatelim} tool.
703 @item
704 @ref{Renaming Files Using gnatchop}, describes
705 @code{gnatchop}, a utility that allows you to preprocess a file that
706 contains Ada source code, and split it into one or more new files, one
707 for each compilation unit.
709 @item
710 @ref{Configuration Pragmas}, describes the configuration pragmas
711 handled by GNAT.
713 @item
714 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
715 shows how to override the default GNAT file naming conventions,
716 either for an individual unit or globally.
718 @item
719 @ref{GNAT Project Manager}, describes how to use project files
720 to organize large projects.
722 @item
723 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
724 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
725 way to navigate through sources.
727 @item
728 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
729 version of an Ada source file with control over casing, indentation,
730 comment placement, and other elements of program presentation style.
733 @item
734 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
735 file name krunching utility, used to handle shortened
736 file names on operating systems with a limit on the length of names.
738 @item
739 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
740 preprocessor utility that allows a single source file to be used to
741 generate multiple or parameterized source files, by means of macro
742 substitution.
744 @ifset vms
745 @item
746 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
747 a tool for rebuilding the GNAT run time with user-supplied
748 configuration pragmas.
749 @end ifset
751 @item
752 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
753 utility that displays information about compiled units, including dependences
754 on the corresponding sources files, and consistency of compilations.
756 @item
757 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
758 to delete files that are produced by the compiler, binder and linker.
760 @ifclear vms
761 @item
762 @ref{GNAT and Libraries}, describes the process of creating and using
763 Libraries with GNAT. It also describes how to recompile the GNAT run-time
764 library.
766 @item
767 @ref{Using the GNU make Utility}, describes some techniques for using
768 the GNAT toolset in Makefiles.
769 @end ifclear
771 @item
772 @ref{Finding Memory Problems}, describes
773 @ifclear vms
774 @command{gnatmem}, a utility that monitors dynamic allocation and deallocation
775 and helps detect ``memory leaks'', and
776 @end ifclear
777 the GNAT Debug Pool facility, which helps detect incorrect memory references.
779 @item
780 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
781 a utility that generates empty but compilable bodies for library units.
783 @item
784 @ref{Other Utility Programs}, discusses several other GNAT utilities,
785 including @code{gnathtml}.
787 @item
788 @ref{Running and Debugging Ada Programs}, describes how to run and debug
789 Ada programs.
791 @ifset vms
792 @item
793 @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
794 DEC Ada 83 @footnote{``DEC Ada'' refers to the legacy product originally
795 developed by Digital Equipment Corporation and currently supported by HP.}
796 for OpenVMS Alpha.
797 @end ifset
799 @item
800 @ref{Platform-Specific Information for the Run-Time Libraries},
801 describes the various run-time
802 libraries supported by GNAT on various platforms and explains how to
803 choose a particular library.
805 @item
806 @ref{Example of Binder Output File}, shows the source code for the binder
807 output file for a sample program.
809 @item
810 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
811 you deal with elaboration order issues.
813 @item
814 @ref{Inline Assembler}, shows how to use the inline assembly facility
815 in an Ada program.
817 @item
818 @ref{Compatibility and Porting Guide}, includes sections on compatibility
819 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
820 in porting code from other environments.
822 @ifset unw
823 @item
824 @ref{Microsoft Windows Topics}, presents information relevant to the
825 Microsoft Windows platform.
826 @end ifset
827 @end itemize
830 @c *************************************************
831 @node What You Should Know before Reading This Guide
832 @c *************************************************
833 @unnumberedsec What You Should Know before Reading This Guide
835 @cindex Ada 95 Language Reference Manual
836 @noindent
837 This user's guide assumes that you are familiar with Ada 95 language, as
838 described in the International Standard ANSI/ISO/IEC-8652:1995, January
839 1995.
841 @node Related Information
842 @unnumberedsec Related Information
844 @noindent
845 For further information about related tools, refer to the following
846 documents:
848 @itemize @bullet
849 @item
850 @cite{GNAT Reference Manual}, which contains all reference
851 material for the GNAT implementation of Ada 95.
853 @ifset unw
854 @item
855 @cite{Using the GNAT Programming System}, which describes the GPS
856 integrated development environment.
858 @item
859 @cite{GNAT Programming System Tutorial}, which introduces the
860 main GPS features through examples.
861 @end ifset
863 @item
864 @cite{Ada 95 Language Reference Manual}, which contains all reference
865 material for the Ada 95 programming language.
867 @item
868 @cite{Debugging with GDB}
869 @ifset vms
870 , located in the GNU:[DOCS] directory,
871 @end ifset
872 contains all details on the use of the GNU source-level debugger.
874 @item
875 @cite{GNU Emacs Manual}
876 @ifset vms
877 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
878 @end ifset
879 contains full information on the extensible editor and programming
880 environment Emacs.
882 @end itemize
884 @c **************
885 @node Conventions
886 @unnumberedsec Conventions
887 @cindex Conventions
888 @cindex Typographical conventions
890 @noindent
891 Following are examples of the typographical and graphic conventions used
892 in this guide:
894 @itemize @bullet
895 @item
896 @code{Functions}, @code{utility program names}, @code{standard names},
897 and @code{classes}.
899 @item
900 @samp{Option flags}
902 @item
903 @file{File Names}, @file{button names}, and @file{field names}.
905 @item
906 @var{Variables}.
908 @item
909 @emph{Emphasis}.
911 @item
912 [optional information or parameters]
914 @item
915 Examples are described by text
916 @smallexample
917 and then shown this way.
918 @end smallexample
919 @end itemize
921 @noindent
922 Commands that are entered by the user are preceded in this manual by the
923 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
924 uses this sequence as a prompt, then the commands will appear exactly as
925 you see them in the manual. If your system uses some other prompt, then
926 the command will appear with the @code{$} replaced by whatever prompt
927 character you are using.
929 @ifset unw
930 Full file names are shown with the ``@code{/}'' character
931 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
932 If you are using GNAT on a Windows platform, please note that
933 the ``@code{\}'' character should be used instead.
934 @end ifset
938 @c ****************************
939 @node Getting Started with GNAT
940 @chapter Getting Started with GNAT
942 @noindent
943 This chapter describes some simple ways of using GNAT to build
944 executable Ada programs.
945 @ifset unw
946 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
947 show how to use the command line environment.
948 @ref{Introduction to Glide and GVD}, provides a brief
949 introduction to the visually-oriented IDE for GNAT.
950 Supplementing Glide on some platforms is GPS, the
951 GNAT Programming System, which offers a richer graphical
952 ``look and feel'', enhanced configurability, support for
953 development in other programming language, comprehensive
954 browsing features, and many other capabilities.
955 For information on GPS please refer to
956 @cite{Using the GNAT Programming System}.
957 @end ifset
959 @menu
960 * Running GNAT::
961 * Running a Simple Ada Program::
962 * Running a Program with Multiple Units::
963 * Using the gnatmake Utility::
964 @ifset vms
965 * Editing with Emacs::
966 @end ifset
967 @ifclear vms
968 * Introduction to GPS::
969 * Introduction to Glide and GVD::
970 @end ifclear
971 @end menu
973 @node Running GNAT
974 @section Running GNAT
976 @noindent
977 Three steps are needed to create an executable file from an Ada source
978 file:
980 @enumerate
981 @item
982 The source file(s) must be compiled.
983 @item
984 The file(s) must be bound using the GNAT binder.
985 @item
986 All appropriate object files must be linked to produce an executable.
987 @end enumerate
989 @noindent
990 All three steps are most commonly handled by using the @code{gnatmake}
991 utility program that, given the name of the main program, automatically
992 performs the necessary compilation, binding and linking steps.
995 @node Running a Simple Ada Program
996 @section Running a Simple Ada Program
998 @noindent
999 Any text editor may be used to prepare an Ada program.
1000 @ifclear vms
1001 If @code{Glide} is
1002 used, the optional Ada mode may be helpful in laying out the program.
1003 @end ifclear
1005 program text is a normal text file. We will suppose in our initial
1006 example that you have used your editor to prepare the following
1007 standard format text file:
1009 @smallexample @c ada
1010 @cartouche
1011 with Ada.Text_IO; use Ada.Text_IO;
1012 procedure Hello is
1013 begin
1014    Put_Line ("Hello WORLD!");
1015 end Hello;
1016 @end cartouche
1017 @end smallexample
1019 @noindent
1020 This file should be named @file{hello.adb}.
1021 With the normal default file naming conventions, GNAT requires
1022 that each file
1023 contain a single compilation unit whose file name is the
1024 unit name,
1025 with periods replaced by hyphens; the
1026 extension is @file{ads} for a
1027 spec and @file{adb} for a body.
1028 You can override this default file naming convention by use of the
1029 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1030 Alternatively, if you want to rename your files according to this default
1031 convention, which is probably more convenient if you will be using GNAT
1032 for all your compilations, then the @code{gnatchop} utility
1033 can be used to generate correctly-named source files
1034 (@pxref{Renaming Files Using gnatchop}).
1036 You can compile the program using the following command (@code{$} is used
1037 as the command prompt in the examples in this document):
1039 @smallexample
1040 $ gcc -c hello.adb
1041 @end smallexample
1043 @noindent
1044 @code{gcc} is the command used to run the compiler. This compiler is
1045 capable of compiling programs in several languages, including Ada 95 and
1046 C. It assumes that you have given it an Ada program if the file extension is
1047 either @file{.ads} or @file{.adb}, and it will then call
1048 the GNAT compiler to compile the specified file.
1050 @ifclear vms
1051 The @option{-c} switch is required. It tells @command{gcc} to only do a
1052 compilation. (For C programs, @command{gcc} can also do linking, but this
1053 capability is not used directly for Ada programs, so the @option{-c}
1054 switch must always be present.)
1055 @end ifclear
1057 This compile command generates a file
1058 @file{hello.o}, which is the object
1059 file corresponding to your Ada program. It also generates
1060 an ``Ada Library Information'' file @file{hello.ali},
1061 which contains additional information used to check
1062 that an Ada program is consistent.
1063 To build an executable file,
1064 use @code{gnatbind} to bind the program
1065 and @code{gnatlink} to link it. The
1066 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1067 @file{ALI} file, but the default extension of @file{.ali} can
1068 be omitted. This means that in the most common case, the argument
1069 is simply the name of the main program:
1071 @smallexample
1072 $ gnatbind hello
1073 $ gnatlink hello
1074 @end smallexample
1076 @noindent
1077 A simpler method of carrying out these steps is to use
1078 @command{gnatmake},
1079 a master program that invokes all the required
1080 compilation, binding and linking tools in the correct order. In particular,
1081 @command{gnatmake} automatically recompiles any sources that have been
1082 modified since they were last compiled, or sources that depend
1083 on such modified sources, so that ``version skew'' is avoided.
1084 @cindex Version skew (avoided by @command{gnatmake})
1086 @smallexample
1087 $ gnatmake hello.adb
1088 @end smallexample
1090 @noindent
1091 The result is an executable program called @file{hello}, which can be
1092 run by entering:
1094 @c The following should be removed (BMB 2001-01-23)
1095 @c @smallexample
1096 @c $ ^./hello^$ RUN HELLO^
1097 @c @end smallexample
1099 @smallexample
1100 $ hello
1101 @end smallexample
1103 @noindent
1104 assuming that the current directory is on the search path
1105 for executable programs.
1107 @noindent
1108 and, if all has gone well, you will see
1110 @smallexample
1111 Hello WORLD!
1112 @end smallexample
1114 @noindent
1115 appear in response to this command.
1118 @c ****************************************
1119 @node Running a Program with Multiple Units
1120 @section Running a Program with Multiple Units
1122 @noindent
1123 Consider a slightly more complicated example that has three files: a
1124 main program, and the spec and body of a package:
1126 @smallexample @c ada
1127 @cartouche
1128 @group
1129 package Greetings is
1130    procedure Hello;
1131    procedure Goodbye;
1132 end Greetings;
1134 with Ada.Text_IO; use Ada.Text_IO;
1135 package body Greetings is
1136    procedure Hello is
1137    begin
1138       Put_Line ("Hello WORLD!");
1139    end Hello;
1141    procedure Goodbye is
1142    begin
1143       Put_Line ("Goodbye WORLD!");
1144    end Goodbye;
1145 end Greetings;
1146 @end group
1148 @group
1149 with Greetings;
1150 procedure Gmain is
1151 begin
1152    Greetings.Hello;
1153    Greetings.Goodbye;
1154 end Gmain;
1155 @end group
1156 @end cartouche
1157 @end smallexample
1159 @noindent
1160 Following the one-unit-per-file rule, place this program in the
1161 following three separate files:
1163 @table @file
1164 @item greetings.ads
1165 spec of package @code{Greetings}
1167 @item greetings.adb
1168 body of package @code{Greetings}
1170 @item gmain.adb
1171 body of main program
1172 @end table
1174 @noindent
1175 To build an executable version of
1176 this program, we could use four separate steps to compile, bind, and link
1177 the program, as follows:
1179 @smallexample
1180 $ gcc -c gmain.adb
1181 $ gcc -c greetings.adb
1182 $ gnatbind gmain
1183 $ gnatlink gmain
1184 @end smallexample
1186 @noindent
1187 Note that there is no required order of compilation when using GNAT.
1188 In particular it is perfectly fine to compile the main program first.
1189 Also, it is not necessary to compile package specs in the case where
1190 there is an accompanying body; you only need to compile the body. If you want
1191 to submit these files to the compiler for semantic checking and not code
1192 generation, then use the
1193 @option{-gnatc} switch:
1195 @smallexample
1196 $ gcc -c greetings.ads -gnatc
1197 @end smallexample
1199 @noindent
1200 Although the compilation can be done in separate steps as in the
1201 above example, in practice it is almost always more convenient
1202 to use the @code{gnatmake} tool. All you need to know in this case
1203 is the name of the main program's source file. The effect of the above four
1204 commands can be achieved with a single one:
1206 @smallexample
1207 $ gnatmake gmain.adb
1208 @end smallexample
1210 @noindent
1211 In the next section we discuss the advantages of using @code{gnatmake} in
1212 more detail.
1214 @c *****************************
1215 @node Using the gnatmake Utility
1216 @section Using the @command{gnatmake} Utility
1218 @noindent
1219 If you work on a program by compiling single components at a time using
1220 @code{gcc}, you typically keep track of the units you modify. In order to
1221 build a consistent system, you compile not only these units, but also any
1222 units that depend on the units you have modified.
1223 For example, in the preceding case,
1224 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1225 you edit @file{greetings.ads}, you must recompile both
1226 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1227 units that depend on @file{greetings.ads}.
1229 @code{gnatbind} will warn you if you forget one of these compilation
1230 steps, so that it is impossible to generate an inconsistent program as a
1231 result of forgetting to do a compilation. Nevertheless it is tedious and
1232 error-prone to keep track of dependencies among units.
1233 One approach to handle the dependency-bookkeeping is to use a
1234 makefile. However, makefiles present maintenance problems of their own:
1235 if the dependencies change as you change the program, you must make
1236 sure that the makefile is kept up-to-date manually, which is also an
1237 error-prone process.
1239 The @code{gnatmake} utility takes care of these details automatically.
1240 Invoke it using either one of the following forms:
1242 @smallexample
1243 $ gnatmake gmain.adb
1244 $ gnatmake ^gmain^GMAIN^
1245 @end smallexample
1247 @noindent
1248 The argument is the name of the file containing the main program;
1249 you may omit the extension. @code{gnatmake}
1250 examines the environment, automatically recompiles any files that need
1251 recompiling, and binds and links the resulting set of object files,
1252 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1253 In a large program, it
1254 can be extremely helpful to use @code{gnatmake}, because working out by hand
1255 what needs to be recompiled can be difficult.
1257 Note that @code{gnatmake}
1258 takes into account all the Ada 95 rules that
1259 establish dependencies among units. These include dependencies that result
1260 from inlining subprogram bodies, and from
1261 generic instantiation. Unlike some other
1262 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1263 found by the compiler on a previous compilation, which may possibly
1264 be wrong when sources change. @code{gnatmake} determines the exact set of
1265 dependencies from scratch each time it is run.
1267 @ifset vms
1268 @node Editing with Emacs
1269 @section Editing with Emacs
1270 @cindex Emacs
1272 @noindent
1273 Emacs is an extensible self-documenting text editor that is available in a
1274 separate VMSINSTAL kit.
1276 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1277 click on the Emacs Help menu and run the Emacs Tutorial.
1278 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1279 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1281 Documentation on Emacs and other tools is available in Emacs under the
1282 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1283 use the middle mouse button to select a topic (e.g. Emacs).
1285 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1286 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1287 get to the Emacs manual.
1288 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1289 prompt.
1291 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1292 which is sufficiently extensible to provide for a complete programming
1293 environment and shell for the sophisticated user.
1294 @end ifset
1296 @ifclear vms
1297 @node Introduction to GPS
1298 @section Introduction to GPS
1299 @cindex GPS (GNAT Programming System)
1300 @cindex GNAT Programming System (GPS)
1301 @noindent
1302 Although the command line interface (@command{gnatmake}, etc.) alone
1303 is sufficient, a graphical Interactive Development
1304 Environment can make it easier for you to compose, navigate, and debug
1305 programs.  This section describes the main features of GPS
1306 (``GNAT Programming System''), the GNAT graphical IDE.
1307 You will see how to use GPS to build and debug an executable, and
1308 you will also learn some of the basics of the GNAT ``project'' facility.
1310 GPS enables you to do much more than is presented here;
1311 e.g., you can produce a call graph, interface to a third-party
1312 Version Control System, and inspect the generated assembly language
1313 for a program.
1314 Indeed, GPS also supports languages other than Ada.
1315 Such additional information, and an explanation of all of the GPS menu
1316 items. may be found in the on-line help, which includes
1317 a user's guide and a tutorial (these are also accessible from the GNAT
1318 startup menu).
1320 @menu
1321 * Building a New Program with GPS::
1322 * Simple Debugging with GPS::
1323 @end menu
1326 @node Building a New Program with GPS
1327 @subsection Building a New Program with GPS
1328 @noindent
1329 GPS invokes the GNAT compilation tools using information
1330 contained in a @emph{project} (also known as a @emph{project file}):
1331 a collection of properties such
1332 as source directories, identities of main subprograms, tool switches, etc.,
1333 and their associated values.
1334 (See @ref{GNAT Project Manager}, for details.)
1335 In order to run GPS, you will need to either create a new project
1336 or else open an existing one.
1338 This section will explain how you can use GPS to create a project,
1339 to associate Ada source files with a project, and to build and run
1340 programs.
1342 @enumerate
1343 @item @emph{Creating a project}
1345 Invoke GPS, either from the command line or the platform's IDE.
1346 After it starts, GPS will display a ``Welcome'' screen with three
1347 radio buttons:
1349 @itemize @bullet
1350 @item
1351 @code{Start with default project in directory}
1353 @item
1354 @code{Create new project with wizard}
1356 @item
1357 @code{Open existing project}
1358 @end itemize
1360 @noindent
1361 Select @code{Create new project with wizard} and press @code{OK}.
1362 A new window will appear.  In the text box labeled with
1363 @code{Enter the name of the project to create}, type @file{sample}
1364 as the project name.
1365 In the next box, browse to choose the directory in which you
1366 would like to create the project file.
1367 After selecting an appropriate directory, press @code{Forward}.
1369 A window will appear with the title
1370 @code{Version Control System Configuration}.
1371 Simply press @code{Forward}.
1373 A window will appear with the title
1374 @code{Please select the source directories for this project}.
1375 The directory that you specified for the project file will be selected
1376 by default as the one to use for sources; simply press @code{Forward}.
1378 A window will appear with the title
1379 @code{Please select the build directory for this project}.
1380 The directory that you specified for the project file will be selected
1381 by default for object files and executables;
1382 simply press @code{Forward}.
1384 A window will appear with the title
1385 @code{Please select the main units for this project}.
1386 You will supply this information later, after creating the source file.
1387 Simply press @code{Forward} for now.
1389 A window will appear with the title
1390 @code{Please select the switches to build the project}.
1391 Press @code{Apply}.  This will create a project file named
1392 @file{sample.prj} in the directory that you had specified.
1394 @item @emph{Creating and saving the source file}
1396 After you create the new project, a GPS window will appear, which is
1397 partitioned into two main sections:
1399 @itemize @bullet
1400 @item
1401 A @emph{Workspace area}, initially greyed out, which you will use for
1402 creating and editing source files
1404 @item
1405 Directly below, a @emph{Messages area}, which initially displays a
1406 ``Welcome'' message.
1407 (If the Messages area is not visible, drag its border upward to expand it.)
1408 @end itemize
1410 @noindent
1411 Select @code{File} on the menu bar, and then the @code{New} command.
1412 The Workspace area will become white, and you can now
1413 enter the source program explicitly.
1414 Type the following text
1416 @smallexample @c ada
1417 @group
1418 with Ada.Text_IO; use Ada.Text_IO;
1419 procedure Hello is
1420 begin
1421   Put_Line("Hello from GPS!");
1422 end Hello;
1423 @end group
1424 @end smallexample
1426 @noindent
1427 Select @code{File}, then @code{Save As}, and enter the source file name
1428 @file{hello.adb}.
1429 The file will be saved in the same directory you specified as the
1430 location of the default project file.
1433 @item @emph{Updating the project file}
1435 You need to add the new source file to the project.
1436 To do this, select
1437 the @code{Project} menu and then @code{Edit project properties}.
1438 Click the @code{Main files} tab on the left, and then the
1439 @code{Add} button.
1440 Choose @file{hello.adb} from the list, and press @code{Open}.
1441 The project settings window will reflect this action.
1442 Click @code{OK}.
1444 @item @emph{Building and running the program}
1446 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1447 and select @file{hello.adb}.
1448 The Messages window will display the resulting invocations of @command{gcc},
1449 @command{gnatbind}, and @command{gnatlink}
1450 (reflecting the default switch settings from the
1451 project file that you created) and then a ``successful compilation/build''
1452 message.
1454 To run the program, choose the @code{Build} menu, then @code{Run}, and
1455 select @command{hello}.
1456 An @emph{Arguments Selection} window will appear.
1457 There are no command line arguments, so just click @code{OK}.
1459 The Messages window will now display the program's output (the string
1460 @code{Hello from GPS}), and at the bottom of the GPS window a status
1461 update is displayed (@code{Run: hello}).
1462 Close the GPS window (or select @code{File}, then @code{Exit}) to
1463 terminate this GPS session.
1464 @end enumerate
1468 @node Simple Debugging with GPS
1469 @subsection Simple Debugging with GPS
1470 @noindent
1471 This section illustrates basic debugging techniques (setting breakpoints,
1472 examining/modifying variables, single stepping).
1474 @enumerate
1475 @item @emph{Opening a project}
1477 Start GPS and select @code{Open existing project}; browse to
1478 specify the project file @file{sample.prj} that you had created in the
1479 earlier example.
1481 @item @emph{Creating a source file}
1483 Select @code{File}, then @code{New}, and type in the following program:
1485 @smallexample @c ada
1486 @group
1487 with Ada.Text_IO; use Ada.Text_IO;
1488 procedure Example is
1489    Line : String (1..80);
1490    N    : Natural;
1491 begin
1492    Put_Line("Type a line of text at each prompt; an empty line to exit");
1493    loop
1494       Put(": ");
1495       Get_Line (Line, N);
1496       Put_Line (Line (1..N) );
1497       exit when N=0;
1498    end loop;
1499 end Example;
1500 @end group
1501 @end smallexample
1503 @noindent
1504 Select @code{File}, then @code{Save as}, and enter the file name
1505 @file{example.adb}.
1507 @item @emph{Updating the project file}
1509 Add @code{Example} as a new main unit for the project:
1510 @enumerate a
1511 @item
1512 Select @code{Project}, then @code{Edit Project Properties}.
1514 @item
1515 Select the @code{Main files} tab, click @code{Add}, then
1516 select the file @file{example.adb} from the list, and
1517 click @code{Open}.
1518 You will see the file name appear in the list of main units
1520 @item
1521 Click @code{OK}
1522 @end enumerate
1524 @item @emph{Building/running the executable}
1526 To build the executable
1527 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1529 Run the program to see its effect (in the Messages area).
1530 Each line that you enter is displayed; an empty line will
1531 cause the loop to exit and the program to terminate.
1533 @item @emph{Debugging the program}
1535 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1536 which are required for debugging, are on by default when you create
1537 a new project.
1538 Thus unless you intentionally remove these settings, you will be able
1539 to debug any program that you develop using GPS.
1541 @enumerate a
1542 @item @emph{Initializing}
1544 Select @code{Debug}, then @code{Initialize}, then @file{example}
1546 @item @emph{Setting a breakpoint}
1548 After performing the initialization step, you will observe a small
1549 icon to the right of each line number.
1550 This serves as a toggle for breakpoints; clicking the icon will
1551 set a breakpoint at the corresponding line (the icon will change to
1552 a red circle with an ``x''), and clicking it again
1553 will remove the breakpoint / reset the icon.
1555 For purposes of this example, set a breakpoint at line 10 (the
1556 statement @code{Put_Line@ (Line@ (1..N));}
1558 @item @emph{Starting program execution}
1560 Select @code{Debug}, then @code{Run}.  When the
1561 @code{Program Arguments} window appears, click @code{OK}.
1562 A console window will appear; enter some line of text,
1563 e.g. @code{abcde}, at the prompt.
1564 The program will pause execution when it gets to the
1565 breakpoint, and the corresponding line is highlighted.
1567 @item @emph{Examining a variable}
1569 Move the mouse over one of the occurrences of the variable @code{N}.
1570 You will see the value (5) displayed, in ``tool tip'' fashion.
1571 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1572 You will see information about @code{N} appear in the @code{Debugger Data}
1573 pane, showing the value as 5.
1576 @item @emph{Assigning a new value to a variable}
1578 Right click on the @code{N} in the @code{Debugger Data} pane, and
1579 select @code{Set value of N}.
1580 When the input window appears, enter the value @code{4} and click
1581 @code{OK}.
1582 This value does not automatically appear in the @code{Debugger Data}
1583 pane; to see it, right click again on the @code{N} in the
1584 @code{Debugger Data} pane and select @code{Update value}.
1585 The new value, 4, will appear in red.
1587 @item @emph{Single stepping}
1589 Select @code{Debug}, then @code{Next}.
1590 This will cause the next statement to be executed, in this case the
1591 call of @code{Put_Line} with the string slice.
1592 Notice in the console window that the displayed string is simply
1593 @code{abcd} and not @code{abcde} which you had entered.
1594 This is because the upper bound of the slice is now 4 rather than 5.
1596 @item @emph{Removing a breakpoint}
1598 Toggle the breakpoint icon at line 10.
1600 @item @emph{Resuming execution from a breakpoint}
1602 Select @code{Debug}, then @code{Continue}.
1603 The program will reach the next iteration of the loop, and
1604 wait for input after displaying the prompt.
1605 This time, just hit the @kbd{Enter} key.
1606 The value of @code{N} will be 0, and the program will terminate.
1607 The console window will disappear.
1608 @end enumerate
1609 @end enumerate
1612 @node Introduction to Glide and GVD
1613 @section Introduction to Glide and GVD
1614 @cindex Glide
1615 @cindex GVD
1616 @noindent
1617 This section describes the main features of Glide,
1618 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1619 the GNU Visual Debugger.
1620 These tools may be present in addition to, or in place of, GPS on some
1621 platforms.
1622 Additional information on Glide and GVD may be found
1623 in the on-line help for these tools.
1625 @menu
1626 * Building a New Program with Glide::
1627 * Simple Debugging with GVD::
1628 * Other Glide Features::
1629 @end menu
1631 @node Building a New Program with Glide
1632 @subsection Building a New Program with Glide
1633 @noindent
1634 The simplest way to invoke Glide is to enter @command{glide}
1635 at the command prompt.  It will generally be useful to issue this
1636 as a background command, thus allowing you to continue using
1637 your command window for other purposes while Glide is running:
1639 @smallexample
1640 $ glide&
1641 @end smallexample
1643 @noindent
1644 Glide will start up with an initial screen displaying the top-level menu items
1645 as well as some other information.  The menu selections are as follows
1646 @itemize @bullet
1647 @item @code{Buffers}
1648 @item @code{Files}
1649 @item @code{Tools}
1650 @item @code{Edit}
1651 @item @code{Search}
1652 @item @code{Mule}
1653 @item @code{Glide}
1654 @item @code{Help}
1655 @end itemize
1657 @noindent
1658 For this introductory example, you will need to create a new Ada source file.
1659 First, select the @code{Files} menu.  This will pop open a menu with around
1660 a dozen or so items.  To create a file, select the @code{Open file...} choice.
1661 Depending on the platform, you may see a pop-up window where you can browse
1662 to an appropriate directory and then enter the file name, or else simply
1663 see a line at the bottom of the Glide window where you can likewise enter
1664 the file name.  Note that in Glide, when you attempt to open a non-existent
1665 file, the effect is to create a file with that name.  For this example enter
1666 @file{hello.adb} as the name of the file.
1668 A new buffer will now appear, occupying the entire Glide window,
1669 with the file name at the top.  The menu selections are slightly different
1670 from the ones you saw on the opening screen; there is an @code{Entities} item,
1671 and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses
1672 the file extension to identify the source language, so @file{adb} indicates
1673 an Ada source file.
1675 You will enter some of the source program lines explicitly,
1676 and use the syntax-oriented template mechanism to enter other lines.
1677 First, type the following text:
1678 @smallexample
1679 with Ada.Text_IO; use Ada.Text_IO;
1680 procedure Hello is
1681 begin
1682 @end smallexample
1684 @noindent
1685 Observe that Glide uses different colors to distinguish reserved words from
1686 identifiers.  Also, after the @code{procedure Hello is} line, the cursor is
1687 automatically indented in anticipation of declarations.  When you enter
1688 @code{begin}, Glide recognizes that there are no declarations and thus places
1689 @code{begin} flush left.  But after the @code{begin} line the cursor is again
1690 indented, where the statement(s) will be placed.
1692 The main part of the program will be a @code{for} loop.  Instead of entering
1693 the text explicitly, however, use a statement template.  Select the @code{Ada}
1694 item on the top menu bar, move the mouse to the @code{Statements} item,
1695 and you will see a large selection of alternatives.  Choose @code{for loop}.
1696 You will be prompted (at the bottom of the buffer) for a loop name;
1697 simply press the @key{Enter} key since a loop name is not needed.
1698 You should see the beginning of a @code{for} loop appear in the source
1699 program window.  You will now be prompted for the name of the loop variable;
1700 enter a line with the identifier @code{ind} (lower case).  Note that,
1701 by default, Glide capitalizes the name (you can override such behavior
1702 if you wish, although this is outside the scope of this introduction).
1703 Next, Glide prompts you for the loop range; enter a line containing
1704 @code{1..5} and you will see this also appear in the source program,
1705 together with the remaining elements of the @code{for} loop syntax.
1707 Next enter the statement (with an intentional error, a missing semicolon)
1708 that will form the body of the loop:
1709 @smallexample
1710 Put_Line("Hello, World" & Integer'Image(I))
1711 @end smallexample
1713 @noindent
1714 Finally, type @code{end Hello;} as the last line in the program.
1715 Now save the file: choose the @code{File} menu item, and then the
1716 @code{Save buffer} selection.  You will see a message at the bottom
1717 of the buffer confirming that the file has been saved.
1719 You are now ready to attempt to build the program.  Select the @code{Ada}
1720 item from the top menu bar.  Although we could choose simply to compile
1721 the file, we will instead attempt to do a build (which invokes
1722 @command{gnatmake}) since, if the compile is successful, we want to build
1723 an executable.  Thus select @code{Ada build}.  This will fail because of the
1724 compilation error, and you will notice that the Glide window has been split:
1725 the top window contains the source file, and the bottom window contains the
1726 output from the GNAT tools. Glide allows you to navigate from a compilation
1727 error to the source file position corresponding to the error: click the
1728 middle mouse button (or simultaneously press the left and right buttons,
1729 on a two-button mouse) on the diagnostic line in the tool window.  The
1730 focus will shift to the source window, and the cursor will be positioned
1731 on the character at which the error was detected.
1733 Correct the error: type in a semicolon to terminate the statement.
1734 Although you can again save the file explicitly, you can also simply invoke
1735 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1736 This time the build will succeed; the tool output window shows you the
1737 options that are supplied by default.  The GNAT tools' output (e.g.
1738 object and ALI files, executable) will go in the directory from which
1739 Glide was launched.
1741 To execute the program, choose @code{Ada} and then @code{Run}.
1742 You should see the program's output displayed in the bottom window:
1744 @smallexample
1745 Hello, world 1
1746 Hello, world 2
1747 Hello, world 3
1748 Hello, world 4
1749 Hello, world 5
1750 @end smallexample
1752 @node Simple Debugging with GVD
1753 @subsection Simple Debugging with GVD
1755 @noindent
1756 This section describes how to set breakpoints, examine/modify variables,
1757 and step through execution.
1759 In order to enable debugging, you need to pass the @option{-g} switch
1760 to both the compiler and to @command{gnatlink}.  If you are using
1761 the command line, passing @option{-g} to @command{gnatmake} will have
1762 this effect.  You can then launch GVD, e.g. on the @code{hello} program,
1763 by issuing the command:
1765 @smallexample
1766 $ gvd hello
1767 @end smallexample
1769 @noindent
1770 If you are using Glide, then @option{-g} is passed to the relevant tools
1771 by default when you do a build.  Start the debugger by selecting the
1772 @code{Ada} menu item, and then @code{Debug}.
1774 GVD comes up in a multi-part window.  One pane shows the names of files
1775 comprising your executable; another pane shows the source code of the current
1776 unit (initially your main subprogram), another pane shows the debugger output
1777 and user interactions, and the fourth pane (the data canvas at the top
1778 of the window) displays data objects that you have selected.
1780 To the left of the source file pane, you will notice green dots adjacent
1781 to some lines.  These are lines for which object code exists and where
1782 breakpoints can thus be set.  You set/reset a breakpoint by clicking
1783 the green dot.  When a breakpoint is set, the dot is replaced by an @code{X}
1784 in a red circle.  Clicking the circle toggles the breakpoint off,
1785 and the red circle is replaced by the green dot.
1787 For this example, set a breakpoint at the statement where @code{Put_Line}
1788 is invoked.
1790 Start program execution by selecting the @code{Run} button on the top menu bar.
1791 (The @code{Start} button will also start your program, but it will
1792 cause program execution to break at the entry to your main subprogram.)
1793 Evidence of reaching the breakpoint will appear: the source file line will be
1794 highlighted, and the debugger interactions pane will display
1795 a relevant message.
1797 You can examine the values of variables in several ways.  Move the mouse
1798 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1799 the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind}
1800 and select @code{Display Ind}; a box showing the variable's name and value
1801 will appear in the data canvas.
1803 Although a loop index is a constant with respect to Ada semantics,
1804 you can change its value in the debugger.  Right-click in the box
1805 for @code{Ind}, and select the @code{Set Value of Ind} item.
1806 Enter @code{2} as the new value, and press @command{OK}.
1807 The box for @code{Ind} shows the update.
1809 Press the @code{Step} button on the top menu bar; this will step through
1810 one line of program text (the invocation of @code{Put_Line}), and you can
1811 observe the effect of having modified @code{Ind} since the value displayed
1812 is @code{2}.
1814 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1815 button.  You will see the remaining output lines displayed in the debugger
1816 interaction window, along with a message confirming normal program
1817 termination.
1819 @node Other Glide Features
1820 @subsection Other Glide Features
1822 @noindent
1823 You may have observed that some of the menu selections contain abbreviations;
1824 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1825 These are @emph{shortcut keys} that you can use instead of selecting
1826 menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1827 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1828 of selecting @code{Files} and then @code{Open file...}.
1830 To abort a Glide command, type @key{Ctrl-g}.
1832 If you want Glide to start with an existing source file, you can either
1833 launch Glide as above and then open the file via @code{Files} @result{}
1834 @code{Open file...}, or else simply pass the name of the source file
1835 on the command line:
1837 @smallexample
1838 $ glide hello.adb&
1839 @end smallexample
1841 @noindent
1842 While you are using Glide, a number of @emph{buffers} exist.
1843 You create some explicitly; e.g., when you open/create a file.
1844 Others arise as an effect of the commands that you issue; e.g., the buffer
1845 containing the output of the tools invoked during a build.  If a buffer
1846 is hidden, you can bring it into a visible window by first opening
1847 the @code{Buffers} menu and then selecting the desired entry.
1849 If a buffer occupies only part of the Glide screen and you want to expand it
1850 to fill the entire screen, then click in the buffer and then select
1851 @code{Files} @result{} @code{One Window}.
1853 If a window is occupied by one buffer and you want to split the window
1854 to bring up a second buffer, perform the following steps:
1855 @itemize @bullet
1856 @item Select @code{Files} @result{} @code{Split Window};
1857 this will produce two windows each of which holds the original buffer
1858 (these are not copies, but rather different views of the same buffer contents)
1860 @item With the focus in one of the windows,
1861 select the desired buffer from the @code{Buffers} menu
1862 @end itemize
1864 @noindent
1865 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1866 @end ifclear
1868 @node The GNAT Compilation Model
1869 @chapter The GNAT Compilation Model
1870 @cindex GNAT compilation model
1871 @cindex Compilation model
1873 @menu
1874 * Source Representation::
1875 * Foreign Language Representation::
1876 * File Naming Rules::
1877 * Using Other File Names::
1878 * Alternative File Naming Schemes::
1879 * Generating Object Files::
1880 * Source Dependencies::
1881 * The Ada Library Information Files::
1882 * Binding an Ada Program::
1883 * Mixed Language Programming::
1884 * Building Mixed Ada & C++ Programs::
1885 * Comparison between GNAT and C/C++ Compilation Models::
1886 * Comparison between GNAT and Conventional Ada Library Models::
1887 @ifset vms
1888 * Placement of temporary files::
1889 @end ifset
1890 @end menu
1892 @noindent
1893 This chapter describes the compilation model used by GNAT. Although
1894 similar to that used by other languages, such as C and C++, this model
1895 is substantially different from the traditional Ada compilation models,
1896 which are based on a library. The model is initially described without
1897 reference to the library-based model. If you have not previously used an
1898 Ada compiler, you need only read the first part of this chapter. The
1899 last section describes and discusses the differences between the GNAT
1900 model and the traditional Ada compiler models. If you have used other
1901 Ada compilers, this section will help you to understand those
1902 differences, and the advantages of the GNAT model.
1904 @node Source Representation
1905 @section Source Representation
1906 @cindex Latin-1
1908 @noindent
1909 Ada source programs are represented in standard text files, using
1910 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1911 7-bit ASCII set, plus additional characters used for
1912 representing foreign languages (@pxref{Foreign Language Representation}
1913 for support of non-USA character sets). The format effector characters
1914 are represented using their standard ASCII encodings, as follows:
1916 @table @code
1917 @item VT
1918 @findex VT
1919 Vertical tab, @code{16#0B#}
1921 @item HT
1922 @findex HT
1923 Horizontal tab, @code{16#09#}
1925 @item CR
1926 @findex CR
1927 Carriage return, @code{16#0D#}
1929 @item LF
1930 @findex LF
1931 Line feed, @code{16#0A#}
1933 @item FF
1934 @findex FF
1935 Form feed, @code{16#0C#}
1936 @end table
1938 @noindent
1939 Source files are in standard text file format. In addition, GNAT will
1940 recognize a wide variety of stream formats, in which the end of physical
1941 physical lines is marked by any of the following sequences:
1942 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1943 in accommodating files that are imported from other operating systems.
1945 @cindex End of source file
1946 @cindex Source file, end
1947 @findex SUB
1948 The end of a source file is normally represented by the physical end of
1949 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1950 recognized as signalling the end of the source file. Again, this is
1951 provided for compatibility with other operating systems where this
1952 code is used to represent the end of file.
1954 Each file contains a single Ada compilation unit, including any pragmas
1955 associated with the unit. For example, this means you must place a
1956 package declaration (a package @dfn{spec}) and the corresponding body in
1957 separate files. An Ada @dfn{compilation} (which is a sequence of
1958 compilation units) is represented using a sequence of files. Similarly,
1959 you will place each subunit or child unit in a separate file.
1961 @node Foreign Language Representation
1962 @section Foreign Language Representation
1964 @noindent
1965 GNAT supports the standard character sets defined in Ada 95 as well as
1966 several other non-standard character sets for use in localized versions
1967 of the compiler (@pxref{Character Set Control}).
1968 @menu
1969 * Latin-1::
1970 * Other 8-Bit Codes::
1971 * Wide Character Encodings::
1972 @end menu
1974 @node Latin-1
1975 @subsection Latin-1
1976 @cindex Latin-1
1978 @noindent
1979 The basic character set is Latin-1. This character set is defined by ISO
1980 standard 8859, part 1. The lower half (character codes @code{16#00#}
1981 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1982 is used to represent additional characters. These include extended letters
1983 used by European languages, such as French accents, the vowels with umlauts
1984 used in German, and the extra letter A-ring used in Swedish.
1986 @findex Ada.Characters.Latin_1
1987 For a complete list of Latin-1 codes and their encodings, see the source
1988 file of library unit @code{Ada.Characters.Latin_1} in file
1989 @file{a-chlat1.ads}.
1990 You may use any of these extended characters freely in character or
1991 string literals. In addition, the extended characters that represent
1992 letters can be used in identifiers.
1994 @node Other 8-Bit Codes
1995 @subsection Other 8-Bit Codes
1997 @noindent
1998 GNAT also supports several other 8-bit coding schemes:
2000 @table @asis
2001 @item ISO 8859-2 (Latin-2)
2002 @cindex Latin-2
2003 @cindex ISO 8859-2
2004 Latin-2 letters allowed in identifiers, with uppercase and lowercase
2005 equivalence.
2007 @item ISO 8859-3 (Latin-3)
2008 @cindex Latin-3
2009 @cindex ISO 8859-3
2010 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2011 equivalence.
2013 @item ISO 8859-4 (Latin-4)
2014 @cindex Latin-4
2015 @cindex ISO 8859-4
2016 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2017 equivalence.
2019 @item ISO 8859-5 (Cyrillic)
2020 @cindex ISO 8859-5
2021 @cindex Cyrillic
2022 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2023 lowercase equivalence.
2025 @item ISO 8859-15 (Latin-9)
2026 @cindex ISO 8859-15
2027 @cindex Latin-9
2028 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2029 lowercase equivalence
2031 @item IBM PC (code page 437)
2032 @cindex code page 437
2033 This code page is the normal default for PCs in the U.S. It corresponds
2034 to the original IBM PC character set. This set has some, but not all, of
2035 the extended Latin-1 letters, but these letters do not have the same
2036 encoding as Latin-1. In this mode, these letters are allowed in
2037 identifiers with uppercase and lowercase equivalence.
2039 @item IBM PC (code page 850)
2040 @cindex code page 850
2041 This code page is a modification of 437 extended to include all the
2042 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2043 mode, all these letters are allowed in identifiers with uppercase and
2044 lowercase equivalence.
2046 @item Full Upper 8-bit
2047 Any character in the range 80-FF allowed in identifiers, and all are
2048 considered distinct. In other words, there are no uppercase and lowercase
2049 equivalences in this range. This is useful in conjunction with
2050 certain encoding schemes used for some foreign character sets (e.g.
2051 the typical method of representing Chinese characters on the PC).
2053 @item No Upper-Half
2054 No upper-half characters in the range 80-FF are allowed in identifiers.
2055 This gives Ada 83 compatibility for identifier names.
2056 @end table
2058 @noindent
2059 For precise data on the encodings permitted, and the uppercase and lowercase
2060 equivalences that are recognized, see the file @file{csets.adb} in
2061 the GNAT compiler sources. You will need to obtain a full source release
2062 of GNAT to obtain this file.
2064 @node Wide Character Encodings
2065 @subsection Wide Character Encodings
2067 @noindent
2068 GNAT allows wide character codes to appear in character and string
2069 literals, and also optionally in identifiers, by means of the following
2070 possible encoding schemes:
2072 @table @asis
2074 @item Hex Coding
2075 In this encoding, a wide character is represented by the following five
2076 character sequence:
2078 @smallexample
2079 ESC a b c d
2080 @end smallexample
2082 @noindent
2083 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2084 characters (using uppercase letters) of the wide character code. For
2085 example, ESC A345 is used to represent the wide character with code
2086 @code{16#A345#}.
2087 This scheme is compatible with use of the full Wide_Character set.
2089 @item Upper-Half Coding
2090 @cindex Upper-Half Coding
2091 The wide character with encoding @code{16#abcd#} where the upper bit is on
2092 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2093 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2094 character, but is not required to be in the upper half. This method can
2095 be also used for shift-JIS or EUC, where the internal coding matches the
2096 external coding.
2098 @item Shift JIS Coding
2099 @cindex Shift JIS Coding
2100 A wide character is represented by a two-character sequence,
2101 @code{16#ab#} and
2102 @code{16#cd#}, with the restrictions described for upper-half encoding as
2103 described above. The internal character code is the corresponding JIS
2104 character according to the standard algorithm for Shift-JIS
2105 conversion. Only characters defined in the JIS code set table can be
2106 used with this encoding method.
2108 @item EUC Coding
2109 @cindex EUC Coding
2110 A wide character is represented by a two-character sequence
2111 @code{16#ab#} and
2112 @code{16#cd#}, with both characters being in the upper half. The internal
2113 character code is the corresponding JIS character according to the EUC
2114 encoding algorithm. Only characters defined in the JIS code set table
2115 can be used with this encoding method.
2117 @item UTF-8 Coding
2118 A wide character is represented using
2119 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2120 10646-1/Am.2. Depending on the character value, the representation
2121 is a one, two, or three byte sequence:
2122 @smallexample
2123 @iftex
2124 @leftskip=.7cm
2125 @end iftex
2126 16#0000#-16#007f#: 2#0xxxxxxx#
2127 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2128 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2130 @end smallexample
2132 @noindent
2133 where the xxx bits correspond to the left-padded bits of the
2134 16-bit character value. Note that all lower half ASCII characters
2135 are represented as ASCII bytes and all upper half characters and
2136 other wide characters are represented as sequences of upper-half
2137 (The full UTF-8 scheme allows for encoding 31-bit characters as
2138 6-byte sequences, but in this implementation, all UTF-8 sequences
2139 of four or more bytes length will be treated as illegal).
2140 @item Brackets Coding
2141 In this encoding, a wide character is represented by the following eight
2142 character sequence:
2144 @smallexample
2145 [ " a b c d " ]
2146 @end smallexample
2148 @noindent
2149 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2150 characters (using uppercase letters) of the wide character code. For
2151 example, [``A345''] is used to represent the wide character with code
2152 @code{16#A345#}. It is also possible (though not required) to use the
2153 Brackets coding for upper half characters. For example, the code
2154 @code{16#A3#} can be represented as @code{[``A3'']}.
2156 This scheme is compatible with use of the full Wide_Character set,
2157 and is also the method used for wide character encoding in the standard
2158 ACVC (Ada Compiler Validation Capability) test suite distributions.
2160 @end table
2162 @noindent
2163 Note: Some of these coding schemes do not permit the full use of the
2164 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2165 use of the upper half of the Latin-1 set.
2167 @node File Naming Rules
2168 @section File Naming Rules
2170 @noindent
2171 The default file name is determined by the name of the unit that the
2172 file contains. The name is formed by taking the full expanded name of
2173 the unit and replacing the separating dots with hyphens and using
2174 ^lowercase^uppercase^ for all letters.
2176 An exception arises if the file name generated by the above rules starts
2177 with one of the characters
2178 @ifset vms
2179 A,G,I, or S,
2180 @end ifset
2181 @ifclear vms
2182 a,g,i, or s,
2183 @end ifclear
2184 and the second character is a
2185 minus. In this case, the character ^tilde^dollar sign^ is used in place
2186 of the minus. The reason for this special rule is to avoid clashes with
2187 the standard names for child units of the packages System, Ada,
2188 Interfaces, and GNAT, which use the prefixes
2189 @ifset vms
2190 S- A- I- and G-
2191 @end ifset
2192 @ifclear vms
2193 s- a- i- and g-
2194 @end ifclear
2195 respectively.
2197 The file extension is @file{.ads} for a spec and
2198 @file{.adb} for a body. The following list shows some
2199 examples of these rules.
2201 @table @file
2202 @item main.ads
2203 Main (spec)
2204 @item main.adb
2205 Main (body)
2206 @item arith_functions.ads
2207 Arith_Functions (package spec)
2208 @item arith_functions.adb
2209 Arith_Functions (package body)
2210 @item func-spec.ads
2211 Func.Spec (child package spec)
2212 @item func-spec.adb
2213 Func.Spec (child package body)
2214 @item main-sub.adb
2215 Sub (subunit of Main)
2216 @item ^a~bad.adb^A$BAD.ADB^
2217 A.Bad (child package body)
2218 @end table
2220 @noindent
2221 Following these rules can result in excessively long
2222 file names if corresponding
2223 unit names are long (for example, if child units or subunits are
2224 heavily nested). An option is available to shorten such long file names
2225 (called file name ``krunching''). This may be particularly useful when
2226 programs being developed with GNAT are to be used on operating systems
2227 with limited file name lengths. @xref{Using gnatkr}.
2229 Of course, no file shortening algorithm can guarantee uniqueness over
2230 all possible unit names; if file name krunching is used, it is your
2231 responsibility to ensure no name clashes occur. Alternatively you
2232 can specify the exact file names that you want used, as described
2233 in the next section. Finally, if your Ada programs are migrating from a
2234 compiler with a different naming convention, you can use the gnatchop
2235 utility to produce source files that follow the GNAT naming conventions.
2236 (For details @pxref{Renaming Files Using gnatchop}.)
2238 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2239 systems, case is not significant. So for example on @code{Windows XP}
2240 if the canonical name is @code{main-sub.adb}, you can use the file name
2241 @code{Main-Sub.adb} instead. However, case is significant for other
2242 operating systems, so for example, if you want to use other than
2243 canonically cased file names on a Unix system, you need to follow
2244 the procedures described in the next section.
2246 @node Using Other File Names
2247 @section Using Other File Names
2248 @cindex File names
2250 @noindent
2251 In the previous section, we have described the default rules used by
2252 GNAT to determine the file name in which a given unit resides. It is
2253 often convenient to follow these default rules, and if you follow them,
2254 the compiler knows without being explicitly told where to find all
2255 the files it needs.
2257 However, in some cases, particularly when a program is imported from
2258 another Ada compiler environment, it may be more convenient for the
2259 programmer to specify which file names contain which units. GNAT allows
2260 arbitrary file names to be used by means of the Source_File_Name pragma.
2261 The form of this pragma is as shown in the following examples:
2262 @cindex Source_File_Name pragma
2264 @smallexample @c ada
2265 @cartouche
2266 pragma Source_File_Name (My_Utilities.Stacks,
2267   Spec_File_Name => "myutilst_a.ada");
2268 pragma Source_File_name (My_Utilities.Stacks,
2269   Body_File_Name => "myutilst.ada");
2270 @end cartouche
2271 @end smallexample
2273 @noindent
2274 As shown in this example, the first argument for the pragma is the unit
2275 name (in this example a child unit). The second argument has the form
2276 of a named association. The identifier
2277 indicates whether the file name is for a spec or a body;
2278 the file name itself is given by a string literal.
2280 The source file name pragma is a configuration pragma, which means that
2281 normally it will be placed in the @file{gnat.adc}
2282 file used to hold configuration
2283 pragmas that apply to a complete compilation environment.
2284 For more details on how the @file{gnat.adc} file is created and used
2285 @pxref{Handling of Configuration Pragmas}
2286 @cindex @file{gnat.adc}
2288 @ifclear vms
2289 GNAT allows completely arbitrary file names to be specified using the
2290 source file name pragma. However, if the file name specified has an
2291 extension other than @file{.ads} or @file{.adb} it is necessary to use
2292 a special syntax when compiling the file. The name in this case must be
2293 preceded by the special sequence @code{-x} followed by a space and the name
2294 of the language, here @code{ada}, as in:
2296 @smallexample
2297 $ gcc -c -x ada peculiar_file_name.sim
2298 @end smallexample
2299 @end ifclear
2301 @noindent
2302 @code{gnatmake} handles non-standard file names in the usual manner (the
2303 non-standard file name for the main program is simply used as the
2304 argument to gnatmake). Note that if the extension is also non-standard,
2305 then it must be included in the gnatmake command, it may not be omitted.
2307 @node Alternative File Naming Schemes
2308 @section Alternative File Naming Schemes
2309 @cindex File naming schemes, alternative
2310 @cindex File names
2312 In the previous section, we described the use of the @code{Source_File_Name}
2313 pragma to allow arbitrary names to be assigned to individual source files.
2314 However, this approach requires one pragma for each file, and especially in
2315 large systems can result in very long @file{gnat.adc} files, and also create
2316 a maintenance problem.
2318 GNAT also provides a facility for specifying systematic file naming schemes
2319 other than the standard default naming scheme previously described. An
2320 alternative scheme for naming is specified by the use of
2321 @code{Source_File_Name} pragmas having the following format:
2322 @cindex Source_File_Name pragma
2324 @smallexample @c ada
2325 pragma Source_File_Name (
2326    Spec_File_Name  => FILE_NAME_PATTERN
2327  [,Casing          => CASING_SPEC]
2328  [,Dot_Replacement => STRING_LITERAL]);
2330 pragma Source_File_Name (
2331    Body_File_Name  => FILE_NAME_PATTERN
2332  [,Casing          => CASING_SPEC]
2333  [,Dot_Replacement => STRING_LITERAL]);
2335 pragma Source_File_Name (
2336    Subunit_File_Name  => FILE_NAME_PATTERN
2337  [,Casing             => CASING_SPEC]
2338  [,Dot_Replacement    => STRING_LITERAL]);
2340 FILE_NAME_PATTERN ::= STRING_LITERAL
2341 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2342 @end smallexample
2344 @noindent
2345 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2346 It contains a single asterisk character, and the unit name is substituted
2347 systematically for this asterisk. The optional parameter
2348 @code{Casing} indicates
2349 whether the unit name is to be all upper-case letters, all lower-case letters,
2350 or mixed-case. If no
2351 @code{Casing} parameter is used, then the default is all
2352 ^lower-case^upper-case^.
2354 The optional @code{Dot_Replacement} string is used to replace any periods
2355 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2356 argument is used then separating dots appear unchanged in the resulting
2357 file name.
2358 Although the above syntax indicates that the
2359 @code{Casing} argument must appear
2360 before the @code{Dot_Replacement} argument, but it
2361 is also permissible to write these arguments in the opposite order.
2363 As indicated, it is possible to specify different naming schemes for
2364 bodies, specs, and subunits. Quite often the rule for subunits is the
2365 same as the rule for bodies, in which case, there is no need to give
2366 a separate @code{Subunit_File_Name} rule, and in this case the
2367 @code{Body_File_name} rule is used for subunits as well.
2369 The separate rule for subunits can also be used to implement the rather
2370 unusual case of a compilation environment (e.g. a single directory) which
2371 contains a subunit and a child unit with the same unit name. Although
2372 both units cannot appear in the same partition, the Ada Reference Manual
2373 allows (but does not require) the possibility of the two units coexisting
2374 in the same environment.
2376 The file name translation works in the following steps:
2378 @itemize @bullet
2380 @item
2381 If there is a specific @code{Source_File_Name} pragma for the given unit,
2382 then this is always used, and any general pattern rules are ignored.
2384 @item
2385 If there is a pattern type @code{Source_File_Name} pragma that applies to
2386 the unit, then the resulting file name will be used if the file exists. If
2387 more than one pattern matches, the latest one will be tried first, and the
2388 first attempt resulting in a reference to a file that exists will be used.
2390 @item
2391 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2392 for which the corresponding file exists, then the standard GNAT default
2393 naming rules are used.
2395 @end itemize
2397 @noindent
2398 As an example of the use of this mechanism, consider a commonly used scheme
2399 in which file names are all lower case, with separating periods copied
2400 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2401 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2402 two pragmas appear:
2404 @smallexample @c ada
2405 pragma Source_File_Name
2406   (Spec_File_Name => "*.1.ada");
2407 pragma Source_File_Name
2408   (Body_File_Name => "*.2.ada");
2409 @end smallexample
2411 @noindent
2412 The default GNAT scheme is actually implemented by providing the following
2413 default pragmas internally:
2415 @smallexample @c ada
2416 pragma Source_File_Name
2417   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2418 pragma Source_File_Name
2419   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2420 @end smallexample
2422 @noindent
2423 Our final example implements a scheme typically used with one of the
2424 Ada 83 compilers, where the separator character for subunits was ``__''
2425 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2426 by adding @file{.ADA}, and subunits by
2427 adding @file{.SEP}. All file names were
2428 upper case. Child units were not present of course since this was an
2429 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2430 the same double underscore separator for child units.
2432 @smallexample @c ada
2433 pragma Source_File_Name
2434   (Spec_File_Name => "*_.ADA",
2435    Dot_Replacement => "__",
2436    Casing = Uppercase);
2437 pragma Source_File_Name
2438   (Body_File_Name => "*.ADA",
2439    Dot_Replacement => "__",
2440    Casing = Uppercase);
2441 pragma Source_File_Name
2442   (Subunit_File_Name => "*.SEP",
2443    Dot_Replacement => "__",
2444    Casing = Uppercase);
2445 @end smallexample
2447 @node Generating Object Files
2448 @section Generating Object Files
2450 @noindent
2451 An Ada program consists of a set of source files, and the first step in
2452 compiling the program is to generate the corresponding object files.
2453 These are generated by compiling a subset of these source files.
2454 The files you need to compile are the following:
2456 @itemize @bullet
2457 @item
2458 If a package spec has no body, compile the package spec to produce the
2459 object file for the package.
2461 @item
2462 If a package has both a spec and a body, compile the body to produce the
2463 object file for the package. The source file for the package spec need
2464 not be compiled in this case because there is only one object file, which
2465 contains the code for both the spec and body of the package.
2467 @item
2468 For a subprogram, compile the subprogram body to produce the object file
2469 for the subprogram. The spec, if one is present, is as usual in a
2470 separate file, and need not be compiled.
2472 @item
2473 @cindex Subunits
2474 In the case of subunits, only compile the parent unit. A single object
2475 file is generated for the entire subunit tree, which includes all the
2476 subunits.
2478 @item
2479 Compile child units independently of their parent units
2480 (though, of course, the spec of all the ancestor unit must be present in order
2481 to compile a child unit).
2483 @item
2484 @cindex Generics
2485 Compile generic units in the same manner as any other units. The object
2486 files in this case are small dummy files that contain at most the
2487 flag used for elaboration checking. This is because GNAT always handles generic
2488 instantiation by means of macro expansion. However, it is still necessary to
2489 compile generic units, for dependency checking and elaboration purposes.
2490 @end itemize
2492 @noindent
2493 The preceding rules describe the set of files that must be compiled to
2494 generate the object files for a program. Each object file has the same
2495 name as the corresponding source file, except that the extension is
2496 @file{.o} as usual.
2498 You may wish to compile other files for the purpose of checking their
2499 syntactic and semantic correctness. For example, in the case where a
2500 package has a separate spec and body, you would not normally compile the
2501 spec. However, it is convenient in practice to compile the spec to make
2502 sure it is error-free before compiling clients of this spec, because such
2503 compilations will fail if there is an error in the spec.
2505 GNAT provides an option for compiling such files purely for the
2506 purposes of checking correctness; such compilations are not required as
2507 part of the process of building a program. To compile a file in this
2508 checking mode, use the @option{-gnatc} switch.
2510 @node Source Dependencies
2511 @section Source Dependencies
2513 @noindent
2514 A given object file clearly depends on the source file which is compiled
2515 to produce it. Here we are using @dfn{depends} in the sense of a typical
2516 @code{make} utility; in other words, an object file depends on a source
2517 file if changes to the source file require the object file to be
2518 recompiled.
2519 In addition to this basic dependency, a given object may depend on
2520 additional source files as follows:
2522 @itemize @bullet
2523 @item
2524 If a file being compiled @code{with}'s a unit @var{X}, the object file
2525 depends on the file containing the spec of unit @var{X}. This includes
2526 files that are @code{with}'ed implicitly either because they are parents
2527 of @code{with}'ed child units or they are run-time units required by the
2528 language constructs used in a particular unit.
2530 @item
2531 If a file being compiled instantiates a library level generic unit, the
2532 object file depends on both the spec and body files for this generic
2533 unit.
2535 @item
2536 If a file being compiled instantiates a generic unit defined within a
2537 package, the object file depends on the body file for the package as
2538 well as the spec file.
2540 @item
2541 @findex Inline
2542 @cindex @option{-gnatn} switch
2543 If a file being compiled contains a call to a subprogram for which
2544 pragma @code{Inline} applies and inlining is activated with the
2545 @option{-gnatn} switch, the object file depends on the file containing the
2546 body of this subprogram as well as on the file containing the spec. Note
2547 that for inlining to actually occur as a result of the use of this switch,
2548 it is necessary to compile in optimizing mode.
2550 @cindex @option{-gnatN} switch
2551 The use of @option{-gnatN} activates a more extensive inlining optimization
2552 that is performed by the front end of the compiler. This inlining does
2553 not require that the code generation be optimized. Like @option{-gnatn},
2554 the use of this switch generates additional dependencies.
2555 Note that
2556 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2557 to specify both options.
2559 @item
2560 If an object file O  depends on the proper body of a subunit through inlining
2561 or instantiation, it depends on the parent unit of the subunit. This means that
2562 any modification of the parent unit or one of its subunits affects the
2563 compilation of O.
2565 @item
2566 The object file for a parent unit depends on all its subunit body files.
2568 @item
2569 The previous two rules meant that for purposes of computing dependencies and
2570 recompilation, a body and all its subunits are treated as an indivisible whole.
2572 @noindent
2573 These rules are applied transitively: if unit @code{A} @code{with}'s
2574 unit @code{B}, whose elaboration calls an inlined procedure in package
2575 @code{C}, the object file for unit @code{A} will depend on the body of
2576 @code{C}, in file @file{c.adb}.
2578 The set of dependent files described by these rules includes all the
2579 files on which the unit is semantically dependent, as described in the
2580 Ada 95 Language Reference Manual. However, it is a superset of what the
2581 ARM describes, because it includes generic, inline, and subunit dependencies.
2583 An object file must be recreated by recompiling the corresponding source
2584 file if any of the source files on which it depends are modified. For
2585 example, if the @code{make} utility is used to control compilation,
2586 the rule for an Ada object file must mention all the source files on
2587 which the object file depends, according to the above definition.
2588 The determination of the necessary
2589 recompilations is done automatically when one uses @code{gnatmake}.
2590 @end itemize
2592 @node The Ada Library Information Files
2593 @section The Ada Library Information Files
2594 @cindex Ada Library Information files
2595 @cindex @file{ALI} files
2597 @noindent
2598 Each compilation actually generates two output files. The first of these
2599 is the normal object file that has a @file{.o} extension. The second is a
2600 text file containing full dependency information. It has the same
2601 name as the source file, but an @file{.ali} extension.
2602 This file is known as the Ada Library Information (@file{ALI}) file.
2603 The following information is contained in the @file{ALI} file.
2605 @itemize @bullet
2606 @item
2607 Version information (indicates which version of GNAT was used to compile
2608 the unit(s) in question)
2610 @item
2611 Main program information (including priority and time slice settings,
2612 as well as the wide character encoding used during compilation).
2614 @item
2615 List of arguments used in the @code{gcc} command for the compilation
2617 @item
2618 Attributes of the unit, including configuration pragmas used, an indication
2619 of whether the compilation was successful, exception model used etc.
2621 @item
2622 A list of relevant restrictions applying to the unit (used for consistency)
2623 checking.
2625 @item
2626 Categorization information (e.g. use of pragma @code{Pure}).
2628 @item
2629 Information on all @code{with}'ed units, including presence of
2630 @code{Elaborate} or @code{Elaborate_All} pragmas.
2632 @item
2633 Information from any @code{Linker_Options} pragmas used in the unit
2635 @item
2636 Information on the use of @code{Body_Version} or @code{Version}
2637 attributes in the unit.
2639 @item
2640 Dependency information. This is a list of files, together with
2641 time stamp and checksum information. These are files on which
2642 the unit depends in the sense that recompilation is required
2643 if any of these units are modified.
2645 @item
2646 Cross-reference data. Contains information on all entities referenced
2647 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2648 provide cross-reference information.
2650 @end itemize
2652 @noindent
2653 For a full detailed description of the format of the @file{ALI} file,
2654 see the source of the body of unit @code{Lib.Writ}, contained in file
2655 @file{lib-writ.adb} in the GNAT compiler sources.
2657 @node Binding an Ada Program
2658 @section Binding an Ada Program
2660 @noindent
2661 When using languages such as C and C++, once the source files have been
2662 compiled the only remaining step in building an executable program
2663 is linking the object modules together. This means that it is possible to
2664 link an inconsistent version of a program, in which two units have
2665 included different versions of the same header.
2667 The rules of Ada do not permit such an inconsistent program to be built.
2668 For example, if two clients have different versions of the same package,
2669 it is illegal to build a program containing these two clients.
2670 These rules are enforced by the GNAT binder, which also determines an
2671 elaboration order consistent with the Ada rules.
2673 The GNAT binder is run after all the object files for a program have
2674 been created. It is given the name of the main program unit, and from
2675 this it determines the set of units required by the program, by reading the
2676 corresponding ALI files. It generates error messages if the program is
2677 inconsistent or if no valid order of elaboration exists.
2679 If no errors are detected, the binder produces a main program, in Ada by
2680 default, that contains calls to the elaboration procedures of those
2681 compilation unit that require them, followed by
2682 a call to the main program. This Ada program is compiled to generate the
2683 object file for the main program. The name of
2684 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2685 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2686 main program unit.
2688 Finally, the linker is used to build the resulting executable program,
2689 using the object from the main program from the bind step as well as the
2690 object files for the Ada units of the program.
2692 @node Mixed Language Programming
2693 @section Mixed Language Programming
2694 @cindex Mixed Language Programming
2696 @noindent
2697 This section describes how to develop a mixed-language program,
2698 specifically one that comprises units in both Ada and C.
2700 @menu
2701 * Interfacing to C::
2702 * Calling Conventions::
2703 @end menu
2705 @node Interfacing to C
2706 @subsection Interfacing to C
2707 @noindent
2708 Interfacing Ada with a foreign language such as C involves using
2709 compiler directives to import and/or export entity definitions in each
2710 language---using @code{extern} statements in C, for instance, and the
2711 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.  For
2712 a full treatment of these topics, read Appendix B, section 1 of the Ada
2713 95 Language Reference Manual.
2715 There are two ways to build a program using GNAT that contains some Ada
2716 sources and some foreign language sources, depending on whether or not
2717 the main subprogram is written in Ada.  Here is a source example with
2718 the main subprogram in Ada:
2720 @smallexample
2721 /* file1.c */
2722 #include <stdio.h>
2724 void print_num (int num)
2726   printf ("num is %d.\n", num);
2727   return;
2730 /* file2.c */
2732 /* num_from_Ada is declared in my_main.adb */
2733 extern int num_from_Ada;
2735 int get_num (void)
2737   return num_from_Ada;
2739 @end smallexample
2741 @smallexample @c ada
2742 --  my_main.adb
2743 procedure My_Main is
2745    --  Declare then export an Integer entity called num_from_Ada
2746    My_Num : Integer := 10;
2747    pragma Export (C, My_Num, "num_from_Ada");
2749    --  Declare an Ada function spec for Get_Num, then use
2750    --  C function get_num for the implementation.
2751    function Get_Num return Integer;
2752    pragma Import (C, Get_Num, "get_num");
2754    --  Declare an Ada procedure spec for Print_Num, then use
2755    --  C function print_num for the implementation.
2756    procedure Print_Num (Num : Integer);
2757    pragma Import (C, Print_Num, "print_num");
2759 begin
2760    Print_Num (Get_Num);
2761 end My_Main;
2762 @end smallexample
2764 @enumerate
2765 @item
2766 To build this example, first compile the foreign language files to
2767 generate object files:
2768 @smallexample
2769 gcc -c file1.c
2770 gcc -c file2.c
2771 @end smallexample
2773 @item
2774 Then, compile the Ada units to produce a set of object files and ALI
2775 files:
2776 @smallexample
2777 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2778 @end smallexample
2780 @item
2781 Run the Ada binder on the Ada main program:
2782 @smallexample
2783 gnatbind my_main.ali
2784 @end smallexample
2786 @item
2787 Link the Ada main program, the Ada objects and the other language
2788 objects:
2789 @smallexample
2790 gnatlink my_main.ali file1.o file2.o
2791 @end smallexample
2792 @end enumerate
2794 The last three steps can be grouped in a single command:
2795 @smallexample
2796 gnatmake my_main.adb -largs file1.o file2.o
2797 @end smallexample
2799 @cindex Binder output file
2800 @noindent
2801 If the main program is in a language other than Ada, then you may have
2802 more than one entry point into the Ada subsystem. You must use a special
2803 binder option to generate callable routines that initialize and
2804 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2805 Calls to the initialization and finalization routines must be inserted
2806 in the main program, or some other appropriate point in the code. The
2807 call to initialize the Ada units must occur before the first Ada
2808 subprogram is called, and the call to finalize the Ada units must occur
2809 after the last Ada subprogram returns. The binder will place the
2810 initialization and finalization subprograms into the
2811 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2812 sources.  To illustrate, we have the following example:
2814 @smallexample
2815 /* main.c */
2816 extern void adainit (void);
2817 extern void adafinal (void);
2818 extern int add (int, int);
2819 extern int sub (int, int);
2821 int main (int argc, char *argv[])
2823   int a = 21, b = 7;
2825   adainit();
2827   /* Should print "21 + 7 = 28" */
2828   printf ("%d + %d = %d\n", a, b, add (a, b));
2829   /* Should print "21 - 7 = 14" */
2830   printf ("%d - %d = %d\n", a, b, sub (a, b));
2832   adafinal();
2834 @end smallexample
2836 @smallexample @c ada
2837 --  unit1.ads
2838 package Unit1 is
2839    function Add (A, B : Integer) return Integer;
2840    pragma Export (C, Add, "add");
2841 end Unit1;
2843 --  unit1.adb
2844 package body Unit1 is
2845    function Add (A, B : Integer) return Integer is
2846    begin
2847       return A + B;
2848    end Add;
2849 end Unit1;
2851 --  unit2.ads
2852 package Unit2 is
2853    function Sub (A, B : Integer) return Integer;
2854    pragma Export (C, Sub, "sub");
2855 end Unit2;
2857 --  unit2.adb
2858 package body Unit2 is
2859    function Sub (A, B : Integer) return Integer is
2860    begin
2861       return A - B;
2862    end Sub;
2863 end Unit2;
2864 @end smallexample
2866 @enumerate
2867 @item
2868 The build procedure for this application is similar to the last
2869 example's.  First, compile the foreign language files to generate object
2870 files:
2871 @smallexample
2872 gcc -c main.c
2873 @end smallexample
2875 @item
2876 Next, compile the Ada units to produce a set of object files and ALI
2877 files:
2878 @smallexample
2879 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2880 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2881 @end smallexample
2883 @item
2884 Run the Ada binder on every generated ALI file.  Make sure to use the
2885 @option{-n} option to specify a foreign main program:
2886 @smallexample
2887 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2888 @end smallexample
2890 @item
2891 Link the Ada main program, the Ada objects and the foreign language
2892 objects. You need only list the last ALI file here:
2893 @smallexample
2894 gnatlink unit2.ali main.o -o exec_file
2895 @end smallexample
2897 This procedure yields a binary executable called @file{exec_file}.
2898 @end enumerate
2900 @node Calling Conventions
2901 @subsection Calling Conventions
2902 @cindex Foreign Languages
2903 @cindex Calling Conventions
2904 GNAT follows standard calling sequence conventions and will thus interface
2905 to any other language that also follows these conventions. The following
2906 Convention identifiers are recognized by GNAT:
2908 @table @code
2909 @cindex Interfacing to Ada
2910 @cindex Other Ada compilers
2911 @cindex Convention Ada
2912 @item Ada
2913 This indicates that the standard Ada calling sequence will be
2914 used and all Ada data items may be passed without any limitations in the
2915 case where GNAT is used to generate both the caller and callee. It is also
2916 possible to mix GNAT generated code and code generated by another Ada
2917 compiler. In this case, the data types should be restricted to simple
2918 cases, including primitive types. Whether complex data types can be passed
2919 depends on the situation. Probably it is safe to pass simple arrays, such
2920 as arrays of integers or floats. Records may or may not work, depending
2921 on whether both compilers lay them out identically. Complex structures
2922 involving variant records, access parameters, tasks, or protected types,
2923 are unlikely to be able to be passed.
2925 Note that in the case of GNAT running
2926 on a platform that supports DEC Ada 83, a higher degree of compatibility
2927 can be guaranteed, and in particular records are layed out in an identical
2928 manner in the two compilers. Note also that if output from two different
2929 compilers is mixed, the program is responsible for dealing with elaboration
2930 issues. Probably the safest approach is to write the main program in the
2931 version of Ada other than GNAT, so that it takes care of its own elaboration
2932 requirements, and then call the GNAT-generated adainit procedure to ensure
2933 elaboration of the GNAT components. Consult the documentation of the other
2934 Ada compiler for further details on elaboration.
2936 However, it is not possible to mix the tasking run time of GNAT and
2937 DEC Ada 83, All the tasking operations must either be entirely within
2938 GNAT compiled sections of the program, or entirely within DEC Ada 83
2939 compiled sections of the program.
2941 @cindex Interfacing to Assembly
2942 @cindex Convention Assembler
2943 @item Assembler
2944 Specifies assembler as the convention. In practice this has the
2945 same effect as convention Ada (but is not equivalent in the sense of being
2946 considered the same convention).
2948 @cindex Convention Asm
2949 @findex Asm
2950 @item Asm
2951 Equivalent to Assembler.
2953 @cindex Interfacing to COBOL
2954 @cindex Convention COBOL
2955 @findex COBOL
2956 @item COBOL
2957 Data will be passed according to the conventions described
2958 in section B.4 of the Ada 95 Reference Manual.
2960 @findex C
2961 @cindex Interfacing to C
2962 @cindex Convention C
2963 @item C
2964 Data will be passed according to the conventions described
2965 in section B.3 of the Ada 95 Reference Manual.
2967 @findex C varargs function
2968 @cindex Intefacing to C varargs function
2969 @cindex varargs function intefacs
2970 @item C varargs function
2971 In C, @code{varargs} allows a function to take a variable number of
2972 arguments. There is no direct equivalent in this to Ada. One
2973 approach that can be used is to create a C wrapper for each
2974 different profile and then interface to this C wrapper. For
2975 example, to print an @code{int} value using @code{printf},
2976 create a C function @code{printfi} that takes two arguments, a
2977 pointer to a string and an int, and calls @code{printf}.
2978 Then in the Ada program, use pragma @code{Import} to
2979 interface to printfi.
2981 It may work on some platforms to directly interface to
2982 a @code{varargs} function by providing a specific Ada profile
2983 for a a particular call. However, this does not work on
2984 all platforms, since there is no guarantee that the
2985 calling sequence for a two argument normal C function
2986 is the same as for calling a @code{varargs} C function with
2987 the same two arguments.
2989 @cindex Convention Default
2990 @findex Default
2991 @item Default
2992 Equivalent to C.
2994 @cindex Convention External
2995 @findex External
2996 @item External
2997 Equivalent to C.
2999 @findex C++
3000 @cindex Interfacing to C++
3001 @cindex Convention C++
3002 @item CPP
3003 This stands for C++. For most purposes this is identical to C.
3004 See the separate description of the specialized GNAT pragmas relating to
3005 C++ interfacing for further details.
3007 @findex Fortran
3008 @cindex Interfacing to Fortran
3009 @cindex Convention Fortran
3010 @item Fortran
3011 Data will be passed according to the conventions described
3012 in section B.5 of the Ada 95 Reference Manual.
3014 @item Intrinsic
3015 This applies to an intrinsic operation, as defined in the Ada 95
3016 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
3017 this means that the body of the subprogram is provided by the compiler itself,
3018 usually by means of an efficient code sequence, and that the user does not
3019 supply an explicit body for it. In an application program, the pragma can
3020 only be applied to the following two sets of names, which the GNAT compiler
3021 recognizes.
3023 @itemize @bullet
3024 @item
3025 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
3026 Arithmetic.  The corresponding subprogram declaration must have
3027 two formal parameters. The
3028 first one must be a signed integer type or a modular type with a binary
3029 modulus, and the second parameter must be of type Natural.
3030 The return type must be the same as the type of the first argument. The size
3031 of this type can only be 8, 16, 32, or 64.
3032 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3033 The corresponding operator declaration must have parameters and result type
3034 that have the same root numeric type (for example, all three are long_float
3035 types). This simplifies the definition of operations that use type checking
3036 to perform dimensional checks:
3038 @smallexample @c ada
3039 type Distance is new Long_Float;
3040 type Time     is new Long_Float;
3041 type Velocity is new Long_Float;
3042 function "/" (D : Distance; T : Time)
3043   return Velocity;
3044 pragma Import (Intrinsic, "/");
3045 @end smallexample
3047 @noindent
3048 This common idiom is often programmed with a generic definition and an
3049 explicit body. The pragma makes it simpler to introduce such declarations.
3050 It incurs no overhead in compilation time or code size, because it is
3051 implemented as a single machine instruction.
3052 @end itemize
3053 @noindent
3055 @ifset unw
3056 @findex Stdcall
3057 @cindex Convention Stdcall
3058 @item Stdcall
3059 This is relevant only to NT/Win95 implementations of GNAT,
3060 and specifies that the Stdcall calling sequence will be used, as defined
3061 by the NT API.
3063 @findex DLL
3064 @cindex Convention DLL
3065 @item DLL
3066 This is equivalent to Stdcall.
3068 @findex Win32
3069 @cindex Convention Win32
3070 @item Win32
3071 This is equivalent to Stdcall.
3072 @end ifset
3074 @findex Stubbed
3075 @cindex Convention Stubbed
3076 @item Stubbed
3077 This is a special convention that indicates that the compiler
3078 should provide a stub body that raises @code{Program_Error}.
3079 @end table
3081 @noindent
3082 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3083 that can be used to parametrize conventions and allow additional synonyms
3084 to be specified. For example if you have legacy code in which the convention
3085 identifier Fortran77 was used for Fortran, you can use the configuration
3086 pragma:
3088 @smallexample @c ada
3089 pragma Convention_Identifier (Fortran77, Fortran);
3090 @end smallexample
3092 @noindent
3093 And from now on the identifier Fortran77 may be used as a convention
3094 identifier (for example in an @code{Import} pragma) with the same
3095 meaning as Fortran.
3097 @node Building Mixed Ada & C++ Programs
3098 @section Building Mixed Ada & C++ Programs
3100 @noindent
3101 A programmer inexperienced with mixed-language development may find that
3102 building an application containing both Ada and C++ code can be a
3103 challenge. As a matter of fact, interfacing with C++ has not been
3104 standardized in the Ada 95 Reference Manual due to the immaturity of --
3105 and lack of standards for -- C++ at the time. This section gives a few
3106 hints that should make this task easier. The first section addresses
3107 the differences regarding interfacing with C. The second section
3108 looks into the delicate problem of linking the complete application from
3109 its Ada and C++ parts. The last section gives some hints on how the GNAT
3110 run time can be adapted in order to allow inter-language dispatching
3111 with a new C++ compiler.
3113 @menu
3114 * Interfacing to C++::
3115 * Linking a Mixed C++ & Ada Program::
3116 * A Simple Example::
3117 * Adapting the Run Time to a New C++ Compiler::
3118 @end menu
3120 @node Interfacing to C++
3121 @subsection Interfacing to C++
3123 @noindent
3124 GNAT supports interfacing with C++ compilers generating code that is
3125 compatible with the standard Application Binary Interface of the given
3126 platform.
3128 @noindent
3129 Interfacing can be done at 3 levels: simple data, subprograms, and
3130 classes. In the first two cases, GNAT offers a specific @var{Convention
3131 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3132 the names of subprograms, and currently, GNAT does not provide any help
3133 to solve the demangling problem. This problem can be addressed in two
3134 ways:
3135 @itemize @bullet
3136 @item
3137 by modifying the C++ code in order to force a C convention using
3138 the @code{extern "C"} syntax.
3140 @item
3141 by figuring out the mangled name and use it as the Link_Name argument of
3142 the pragma import.
3143 @end itemize
3145 @noindent
3146 Interfacing at the class level can be achieved by using the GNAT specific
3147 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3148 Reference Manual for additional information.
3150 @node Linking a Mixed C++ & Ada Program
3151 @subsection Linking a Mixed C++ & Ada Program
3153 @noindent
3154 Usually the linker of the C++ development system must be used to link
3155 mixed applications because most C++ systems will resolve elaboration
3156 issues (such as calling constructors on global class instances)
3157 transparently during the link phase. GNAT has been adapted to ease the
3158 use of a foreign linker for the last phase. Three cases can be
3159 considered:
3160 @enumerate
3162 @item
3163 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3164 The C++ linker can simply be called by using the C++ specific driver
3165 called @code{c++}. Note that this setup is not very common because it
3166 may involve recompiling the whole GCC tree from sources, which makes it
3167 harder to upgrade the compilation system for one language without
3168 destabilizing the other.
3170 @smallexample
3171 $ c++ -c file1.C
3172 $ c++ -c file2.C
3173 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3174 @end smallexample
3176 @item
3177 Using GNAT and G++ from two different GCC installations: If both
3178 compilers are on the PATH, the previous method may be used. It is
3179 important to note that environment variables such as C_INCLUDE_PATH,
3180 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3181 at the same time and may make one of the two compilers operate
3182 improperly if set during invocation of the wrong compiler.  It is also
3183 very important that the linker uses the proper @file{libgcc.a} GCC
3184 library -- that is, the one from the C++ compiler installation. The
3185 implicit link command as suggested in the gnatmake command from the
3186 former example can be replaced by an explicit link command with the
3187 full-verbosity option in order to verify which library is used:
3188 @smallexample
3189 $ gnatbind ada_unit
3190 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3191 @end smallexample
3192 If there is a problem due to interfering environment variables, it can
3193 be worked around by using an intermediate script. The following example
3194 shows the proper script to use when GNAT has not been installed at its
3195 default location and g++ has been installed at its default location:
3197 @smallexample
3198 $ cat ./my_script
3199 #!/bin/sh
3200 unset BINUTILS_ROOT
3201 unset GCC_ROOT
3202 c++ $*
3203 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3204 @end smallexample
3206 @item
3207 Using a non-GNU C++ compiler: The commands previously described can be
3208 used to insure that the C++ linker is used. Nonetheless, you need to add
3209 the path to libgcc explicitly, since some libraries needed by GNAT are
3210 located in this directory:
3212 @smallexample
3213 $ cat ./my_script
3214 #!/bin/sh
3215 CC $* `gcc -print-libgcc-file-name`
3216 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3217 @end smallexample
3219 Where CC is the name of the non-GNU C++ compiler.
3221 @end enumerate
3223 @node A Simple Example
3224 @subsection  A Simple Example
3225 @noindent
3226 The following example, provided as part of the GNAT examples, shows how
3227 to achieve procedural interfacing between Ada and C++ in both
3228 directions. The C++ class A has two methods. The first method is exported
3229 to Ada by the means of an extern C wrapper function. The second method
3230 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3231 a limited record with a layout comparable to the C++ class. The Ada
3232 subprogram, in turn, calls the C++ method. So, starting from the C++
3233 main program, the process passes back and forth between the two
3234 languages.
3236 @noindent
3237 Here are the compilation commands:
3238 @smallexample
3239 $ gnatmake -c simple_cpp_interface
3240 $ c++ -c cpp_main.C
3241 $ c++ -c ex7.C
3242 $ gnatbind -n simple_cpp_interface
3243 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3244       -lstdc++ ex7.o cpp_main.o
3245 @end smallexample
3247 @noindent
3248 Here are the corresponding sources:
3249 @smallexample
3251 //cpp_main.C
3253 #include "ex7.h"
3255 extern "C" @{
3256   void adainit (void);
3257   void adafinal (void);
3258   void method1 (A *t);
3261 void method1 (A *t)
3263   t->method1 ();
3266 int main ()
3268   A obj;
3269   adainit ();
3270   obj.method2 (3030);
3271   adafinal ();
3274 //ex7.h
3276 class Origin @{
3277  public:
3278   int o_value;
3280 class A : public Origin @{
3281  public:
3282   void method1 (void);
3283   virtual void method2 (int v);
3284   A();
3285   int   a_value;
3288 //ex7.C
3290 #include "ex7.h"
3291 #include <stdio.h>
3293 extern "C" @{ void ada_method2 (A *t, int v);@}
3295 void A::method1 (void)
3297   a_value = 2020;
3298   printf ("in A::method1, a_value = %d \n",a_value);
3302 void A::method2 (int v)
3304    ada_method2 (this, v);
3305    printf ("in A::method2, a_value = %d \n",a_value);
3309 A::A(void)
3311    a_value = 1010;
3312   printf ("in A::A, a_value = %d \n",a_value);
3315 -- Ada sources
3316 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3318    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3319    @b{begin}
3320       Method1 (This);
3321       This.A_Value := V;
3322    @b{end} Ada_Method2;
3324 @b{end} Simple_Cpp_Interface;
3326 @b{package} Simple_Cpp_Interface @b{is}
3327    @b{type} A @b{is} @b{limited}
3328       @b{record}
3329          O_Value : Integer;
3330          A_Value : Integer;
3331       @b{end} @b{record};
3332    @b{pragma} Convention (C, A);
3334    @b{procedure} Method1 (This : @b{in} @b{out} A);
3335    @b{pragma} Import (C, Method1);
3337    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3338    @b{pragma} Export (C, Ada_Method2);
3340 @b{end} Simple_Cpp_Interface;
3341 @end smallexample
3343 @node Adapting the Run Time to a New C++ Compiler
3344 @subsection Adapting the Run Time to a New C++ Compiler
3345 @noindent
3346 GNAT offers the capability to derive Ada 95 tagged types directly from
3347 preexisting C++ classes and . See ``Interfacing with C++'' in the
3348 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3349 such a goal
3350 has been made user configurable through a GNAT library unit
3351 @code{Interfaces.CPP}. The default version of this file is adapted to
3352 the GNU C++ compiler. Internal knowledge of the virtual
3353 table layout used by the new C++ compiler is needed to configure
3354 properly this unit. The Interface of this unit is known by the compiler
3355 and cannot be changed except for the value of the constants defining the
3356 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3357 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3358 of this unit for more details.
3360 @node Comparison between GNAT and C/C++ Compilation Models
3361 @section Comparison between GNAT and C/C++ Compilation Models
3363 @noindent
3364 The GNAT model of compilation is close to the C and C++ models. You can
3365 think of Ada specs as corresponding to header files in C. As in C, you
3366 don't need to compile specs; they are compiled when they are used. The
3367 Ada @code{with} is similar in effect to the @code{#include} of a C
3368 header.
3370 One notable difference is that, in Ada, you may compile specs separately
3371 to check them for semantic and syntactic accuracy. This is not always
3372 possible with C headers because they are fragments of programs that have
3373 less specific syntactic or semantic rules.
3375 The other major difference is the requirement for running the binder,
3376 which performs two important functions. First, it checks for
3377 consistency. In C or C++, the only defense against assembling
3378 inconsistent programs lies outside the compiler, in a makefile, for
3379 example. The binder satisfies the Ada requirement that it be impossible
3380 to construct an inconsistent program when the compiler is used in normal
3381 mode.
3383 @cindex Elaboration order control
3384 The other important function of the binder is to deal with elaboration
3385 issues. There are also elaboration issues in C++ that are handled
3386 automatically. This automatic handling has the advantage of being
3387 simpler to use, but the C++ programmer has no control over elaboration.
3388 Where @code{gnatbind} might complain there was no valid order of
3389 elaboration, a C++ compiler would simply construct a program that
3390 malfunctioned at run time.
3392 @node Comparison between GNAT and Conventional Ada Library Models
3393 @section Comparison between GNAT and Conventional Ada Library Models
3395 @noindent
3396 This section is intended to be useful to Ada programmers who have
3397 previously used an Ada compiler implementing the traditional Ada library
3398 model, as described in the Ada 95 Language Reference Manual. If you
3399 have not used such a system, please go on to the next section.
3401 @cindex GNAT library
3402 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
3403 source files themselves acts as the library. Compiling Ada programs does
3404 not generate any centralized information, but rather an object file and
3405 a ALI file, which are of interest only to the binder and linker.
3406 In a traditional system, the compiler reads information not only from
3407 the source file being compiled, but also from the centralized library.
3408 This means that the effect of a compilation depends on what has been
3409 previously compiled. In particular:
3411 @itemize @bullet
3412 @item
3413 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3414 to the version of the unit most recently compiled into the library.
3416 @item
3417 Inlining is effective only if the necessary body has already been
3418 compiled into the library.
3420 @item
3421 Compiling a unit may obsolete other units in the library.
3422 @end itemize
3424 @noindent
3425 In GNAT, compiling one unit never affects the compilation of any other
3426 units because the compiler reads only source files. Only changes to source
3427 files can affect the results of a compilation. In particular:
3429 @itemize @bullet
3430 @item
3431 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3432 to the source version of the unit that is currently accessible to the
3433 compiler.
3435 @item
3436 @cindex Inlining
3437 Inlining requires the appropriate source files for the package or
3438 subprogram bodies to be available to the compiler. Inlining is always
3439 effective, independent of the order in which units are complied.
3441 @item
3442 Compiling a unit never affects any other compilations. The editing of
3443 sources may cause previous compilations to be out of date if they
3444 depended on the source file being modified.
3445 @end itemize
3447 @noindent
3448 The most important result of these differences is that order of compilation
3449 is never significant in GNAT. There is no situation in which one is
3450 required to do one compilation before another. What shows up as order of
3451 compilation requirements in the traditional Ada library becomes, in
3452 GNAT, simple source dependencies; in other words, there is only a set
3453 of rules saying what source files must be present when a file is
3454 compiled.
3456 @ifset vms
3457 @node Placement of temporary files
3458 @section Placement of temporary files
3459 @cindex Temporary files (user control over placement)
3461 @noindent
3462 GNAT creates temporary files in the directory designated by the environment
3463 variable @env{TMPDIR}.
3464 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3465 for detailed information on how environment variables are resolved.
3466 For most users the easiest way to make use of this feature is to simply
3467 define @env{TMPDIR} as a job level logical name).
3468 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3469 for compiler temporary files, then you can include something like the
3470 following command in your @file{LOGIN.COM} file:
3472 @smallexample
3473 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3474 @end smallexample
3476 @noindent
3477 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3478 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3479 designated by @env{TEMP}.
3480 If none of these environment variables are defined then GNAT uses the
3481 directory designated by the logical name @code{SYS$SCRATCH:}
3482 (by default the user's home directory). If all else fails
3483 GNAT uses the current directory for temporary files.
3484 @end ifset
3487 @c *************************
3488 @node Compiling Using gcc
3489 @chapter Compiling Using @code{gcc}
3491 @noindent
3492 This chapter discusses how to compile Ada programs using the @code{gcc}
3493 command. It also describes the set of switches
3494 that can be used to control the behavior of the compiler.
3495 @menu
3496 * Compiling Programs::
3497 * Switches for gcc::
3498 * Search Paths and the Run-Time Library (RTL)::
3499 * Order of Compilation Issues::
3500 * Examples::
3501 @end menu
3503 @node Compiling Programs
3504 @section Compiling Programs
3506 @noindent
3507 The first step in creating an executable program is to compile the units
3508 of the program using the @code{gcc} command. You must compile the
3509 following files:
3511 @itemize @bullet
3512 @item
3513 the body file (@file{.adb}) for a library level subprogram or generic
3514 subprogram
3516 @item
3517 the spec file (@file{.ads}) for a library level package or generic
3518 package that has no body
3520 @item
3521 the body file (@file{.adb}) for a library level package
3522 or generic package that has a body
3524 @end itemize
3526 @noindent
3527 You need @emph{not} compile the following files
3529 @itemize @bullet
3531 @item
3532 the spec of a library unit which has a body
3534 @item
3535 subunits
3536 @end itemize
3538 @noindent
3539 because they are compiled as part of compiling related units. GNAT
3540 package specs
3541 when the corresponding body is compiled, and subunits when the parent is
3542 compiled.
3544 @cindex cannot generate code
3545 If you attempt to compile any of these files, you will get one of the
3546 following error messages (where fff is the name of the file you compiled):
3548 @smallexample
3549 cannot generate code for file @var{fff} (package spec)
3550 to check package spec, use -gnatc
3552 cannot generate code for file @var{fff} (missing subunits)
3553 to check parent unit, use -gnatc
3555 cannot generate code for file @var{fff} (subprogram spec)
3556 to check subprogram spec, use -gnatc
3558 cannot generate code for file @var{fff} (subunit)
3559 to check subunit, use -gnatc
3560 @end smallexample
3562 @noindent
3563 As indicated by the above error messages, if you want to submit
3564 one of these files to the compiler to check for correct semantics
3565 without generating code, then use the @option{-gnatc} switch.
3567 The basic command for compiling a file containing an Ada unit is
3569 @smallexample
3570 $ gcc -c [@var{switches}] @file{file name}
3571 @end smallexample
3573 @noindent
3574 where @var{file name} is the name of the Ada file (usually
3575 having an extension
3576 @file{.ads} for a spec or @file{.adb} for a body).
3577 @ifclear vms
3578 You specify the
3579 @option{-c} switch to tell @code{gcc} to compile, but not link, the file.
3580 @end ifclear
3581 The result of a successful compilation is an object file, which has the
3582 same name as the source file but an extension of @file{.o} and an Ada
3583 Library Information (ALI) file, which also has the same name as the
3584 source file, but with @file{.ali} as the extension. GNAT creates these
3585 two output files in the current directory, but you may specify a source
3586 file in any directory using an absolute or relative path specification
3587 containing the directory information.
3589 @findex gnat1
3590 @code{gcc} is actually a driver program that looks at the extensions of
3591 the file arguments and loads the appropriate compiler. For example, the
3592 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3593 These programs are in directories known to the driver program (in some
3594 configurations via environment variables you set), but need not be in
3595 your path. The @code{gcc} driver also calls the assembler and any other
3596 utilities needed to complete the generation of the required object
3597 files.
3599 It is possible to supply several file names on the same @code{gcc}
3600 command. This causes @code{gcc} to call the appropriate compiler for
3601 each file. For example, the following command lists three separate
3602 files to be compiled:
3604 @smallexample
3605 $ gcc -c x.adb y.adb z.c
3606 @end smallexample
3608 @noindent
3609 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3610 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3611 The compiler generates three object files @file{x.o}, @file{y.o} and
3612 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3613 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3614 @ifclear vms
3615 except for
3616 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3617 @end ifclear
3619 @node Switches for gcc
3620 @section Switches for @code{gcc}
3622 @noindent
3623 The @code{gcc} command accepts switches that control the
3624 compilation process. These switches are fully described in this section.
3625 First we briefly list all the switches, in alphabetical order, then we
3626 describe the switches in more detail in functionally grouped sections.
3628 @menu
3629 * Output and Error Message Control::
3630 * Warning Message Control::
3631 * Debugging and Assertion Control::
3632 * Validity Checking::
3633 * Style Checking::
3634 * Run-Time Checks::
3635 * Stack Overflow Checking::
3636 * Using gcc for Syntax Checking::
3637 * Using gcc for Semantic Checking::
3638 * Compiling Ada 83 Programs::
3639 * Character Set Control::
3640 * File Naming Control::
3641 * Subprogram Inlining Control::
3642 * Auxiliary Output Control::
3643 * Debugging Control::
3644 * Exception Handling Control::
3645 * Units to Sources Mapping Files::
3646 * Integrated Preprocessing::
3647 * Code Generation Control::
3648 @ifset vms
3649 * Return Codes::
3650 @end ifset
3651 @end menu
3653 @table @option
3654 @c !sort!
3655 @ifclear vms
3656 @cindex @option{-b} (@code{gcc})
3657 @item -b @var{target}
3658 Compile your program to run on @var{target}, which is the name of a
3659 system configuration. You must have a GNAT cross-compiler built if
3660 @var{target} is not the same as your host system.
3662 @item -B@var{dir}
3663 @cindex @option{-B} (@code{gcc})
3664 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3665 from @var{dir} instead of the default location. Only use this switch
3666 when multiple versions of the GNAT compiler are available. See the
3667 @code{gcc} manual page for further details. You would normally use the
3668 @option{-b} or @option{-V} switch instead.
3670 @item -c
3671 @cindex @option{-c} (@code{gcc})
3672 Compile. Always use this switch when compiling Ada programs.
3674 Note: for some other languages when using @code{gcc}, notably in
3675 the case of C and C++, it is possible to use
3676 use @code{gcc} without a @option{-c} switch to
3677 compile and link in one step. In the case of GNAT, you
3678 cannot use this approach, because the binder must be run
3679 and @code{gcc} cannot be used to run the GNAT binder.
3680 @end ifclear
3682 @item -fno-inline
3683 @cindex @option{-fno-inline} (@code{gcc})
3684 Suppresses all back-end inlining, even if other optimization or inlining
3685 switches are set.
3686 This includes suppression of inlining that results
3687 from the use of the pragma @code{Inline_Always}.
3688 See also @option{-gnatn} and @option{-gnatN}.
3690 @item -fno-strict-aliasing
3691 @cindex @option{-fno-strict-aliasing} (@code{gcc})
3692 Causes the compiler to avoid assumptions regarding non-aliasing
3693 of objects of different types. See section
3694 @pxref{Optimization and Strict Aliasing} for details.
3696 @item -fstack-check
3697 @cindex @option{-fstack-check} (@code{gcc})
3698 Activates stack checking.
3699 See @ref{Stack Overflow Checking} for details of the use of this option.
3701 @item ^-g^/DEBUG^
3702 @cindex @option{^-g^/DEBUG^} (@code{gcc})
3703 Generate debugging information. This information is stored in the object
3704 file and copied from there to the final executable file by the linker,
3705 where it can be read by the debugger. You must use the
3706 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3708 @item -gnat83
3709 @cindex @option{-gnat83} (@code{gcc})
3710 Enforce Ada 83 restrictions.
3712 @item -gnata
3713 @cindex @option{-gnata} (@code{gcc})
3714 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3715 activated.
3717 @item -gnatA
3718 @cindex @option{-gnatA} (@code{gcc})
3719 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3720 it will be ignored.
3722 @item -gnatb
3723 @cindex @option{-gnatb} (@code{gcc})
3724 Generate brief messages to @file{stderr} even if verbose mode set.
3726 @item -gnatc
3727 @cindex @option{-gnatc} (@code{gcc})
3728 Check syntax and semantics only (no code generation attempted).
3730 @item -gnatd
3731 @cindex @option{-gnatd} (@code{gcc})
3732 Specify debug options for the compiler. The string of characters after
3733 the @option{-gnatd} specify the specific debug options. The possible
3734 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3735 compiler source file @file{debug.adb} for details of the implemented
3736 debug options. Certain debug options are relevant to applications
3737 programmers, and these are documented at appropriate points in this
3738 users guide.
3740 @item -gnatD
3741 @cindex @option{-gnatD} (@code{gcc})
3742 Create expanded source files for source level debugging. This switch
3743 also suppress generation of cross-reference information
3744 (see @option{-gnatx}).
3746 @item -gnatec=@var{path}
3747 @cindex @option{-gnatec} (@code{gcc})
3748 Specify a configuration pragma file
3749 @ifclear vms
3750 (the equal sign is optional)
3751 @end ifclear
3752 (see @ref{The Configuration Pragmas Files}).
3754 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3755 @cindex @option{-gnateD} (@code{gcc})
3756 Defines a symbol, associated with value, for preprocessing.
3757 (see @ref{Integrated Preprocessing})
3759 @item -gnatef
3760 @cindex @option{-gnatef} (@code{gcc})
3761 Display full source path name in brief error messages.
3763 @item -gnatem=@var{path}
3764 @cindex @option{-gnatem} (@code{gcc})
3765 Specify a mapping file
3766 @ifclear vms
3767 (the equal sign is optional)
3768 @end ifclear
3769 (see @ref{Units to Sources Mapping Files}).
3771 @item -gnatep=@var{file}
3772 @cindex @option{-gnatep} (@code{gcc})
3773 Specify a preprocessing data file
3774 @ifclear vms
3775 (the equal sign is optional)
3776 @end ifclear
3777 (see @ref{Integrated Preprocessing}).
3779 @item -gnatE
3780 @cindex @option{-gnatE} (@code{gcc})
3781 Full dynamic elaboration checks.
3783 @item -gnatf
3784 @cindex @option{-gnatf} (@code{gcc})
3785 Full errors. Multiple errors per line, all undefined references, do not
3786 attempt to suppress cascaded errors.
3788 @item -gnatF
3789 @cindex @option{-gnatF} (@code{gcc})
3790 Externals names are folded to all uppercase.
3792 @item -gnatg
3793 @cindex @option{-gnatg} (@code{gcc})
3794 Internal GNAT implementation mode. This should not be used for
3795 applications programs, it is intended only for use by the compiler
3796 and its run-time library. For documentation, see the GNAT sources.
3797 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3798 are generated on unreferenced entities, and all warnings are treated
3799 as errors.
3801 @item -gnatG
3802 @cindex @option{-gnatG} (@code{gcc})
3803 List generated expanded code in source form.
3805 @item ^-gnath^/HELP^
3806 @cindex @option{^-gnath^/HELP^} (@code{gcc})
3807 Output usage information. The output is written to @file{stdout}.
3809 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3810 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
3811 Identifier character set
3812 @ifclear vms
3813 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3814 @end ifclear
3815 @ifset vms
3816 For details of the possible selections for @var{c},
3817 see @xref{Character Set Control}.
3818 @end ifset
3820 @item -gnatk=@var{n}
3821 @cindex @option{-gnatk} (@code{gcc})
3822 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3824 @item -gnatl
3825 @cindex @option{-gnatl} (@code{gcc})
3826 Output full source listing with embedded error messages.
3828 @item -gnatL
3829 @cindex @option{-gnatL} (@code{gcc})
3830 Use the longjmp/setjmp method for exception handling
3832 @item -gnatm=@var{n}
3833 @cindex @option{-gnatm} (@code{gcc})
3834 Limit number of detected error or warning messages to @var{n}
3835 where @var{n} is in the range 1..999_999. The default setting if
3836 no switch is given is 9999. Compilation is terminated if this
3837 limit is exceeded.
3839 @item -gnatn
3840 @cindex @option{-gnatn} (@code{gcc})
3841 Activate inlining for subprograms for which
3842 pragma @code{inline} is specified. This inlining is performed
3843 by the GCC back-end.
3845 @item -gnatN
3846 @cindex @option{-gnatN} (@code{gcc})
3847 Activate front end inlining for subprograms for which
3848 pragma @code{Inline} is specified. This inlining is performed
3849 by the front end and will be visible in the
3850 @option{-gnatG} output.
3851 In some cases, this has proved more effective than the back end
3852 inlining resulting from the use of
3853 @option{-gnatn}.
3854 Note that
3855 @option{-gnatN} automatically implies
3856 @option{-gnatn} so it is not necessary
3857 to specify both options. There are a few cases that the back-end inlining
3858 catches that cannot be dealt with in the front-end.
3860 @item -gnato
3861 @cindex @option{-gnato} (@code{gcc})
3862 Enable numeric overflow checking (which is not normally enabled by
3863 default). Not that division by zero is a separate check that is not
3864 controlled by this switch (division by zero checking is on by default).
3866 @item -gnatp
3867 @cindex @option{-gnatp} (@code{gcc})
3868 Suppress all checks.
3870 @item -gnatP
3871 @cindex @option{-gnatP} (@code{gcc})
3872 Enable polling. This is required on some systems (notably Windows NT) to
3873 obtain asynchronous abort and asynchronous transfer of control capability.
3874 See the description of pragma Polling in the GNAT Reference Manual for
3875 full details.
3877 @item -gnatq
3878 @cindex @option{-gnatq} (@code{gcc})
3879 Don't quit; try semantics, even if parse errors.
3881 @item -gnatQ
3882 @cindex @option{-gnatQ} (@code{gcc})
3883 Don't quit; generate @file{ALI} and tree files even if illegalities.
3885 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3886 @cindex @option{-gnatR} (@code{gcc})
3887 Output representation information for declared types and objects.
3889 @item -gnats
3890 @cindex @option{-gnats} (@code{gcc})
3891 Syntax check only.
3893 @item -gnatS
3894 @cindex @option{-gnatS} (@code{gcc})
3895 Print package Standard.
3897 @item -gnatt
3898 @cindex @option{-gnatt} (@code{gcc})
3899 Generate tree output file.
3901 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3902 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@code{gcc})
3903 All compiler tables start at @var{nnn} times usual starting size.
3905 @item -gnatu
3906 @cindex @option{-gnatu} (@code{gcc})
3907 List units for this compilation.
3909 @item -gnatU
3910 @cindex @option{-gnatU} (@code{gcc})
3911 Tag all error messages with the unique string ``error:''
3913 @item -gnatv
3914 @cindex @option{-gnatv} (@code{gcc})
3915 Verbose mode. Full error output with source lines to @file{stdout}.
3917 @item -gnatV
3918 @cindex @option{-gnatV} (@code{gcc})
3919 Control level of validity checking. See separate section describing
3920 this feature.
3922 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
3923 @cindex @option{^-gnatw^/WARNINGS^} (@code{gcc})
3924 Warning mode where
3925 ^@var{xxx} is a string of option letters that^the list of options^ denotes
3926 the exact warnings that
3927 are enabled or disabled. (see @ref{Warning Message Control})
3929 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3930 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
3931 Wide character encoding method
3932 @ifclear vms
3933 (@var{e}=n/h/u/s/e/8).
3934 @end ifclear
3935 @ifset vms
3936 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3937 @end ifset
3939 @item -gnatx
3940 @cindex @option{-gnatx} (@code{gcc})
3941 Suppress generation of cross-reference information.
3943 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3944 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@code{gcc})
3945 Enable built-in style checks. (see @ref{Style Checking})
3947 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3948 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@code{gcc})
3949 Distribution stub generation and compilation
3950 @ifclear vms
3951 (@var{m}=r/c for receiver/caller stubs).
3952 @end ifclear
3953 @ifset vms
3954 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3955 to be generated and compiled).
3956 @end ifset
3958 @item -gnatZ
3959 Use the zero cost method for exception handling
3961 @item ^-I^/SEARCH=^@var{dir}
3962 @cindex @option{^-I^/SEARCH^} (@code{gcc})
3963 @cindex RTL
3964 Direct GNAT to search the @var{dir} directory for source files needed by
3965 the current compilation
3966 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3968 @item ^-I-^/NOCURRENT_DIRECTORY^
3969 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gcc})
3970 @cindex RTL
3971 Except for the source file named in the command line, do not look for source
3972 files in the directory containing the source file named in the command line
3973 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3975 @ifclear vms
3976 @item -mbig-switch
3977 @cindex @option{-mbig-switch} (@command{gcc})
3978 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
3979 This standard gcc switch causes the compiler to use larger offsets in its
3980 jump table representation for @code{case} statements.
3981 This may result in less efficient code, but is sometimes necessary
3982 (for example on HP-UX targets)
3983 @cindex HP-UX and @option{-mbig-switch} option
3984 in order to compile large and/or nested @code{case} statements.
3986 @item -o @var{file}
3987 @cindex @option{-o} (@code{gcc})
3988 This switch is used in @code{gcc} to redirect the generated object file
3989 and its associated ALI file. Beware of this switch with GNAT, because it may
3990 cause the object file and ALI file to have different names which in turn
3991 may confuse the binder and the linker.
3992 @end ifclear
3994 @item -nostdinc
3995 @cindex @option{-nostdinc} (@command{gcc})
3996 Inhibit the search of the default location for the GNAT Run Time
3997 Library (RTL) source files.
3999 @item -nostdlib
4000 @cindex @option{-nostdlib} (@command{gcc})
4001 Inhibit the search of the default location for the GNAT Run Time
4002 Library (RTL) ALI files.
4004 @ifclear vms
4005 @item -O[@var{n}]
4006 @cindex @option{-O} (@code{gcc})
4007 @var{n} controls the optimization level.
4009 @table @asis
4010 @item n = 0
4011 No optimization, the default setting if no @option{-O} appears
4013 @item n = 1
4014 Normal optimization, the default if you specify @option{-O} without
4015 an operand.
4017 @item n = 2
4018 Extensive optimization
4020 @item n = 3
4021 Extensive optimization with automatic inlining of subprograms not
4022 specified by pragma @code{Inline}. This applies only to
4023 inlining within a unit. For details on control of inlining
4024 see @xref{Subprogram Inlining Control}.
4025 @end table
4026 @end ifclear
4028 @ifset vms
4029 @item  /NOOPTIMIZE
4030 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4031 Equivalent to @option{/OPTIMIZE=NONE}.
4032 This is the default behavior in the absence of an @option{/OPTMIZE}
4033 qualifier.
4035 @item /OPTIMIZE[=(keyword[,...])]
4036 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4037 Selects the level of optimization for your program. The supported
4038 keywords are as follows:
4039 @table @code
4040 @item   ALL
4041 Perform most optimizations, including those that
4042 are expensive.
4043 This is the default if the @option{/OPTMIZE} qualifier is supplied
4044 without keyword options.
4046 @item   NONE
4047 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4049 @item SOME
4050 Perform some optimizations, but omit ones that are costly.
4052 @item   DEVELOPMENT
4053 Same as @code{SOME}.
4055 @item   INLINING
4056 Full optimization, and also attempt automatic inlining of small
4057 subprograms within a unit even when pragma @code{Inline}
4058 is not specified (@pxref{Inlining of Subprograms}).
4060 @item   UNROLL_LOOPS
4061 Try to unroll loops. This keyword may be specified together with
4062 any keyword above other than @code{NONE}. Loop unrolling
4063 usually, but not always, improves the performance of programs.
4064 @end table
4065 @end ifset
4067 @ifclear vms
4068 @item -pass-exit-codes
4069 @cindex @option{-pass-exit-codes} (@code{gcc})
4070 Catch exit codes from the compiler and use the most meaningful as
4071 exit status.
4072 @end ifclear
4074 @item --RTS=@var{rts-path}
4075 @cindex @option{--RTS} (@code{gcc})
4076 Specifies the default location of the runtime library. Same meaning as the
4077 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
4079 @item ^-S^/ASM^
4080 @cindex @option{^-S^/ASM^} (@code{gcc})
4081 ^Used in place of @option{-c} to^Used to^
4082 cause the assembler source file to be
4083 generated, using @file{^.s^.S^} as the extension,
4084 instead of the object file.
4085 This may be useful if you need to examine the generated assembly code.
4087 @item ^-v^/VERBOSE^
4088 @cindex @option{^-v^/VERBOSE^} (@code{gcc})
4089 Show commands generated by the @code{gcc} driver. Normally used only for
4090 debugging purposes or if you need to be sure what version of the
4091 compiler you are executing.
4093 @ifclear vms
4094 @item -V @var{ver}
4095 @cindex @option{-V} (@code{gcc})
4096 Execute @var{ver} version of the compiler. This is the @code{gcc}
4097 version, not the GNAT version.
4098 @end ifclear
4100 @end table
4102 @ifclear vms
4103 You may combine a sequence of GNAT switches into a single switch. For
4104 example, the combined switch
4106 @cindex Combining GNAT switches
4107 @smallexample
4108 -gnatofi3
4109 @end smallexample
4111 @noindent
4112 is equivalent to specifying the following sequence of switches:
4114 @smallexample
4115 -gnato -gnatf -gnati3
4116 @end smallexample
4117 @end ifclear
4120 @c NEED TO CHECK THIS FOR VMS
4122 @noindent
4123 The following restrictions apply to the combination of switches
4124 in this manner:
4126 @itemize @bullet
4127 @item
4128 The switch @option{-gnatc} if combined with other switches must come
4129 first in the string.
4131 @item
4132 The switch @option{-gnats} if combined with other switches must come
4133 first in the string.
4135 @item
4136 The switches
4137 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4138 may not be combined with any other switches.
4140 @ifclear vms
4141 @item
4142 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4143 switch), then all further characters in the switch are interpreted
4144 as style modifiers (see description of @option{-gnaty}).
4146 @item
4147 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4148 switch), then all further characters in the switch are interpreted
4149 as debug flags (see description of @option{-gnatd}).
4151 @item
4152 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4153 switch), then all further characters in the switch are interpreted
4154 as warning mode modifiers (see description of @option{-gnatw}).
4156 @item
4157 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4158 switch), then all further characters in the switch are interpreted
4159 as validity checking options (see description of @option{-gnatV}).
4160 @end ifclear
4161 @end itemize
4164 @node Output and Error Message Control
4165 @subsection Output and Error Message Control
4166 @findex stderr
4168 @noindent
4169 The standard default format for error messages is called ``brief format''.
4170 Brief format messages are written to @file{stderr} (the standard error
4171 file) and have the following form:
4173 @smallexample
4174 e.adb:3:04: Incorrect spelling of keyword "function"
4175 e.adb:4:20: ";" should be "is"
4176 @end smallexample
4178 @noindent
4179 The first integer after the file name is the line number in the file,
4180 and the second integer is the column number within the line.
4181 @code{glide} can parse the error messages
4182 and point to the referenced character.
4183 The following switches provide control over the error message
4184 format:
4186 @table @option
4187 @c !sort!
4188 @item -gnatv
4189 @cindex @option{-gnatv} (@code{gcc})
4190 @findex stdout
4191 @ifclear vms
4192 The v stands for verbose.
4193 @end ifclear
4194 The effect of this setting is to write long-format error
4195 messages to @file{stdout} (the standard output file.
4196 The same program compiled with the
4197 @option{-gnatv} switch would generate:
4199 @smallexample
4200 @cartouche
4201 3. funcion X (Q : Integer)
4202    |
4203 >>> Incorrect spelling of keyword "function"
4204 4. return Integer;
4205                  |
4206 >>> ";" should be "is"
4207 @end cartouche
4208 @end smallexample
4210 @noindent
4211 The vertical bar indicates the location of the error, and the @samp{>>>}
4212 prefix can be used to search for error messages. When this switch is
4213 used the only source lines output are those with errors.
4215 @item -gnatl
4216 @cindex @option{-gnatl} (@code{gcc})
4217 @ifclear vms
4218 The @code{l} stands for list.
4219 @end ifclear
4220 This switch causes a full listing of
4221 the file to be generated. The output might look as follows:
4223 @smallexample
4224 @cartouche
4225  1. procedure E is
4226  2.    V : Integer;
4227  3.    funcion X (Q : Integer)
4228        |
4229     >>> Incorrect spelling of keyword "function"
4230  4.     return Integer;
4231                       |
4232     >>> ";" should be "is"
4233  5.    begin
4234  6.       return Q + Q;
4235  7.    end;
4236  8. begin
4237  9.    V := X + X;
4238 10.end E;
4239 @end cartouche
4240 @end smallexample
4242 @noindent
4243 @findex stderr
4244 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4245 standard output is redirected, a brief summary is written to
4246 @file{stderr} (standard error) giving the number of error messages and
4247 warning messages generated.
4249 @item -gnatU
4250 @cindex @option{-gnatU} (@code{gcc})
4251 This switch forces all error messages to be preceded by the unique
4252 string ``error:''. This means that error messages take a few more
4253 characters in space, but allows easy searching for and identification
4254 of error messages.
4256 @item -gnatb
4257 @cindex @option{-gnatb} (@code{gcc})
4258 @ifclear vms
4259 The @code{b} stands for brief.
4260 @end ifclear
4261 This switch causes GNAT to generate the
4262 brief format error messages to @file{stderr} (the standard error
4263 file) as well as the verbose
4264 format message or full listing (which as usual is written to
4265 @file{stdout} (the standard output file).
4267 @item -gnatm^^=^@var{n}
4268 @cindex @option{-gnatm} (@code{gcc})
4269 @ifclear vms
4270 The @code{m} stands for maximum.
4271 @end ifclear
4272 @var{n} is a decimal integer in the
4273 range of 1 to 999 and limits the number of error messages to be
4274 generated. For example, using @option{-gnatm2} might yield
4276 @smallexample
4277 e.adb:3:04: Incorrect spelling of keyword "function"
4278 e.adb:5:35: missing ".."
4279 fatal error: maximum errors reached
4280 compilation abandoned
4281 @end smallexample
4283 @item -gnatf
4284 @cindex @option{-gnatf} (@code{gcc})
4285 @cindex Error messages, suppressing
4286 @ifclear vms
4287 The @code{f} stands for full.
4288 @end ifclear
4289 Normally, the compiler suppresses error messages that are likely to be
4290 redundant. This switch causes all error
4291 messages to be generated. In particular, in the case of
4292 references to undefined variables. If a given variable is referenced
4293 several times, the normal format of messages is
4294 @smallexample
4295 e.adb:7:07: "V" is undefined (more references follow)
4296 @end smallexample
4298 @noindent
4299 where the parenthetical comment warns that there are additional
4300 references to the variable @code{V}. Compiling the same program with the
4301 @option{-gnatf} switch yields
4303 @smallexample
4304 e.adb:7:07: "V" is undefined
4305 e.adb:8:07: "V" is undefined
4306 e.adb:8:12: "V" is undefined
4307 e.adb:8:16: "V" is undefined
4308 e.adb:9:07: "V" is undefined
4309 e.adb:9:12: "V" is undefined
4310 @end smallexample
4312 @noindent
4313 The @option{-gnatf} switch also generates additional information for
4314 some error messages.  Some examples are:
4316 @itemize @bullet
4317 @item
4318 Full details on entities not available in high integrity mode
4319 @item
4320 Details on possibly non-portable unchecked conversion
4321 @item
4322 List possible interpretations for ambiguous calls
4323 @item
4324 Additional details on incorrect parameters
4325 @end itemize
4328 @item -gnatq
4329 @cindex @option{-gnatq} (@code{gcc})
4330 @ifclear vms
4331 The @code{q} stands for quit (really ``don't quit'').
4332 @end ifclear
4333 In normal operation mode, the compiler first parses the program and
4334 determines if there are any syntax errors. If there are, appropriate
4335 error messages are generated and compilation is immediately terminated.
4336 This switch tells
4337 GNAT to continue with semantic analysis even if syntax errors have been
4338 found. This may enable the detection of more errors in a single run. On
4339 the other hand, the semantic analyzer is more likely to encounter some
4340 internal fatal error when given a syntactically invalid tree.
4342 @item -gnatQ
4343 @cindex @option{-gnatQ} (@code{gcc})
4344 In normal operation mode, the @file{ALI} file is not generated if any
4345 illegalities are detected in the program. The use of @option{-gnatQ} forces
4346 generation of the @file{ALI} file. This file is marked as being in
4347 error, so it cannot be used for binding purposes, but it does contain
4348 reasonably complete cross-reference information, and thus may be useful
4349 for use by tools (e.g. semantic browsing tools or integrated development
4350 environments) that are driven from the @file{ALI} file. This switch
4351 implies @option{-gnatq}, since the semantic phase must be run to get a
4352 meaningful ALI file.
4354 In addition, if @option{-gnatt} is also specified, then the tree file is
4355 generated even if there are illegalities. It may be useful in this case
4356 to also specify @option{-gnatq} to ensure that full semantic processing
4357 occurs. The resulting tree file can be processed by ASIS, for the purpose
4358 of providing partial information about illegal units, but if the error
4359 causes the tree to be badly malformed, then ASIS may crash during the
4360 analysis.
4362 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4363 being in error, @code{gnatmake} will attempt to recompile the source when it
4364 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4366 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4367 since ALI files are never generated if @option{-gnats} is set.
4369 @end table
4372 @node Warning Message Control
4373 @subsection Warning Message Control
4374 @cindex Warning messages
4375 @noindent
4376 In addition to error messages, which correspond to illegalities as defined
4377 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4378 situations.
4380 First, the compiler considers some constructs suspicious and generates a
4381 warning message to alert you to a possible error. Second, if the
4382 compiler detects a situation that is sure to raise an exception at
4383 run time, it generates a warning message. The following shows an example
4384 of warning messages:
4385 @smallexample
4386 e.adb:4:24: warning: creation of object may raise Storage_Error
4387 e.adb:10:17: warning: static value out of range
4388 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4389 @end smallexample
4391 @noindent
4392 GNAT considers a large number of situations as appropriate
4393 for the generation of warning messages. As always, warnings are not
4394 definite indications of errors. For example, if you do an out-of-range
4395 assignment with the deliberate intention of raising a
4396 @code{Constraint_Error} exception, then the warning that may be
4397 issued does not indicate an error. Some of the situations for which GNAT
4398 issues warnings (at least some of the time) are given in the following
4399 list. This list is not complete, and new warnings are often added to
4400 subsequent versions of GNAT. The list is intended to give a general idea
4401 of the kinds of warnings that are generated.
4403 @itemize @bullet
4404 @item
4405 Possible infinitely recursive calls
4407 @item
4408 Out-of-range values being assigned
4410 @item
4411 Possible order of elaboration problems
4413 @item
4414 Unreachable code
4416 @item
4417 Fixed-point type declarations with a null range
4419 @item
4420 Direct_IO or Sequential_IO instantiated with a type that has access values
4422 @item
4423 Variables that are never assigned a value
4425 @item
4426 Variables that are referenced before being initialized
4428 @item
4429 Task entries with no corresponding @code{accept} statement
4431 @item
4432 Duplicate accepts for the same task entry in a @code{select}
4434 @item
4435 Objects that take too much storage
4437 @item
4438 Unchecked conversion between types of differing sizes
4440 @item
4441 Missing @code{return} statement along some execution path in a function
4443 @item
4444 Incorrect (unrecognized) pragmas
4446 @item
4447 Incorrect external names
4449 @item
4450 Allocation from empty storage pool
4452 @item
4453 Potentially blocking operation in protected type
4455 @item
4456 Suspicious parenthesization of expressions
4458 @item
4459 Mismatching bounds in an aggregate
4461 @item
4462 Attempt to return local value by reference
4465 @item
4466 Premature instantiation of a generic body
4468 @item
4469 Attempt to pack aliased components
4471 @item
4472 Out of bounds array subscripts
4474 @item
4475 Wrong length on string assignment
4477 @item
4478 Violations of style rules if style checking is enabled
4480 @item
4481 Unused @code{with} clauses
4483 @item
4484 @code{Bit_Order} usage that does not have any effect
4486 @item
4487 @code{Standard.Duration} used to resolve universal fixed expression
4489 @item
4490 Dereference of possibly null value
4492 @item
4493 Declaration that is likely to cause storage error
4495 @item
4496 Internal GNAT unit @code{with}'ed by application unit
4498 @item
4499 Values known to be out of range at compile time
4501 @item
4502 Unreferenced labels and variables
4504 @item
4505 Address overlays that could clobber memory
4507 @item
4508 Unexpected initialization when address clause present
4510 @item
4511 Bad alignment for address clause
4513 @item
4514 Useless type conversions
4516 @item
4517 Redundant assignment statements and other redundant constructs
4519 @item
4520 Useless exception handlers
4522 @item
4523 Accidental hiding of name by child unit
4526 @item
4527 Access before elaboration detected at compile time
4529 @item
4530 A range in a @code{for} loop that is known to be null or might be null
4532 @end itemize
4534 @noindent
4535 The following switches are available to control the handling of
4536 warning messages:
4538 @table @option
4539 @c !sort!
4540 @item -gnatwa
4541 @emph{Activate all optional errors.}
4542 @cindex @option{-gnatwa} (@code{gcc})
4543 This switch activates most optional warning messages, see remaining list
4544 in this section for details on optional warning messages that can be
4545 individually controlled.  The warnings that are not turned on by this
4546 switch are
4547 @option{-gnatwd} (implicit dereferencing),
4548 @option{-gnatwh} (hiding),
4549 and @option{-gnatwl} (elaboration warnings).
4550 All other optional warnings are turned on.
4552 @item -gnatwA
4553 @emph{Suppress all optional errors.}
4554 @cindex @option{-gnatwA} (@code{gcc})
4555 This switch suppresses all optional warning messages, see remaining list
4556 in this section for details on optional warning messages that can be
4557 individually controlled.
4559 @item -gnatwc
4560 @emph{Activate warnings on conditionals.}
4561 @cindex @option{-gnatwc} (@code{gcc})
4562 @cindex Conditionals, constant
4563 This switch activates warnings for conditional expressions used in
4564 tests that are known to be True or False at compile time. The default
4565 is that such warnings are not generated.
4566 Note that this warning does
4567 not get issued for the use of boolean variables or constants whose
4568 values are known at compile time, since this is a standard technique
4569 for conditional compilation in Ada, and this would generate too many
4570 ``false positive'' warnings.
4571 This warning can also be turned on using @option{-gnatwa}.
4573 @item -gnatwC
4574 @emph{Suppress warnings on conditionals.}
4575 @cindex @option{-gnatwC} (@code{gcc})
4576 This switch suppresses warnings for conditional expressions used in
4577 tests that are known to be True or False at compile time.
4579 @item -gnatwd
4580 @emph{Activate warnings on implicit dereferencing.}
4581 @cindex @option{-gnatwd} (@code{gcc})
4582 If this switch is set, then the use of a prefix of an access type
4583 in an indexed component, slice, or selected component without an
4584 explicit @code{.all} will generate a warning. With this warning
4585 enabled, access checks occur only at points where an explicit
4586 @code{.all} appears in the source code (assuming no warnings are
4587 generated as a result of this switch). The default is that such
4588 warnings are not generated.
4589 Note that @option{-gnatwa} does not affect the setting of
4590 this warning option.
4592 @item -gnatwD
4593 @emph{Suppress warnings on implicit dereferencing.}
4594 @cindex @option{-gnatwD} (@code{gcc})
4595 @cindex Implicit dereferencing
4596 @cindex Dereferencing, implicit
4597 This switch suppresses warnings for implicit dereferences in
4598 indexed components, slices, and selected components.
4600 @item -gnatwe
4601 @emph{Treat warnings as errors.}
4602 @cindex @option{-gnatwe} (@code{gcc})
4603 @cindex Warnings, treat as error
4604 This switch causes warning messages to be treated as errors.
4605 The warning string still appears, but the warning messages are counted
4606 as errors, and prevent the generation of an object file.
4608 @item -gnatwf
4609 @emph{Activate warnings on unreferenced formals.}
4610 @cindex @option{-gnatwf} (@code{gcc})
4611 @cindex Formals, unreferenced
4612 This switch causes a warning to be generated if a formal parameter
4613 is not referenced in the body of the subprogram. This warning can
4614 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4616 @item -gnatwF
4617 @emph{Suppress warnings on unreferenced formals.}
4618 @cindex @option{-gnatwF} (@code{gcc})
4619 This switch suppresses warnings for unreferenced formal
4620 parameters. Note that the
4621 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4622 effect of warning on unreferenced entities other than subprogram
4623 formals.
4625 @item -gnatwg
4626 @emph{Activate warnings on unrecognized pragmas.}
4627 @cindex @option{-gnatwg} (@code{gcc})
4628 @cindex Pragmas, unrecognized
4629 This switch causes a warning to be generated if an unrecognized
4630 pragma is encountered. Apart from issuing this warning, the
4631 pragma is ignored and has no effect. This warning can
4632 also be turned on using @option{-gnatwa}. The default
4633 is that such warnings are issued (satisfying the Ada Reference
4634 Manual requirement that such warnings appear).
4636 @item -gnatwG
4637 @emph{Suppress warnings on unrecognized pragmas.}
4638 @cindex @option{-gnatwG} (@code{gcc})
4639 This switch suppresses warnings for unrecognized pragmas.
4641 @item -gnatwh
4642 @emph{Activate warnings on hiding.}
4643 @cindex @option{-gnatwh} (@code{gcc})
4644 @cindex Hiding of Declarations
4645 This switch activates warnings on hiding declarations.
4646 A declaration is considered hiding
4647 if it is for a non-overloadable entity, and it declares an entity with the
4648 same name as some other entity that is directly or use-visible. The default
4649 is that such warnings are not generated.
4650 Note that @option{-gnatwa} does not affect the setting of this warning option.
4652 @item -gnatwH
4653 @emph{Suppress warnings on hiding.}
4654 @cindex @option{-gnatwH} (@code{gcc})
4655 This switch suppresses warnings on hiding declarations.
4657 @item -gnatwi
4658 @emph{Activate warnings on implementation units.}
4659 @cindex @option{-gnatwi} (@code{gcc})
4660 This switch activates warnings for a @code{with} of an internal GNAT
4661 implementation unit, defined as any unit from the @code{Ada},
4662 @code{Interfaces}, @code{GNAT},
4663 ^^@code{DEC},^ or @code{System}
4664 hierarchies that is not
4665 documented in either the Ada Reference Manual or the GNAT
4666 Programmer's Reference Manual. Such units are intended only
4667 for internal implementation purposes and should not be @code{with}'ed
4668 by user programs. The default is that such warnings are generated
4669 This warning can also be turned on using @option{-gnatwa}.
4671 @item -gnatwI
4672 @emph{Disable warnings on implementation units.}
4673 @cindex @option{-gnatwI} (@code{gcc})
4674 This switch disables warnings for a @code{with} of an internal GNAT
4675 implementation unit.
4677 @item -gnatwj
4678 @emph{Activate warnings on obsolescent features (Annex J).}
4679 @cindex @option{-gnatwj} (@code{gcc})
4680 @cindex Features, obsolescent
4681 @cindex Obsolescent features
4682 If this warning option is activated, then warnings are generated for
4683 calls to subprograms marked with @code{pragma Obsolescent} and
4684 for use of features in Annex J of the Ada Reference Manual. In the
4685 case of Annex J, not all features are flagged. In particular use
4686 of the renamed packages (like @code{Text_IO}) and use of package
4687 @code{ASCII} are not flagged, since these are very common and
4688 would generate many annoying positive warnings. The default is that
4689 such warnings are not generated.
4691 @item -gnatwJ
4692 @emph{Suppress warnings on obsolescent features (Annex J).}
4693 @cindex @option{-gnatwJ} (@code{gcc})
4694 This switch disables warnings on use of obsolescent features.
4696 @item -gnatwk
4697 @emph{Activate warnings on variables that could be constants.}
4698 @cindex @option{-gnatwk} (@code{gcc})
4699 This switch activates warnings for variables that are initialized but
4700 never modified, and then could be declared constants.
4702 @item -gnatwK
4703 @emph{Suppress warnings on variables that could be constants.}
4704 @cindex @option{-gnatwK} (@code{gcc})
4705 This switch disables warnings on variables that could be declared constants.
4707 @item -gnatwl
4708 @emph{Activate warnings for missing elaboration pragmas.}
4709 @cindex @option{-gnatwl} (@code{gcc})
4710 @cindex Elaboration, warnings
4711 This switch activates warnings on missing
4712 @code{pragma Elaborate_All} statements.
4713 See the section in this guide on elaboration checking for details on
4714 when such pragma should be used. Warnings are also generated if you
4715 are using the static mode of elaboration, and a @code{pragma Elaborate}
4716 is encountered. The default is that such warnings
4717 are not generated.
4718 This warning is not automatically turned on by the use of @option{-gnatwa}.
4720 @item -gnatwL
4721 @emph{Suppress warnings for missing elaboration pragmas.}
4722 @cindex @option{-gnatwL} (@code{gcc})
4723 This switch suppresses warnings on missing pragma Elaborate_All statements.
4724 See the section in this guide on elaboration checking for details on
4725 when such pragma should be used.
4727 @item -gnatwm
4728 @emph{Activate warnings on modified but unreferenced variables.}
4729 @cindex @option{-gnatwm} (@code{gcc})
4730 This switch activates warnings for variables that are assigned (using
4731 an initialization value or with one or more assignment statements) but
4732 whose value is never read. The warning is suppressed for volatile
4733 variables and also for variables that are renamings of other variables
4734 or for which an address clause is given.
4735 This warning can also be turned on using @option{-gnatwa}.
4737 @item -gnatwM
4738 @emph{Disable warnings on modified but unreferenced variables.}
4739 @cindex @option{-gnatwM} (@code{gcc})
4740 This switch disables warnings for variables that are assigned or
4741 initialized, but never read.
4743 @item -gnatwn
4744 @emph{Set normal warnings mode.}
4745 @cindex @option{-gnatwn} (@code{gcc})
4746 This switch sets normal warning mode, in which enabled warnings are
4747 issued and treated as warnings rather than errors. This is the default
4748 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4749 an explicit @option{-gnatws} or
4750 @option{-gnatwe}. It also cancels the effect of the
4751 implicit @option{-gnatwe} that is activated by the
4752 use of @option{-gnatg}.
4754 @item -gnatwo
4755 @emph{Activate warnings on address clause overlays.}
4756 @cindex @option{-gnatwo} (@code{gcc})
4757 @cindex Address Clauses, warnings
4758 This switch activates warnings for possibly unintended initialization
4759 effects of defining address clauses that cause one variable to overlap
4760 another. The default is that such warnings are generated.
4761 This warning can also be turned on using @option{-gnatwa}.
4763 @item -gnatwO
4764 @emph{Suppress warnings on address clause overlays.}
4765 @cindex @option{-gnatwO} (@code{gcc})
4766 This switch suppresses warnings on possibly unintended initialization
4767 effects of defining address clauses that cause one variable to overlap
4768 another.
4770 @item -gnatwp
4771 @emph{Activate warnings on ineffective pragma Inlines.}
4772 @cindex @option{-gnatwp} (@code{gcc})
4773 @cindex Inlining, warnings
4774 This switch activates warnings for failure of front end inlining
4775 (activated by @option{-gnatN}) to inline a particular call. There are
4776 many reasons for not being able to inline a call, including most
4777 commonly that the call is too complex to inline.
4778 This warning can also be turned on using @option{-gnatwa}.
4780 @item -gnatwP
4781 @emph{Suppress warnings on ineffective pragma Inlines.}
4782 @cindex @option{-gnatwP} (@code{gcc})
4783 This switch suppresses warnings on ineffective pragma Inlines. If the
4784 inlining mechanism cannot inline a call, it will simply ignore the
4785 request silently.
4787 @item -gnatwr
4788 @emph{Activate warnings on redundant constructs.}
4789 @cindex @option{-gnatwr} (@code{gcc})
4790 This switch activates warnings for redundant constructs. The following
4791 is the current list of constructs regarded as redundant:
4792 This warning can also be turned on using @option{-gnatwa}.
4794 @itemize @bullet
4795 @item
4796 Assignment of an item to itself.
4797 @item
4798 Type conversion that converts an expression to its own type.
4799 @item
4800 Use of the attribute @code{Base} where @code{typ'Base} is the same
4801 as @code{typ}.
4802 @item
4803 Use of pragma @code{Pack} when all components are placed by a record
4804 representation clause.
4805 @item
4806 Exception handler containing only a reraise statement (raise with no
4807 operand) which has no effect.
4808 @item
4809 Use of the operator abs on an operand that is known at compile time
4810 to be non-negative
4811 @item
4812 Use of an unnecessary extra level of parentheses (C-style) around conditions
4813 in @code{if} statements, @code{while} statements and @code{exit} statements.
4814 @item
4815 Comparison of boolean expressions to an explicit True value.
4816 @end itemize
4818 @item -gnatwR
4819 @emph{Suppress warnings on redundant constructs.}
4820 @cindex @option{-gnatwR} (@code{gcc})
4821 This switch suppresses warnings for redundant constructs.
4823 @item -gnatws
4824 @emph{Suppress all warnings.}
4825 @cindex @option{-gnatws} (@code{gcc})
4826 This switch completely suppresses the
4827 output of all warning messages from the GNAT front end.
4828 Note that it does not suppress warnings from the @code{gcc} back end.
4829 To suppress these back end warnings as well, use the switch @option{-w}
4830 in addition to @option{-gnatws}.
4832 @item -gnatwu
4833 @emph{Activate warnings on unused entities.}
4834 @cindex @option{-gnatwu} (@code{gcc})
4835 This switch activates warnings to be generated for entities that
4836 are declared but not referenced, and for units that are @code{with}'ed
4837 and not
4838 referenced. In the case of packages, a warning is also generated if
4839 no entities in the package are referenced. This means that if the package
4840 is referenced but the only references are in @code{use}
4841 clauses or @code{renames}
4842 declarations, a warning is still generated. A warning is also generated
4843 for a generic package that is @code{with}'ed but never instantiated.
4844 In the case where a package or subprogram body is compiled, and there
4845 is a @code{with} on the corresponding spec
4846 that is only referenced in the body,
4847 a warning is also generated, noting that the
4848 @code{with} can be moved to the body. The default is that
4849 such warnings are not generated.
4850 This switch also activates warnings on unreferenced formals
4851 (it is includes the effect of @option{-gnatwf}).
4852 This warning can also be turned on using @option{-gnatwa}.
4854 @item -gnatwU
4855 @emph{Suppress warnings on unused entities.}
4856 @cindex @option{-gnatwU} (@code{gcc})
4857 This switch suppresses warnings for unused entities and packages.
4858 It also turns off warnings on unreferenced formals (and thus includes
4859 the effect of @option{-gnatwF}).
4861 @item -gnatwv
4862 @emph{Activate warnings on unassigned variables.}
4863 @cindex @option{-gnatwv} (@code{gcc})
4864 @cindex Unassigned variable warnings
4865 This switch activates warnings for access to variables which
4866 may not be properly initialized. The default is that
4867 such warnings are generated.
4869 @item -gnatwV
4870 @emph{Suppress warnings on unassigned variables.}
4871 @cindex @option{-gnatwV} (@code{gcc})
4872 This switch suppresses warnings for access to variables which
4873 may not be properly initialized.
4875 @item -gnatwx
4876 @emph{Activate warnings on Export/Import pragmas.}
4877 @cindex @option{-gnatwx} (@code{gcc})
4878 @cindex Export/Import pragma warnings
4879 This switch activates warnings on Export/Import pragmas when
4880 the compiler detects a possible conflict between the Ada and
4881 foreign language calling sequences. For example, the use of
4882 default parameters in a convention C procedure is dubious
4883 because the C compiler cannot supply the proper default, so
4884 a warning is issued. The default is that such warnings are
4885 generated.
4887 @item -gnatwX
4888 @emph{Suppress warnings on Export/Import pragmas.}
4889 @cindex @option{-gnatwX} (@code{gcc})
4890 This switch suppresses warnings on Export/Import pragmas.
4891 The sense of this is that you are telling the compiler that
4892 you know what you are doing in writing the pragma, and it
4893 should not complain at you.
4895 @item -gnatwz
4896 @emph{Activate warnings on unchecked conversions.}
4897 @cindex @option{-gnatwz} (@code{gcc})
4898 @cindex Unchecked_Conversion warnings
4899 This switch activates warnings for unchecked conversions
4900 where the types are known at compile time to have different
4901 sizes. The default
4902 is that such warnings are generated.
4904 @item -gnatwZ
4905 @emph{Suppress warnings on unchecked conversions.}
4906 @cindex @option{-gnatwZ} (@code{gcc})
4907 This switch suppresses warnings for unchecked conversions
4908 where the types are known at compile time to have different
4909 sizes.
4911 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
4912 @cindex @option{-Wuninitialized}
4913 The warnings controlled by the @option{-gnatw} switch are generated by the
4914 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
4915 can provide additional warnings. One such useful warning is provided by
4916 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
4917 conjunction with tunrning on optimization mode. This causes the flow
4918 analysis circuits of the back end optimizer to output additional
4919 warnings about uninitialized variables.
4921 @item ^-w^/NO_BACK_END_WARNINGS^
4922 @cindex @option{-w}
4923 This switch suppresses warnings from the @option{^gcc^GCC^} back end. It may
4924 be used in conjunction with @option{-gnatws} to ensure that all warnings
4925 are suppressed during the entire compilation process.
4927 @end table
4929 @noindent
4930 @ifclear vms
4931 A string of warning parameters can be used in the same parameter. For example:
4933 @smallexample
4934 -gnatwaLe
4935 @end smallexample
4937 @noindent
4938 will turn on all optional warnings except for elaboration pragma warnings,
4939 and also specify that warnings should be treated as errors.
4940 @end ifclear
4941 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
4943 @table @option
4944 @c !sort!
4945 @item -gnatwC
4946 @item -gnatwD
4947 @item -gnatwF
4948 @item -gnatwg
4949 @item -gnatwH
4950 @item -gnatwi
4951 @item -gnatwJ
4952 @item -gnatwK
4953 @item -gnatwL
4954 @item -gnatwM
4955 @item -gnatwn
4956 @item -gnatwo
4957 @item -gnatwP
4958 @item -gnatwR
4959 @item -gnatwU
4960 @item -gnatwv
4961 @item -gnatwz
4962 @item -gnatwx
4964 @end table
4967 @node Debugging and Assertion Control
4968 @subsection Debugging and Assertion Control
4970 @table @option
4971 @item -gnata
4972 @cindex @option{-gnata} (@code{gcc})
4973 @findex Assert
4974 @findex Debug
4975 @cindex Assertions
4977 @noindent
4978 The pragmas @code{Assert} and @code{Debug} normally have no effect and
4979 are ignored. This switch, where @samp{a} stands for assert, causes
4980 @code{Assert} and @code{Debug} pragmas to be activated.
4982 The pragmas have the form:
4984 @smallexample
4985 @cartouche
4986    @b{pragma} Assert (@var{Boolean-expression} [,
4987                       @var{static-string-expression}])
4988    @b{pragma} Debug (@var{procedure call})
4989 @end cartouche
4990 @end smallexample
4992 @noindent
4993 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
4994 If the result is @code{True}, the pragma has no effect (other than
4995 possible side effects from evaluating the expression). If the result is
4996 @code{False}, the exception @code{Assert_Failure} declared in the package
4997 @code{System.Assertions} is
4998 raised (passing @var{static-string-expression}, if present, as the
4999 message associated with the exception). If no string expression is
5000 given the default is a string giving the file name and line number
5001 of the pragma.
5003 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5004 @code{pragma Debug} may appear within a declaration sequence, allowing
5005 debugging procedures to be called between declarations.
5007 @ifset vms
5008 @item /DEBUG[=debug-level]
5009 @itemx  /NODEBUG
5010 Specifies how much debugging information is to be included in
5011 the resulting object file where 'debug-level' is one of the following:
5012 @table @code
5013 @item   TRACEBACK
5014 Include both debugger symbol records and traceback
5015 the object file.
5016 This is the default setting.
5017 @item   ALL
5018 Include both debugger symbol records and traceback in
5019 object file.
5020 @item   NONE
5021 Excludes both debugger symbol records and traceback
5022 the object file. Same as /NODEBUG.
5023 @item   SYMBOLS
5024 Includes only debugger symbol records in the object
5025 file. Note that this doesn't include traceback information.
5026 @end table
5027 @end ifset
5028 @end table
5030 @node Validity Checking
5031 @subsection Validity Checking
5032 @findex Validity Checking
5034 @noindent
5035 The Ada 95 Reference Manual has specific requirements for checking
5036 for invalid values. In particular, RM 13.9.1 requires that the
5037 evaluation of invalid values (for example from unchecked conversions),
5038 not result in erroneous execution. In GNAT, the result of such an
5039 evaluation in normal default mode is to either use the value
5040 unmodified, or to raise Constraint_Error in those cases where use
5041 of the unmodified value would cause erroneous execution. The cases
5042 where unmodified values might lead to erroneous execution are case
5043 statements (where a wild jump might result from an invalid value),
5044 and subscripts on the left hand side (where memory corruption could
5045 occur as a result of an invalid value).
5047 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5048 checking mode.
5049 @ifclear vms
5050 The @code{x} argument is a string of letters that
5051 indicate validity checks that are performed or not performed in addition
5052 to the default checks described above.
5053 @end ifclear
5054 @ifset vms
5055 The options allowed for this qualifier
5056 indicate validity checks that are performed or not performed in addition
5057 to the default checks described above.
5058 @end ifset
5061 @table @option
5062 @c !sort!
5063 @item -gnatVa
5064 @emph{All validity checks.}
5065 @cindex @option{-gnatVa} (@code{gcc})
5066 All validity checks are turned on.
5067 @ifclear vms
5068 That is, @option{-gnatVa} is
5069 equivalent to @option{gnatVcdfimorst}.
5070 @end ifclear
5072 @item -gnatVc
5073 @emph{Validity checks for copies.}
5074 @cindex @option{-gnatVc} (@code{gcc})
5075 The right hand side of assignments, and the initializing values of
5076 object declarations are validity checked.
5078 @item -gnatVd
5079 @emph{Default (RM) validity checks.}
5080 @cindex @option{-gnatVd} (@code{gcc})
5081 Some validity checks are done by default following normal Ada semantics
5082 (RM 13.9.1 (9-11)).
5083 A check is done in case statements that the expression is within the range
5084 of the subtype. If it is not, Constraint_Error is raised.
5085 For assignments to array components, a check is done that the expression used
5086 as index is within the range. If it is not, Constraint_Error is raised.
5087 Both these validity checks may be turned off using switch @option{-gnatVD}.
5088 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5089 switch @option{-gnatVd} will leave the checks turned on.
5090 Switch @option{-gnatVD} should be used only if you are sure that all such
5091 expressions have valid values. If you use this switch and invalid values
5092 are present, then the program is erroneous, and wild jumps or memory
5093 overwriting may occur.
5095 @item -gnatVf
5096 @emph{Validity checks for floating-point values.}
5097 @cindex @option{-gnatVf} (@code{gcc})
5098 In the absence of this switch, validity checking occurs only for discrete
5099 values. If @option{-gnatVf} is specified, then validity checking also applies
5100 for floating-point values, and NaN's and infinities are considered invalid,
5101 as well as out of range values for constrained types. Note that this means
5102 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5103 in which floating-point values are checked depends on the setting of other
5104 options. For example,
5105 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5106 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5107 (the order does not matter) specifies that floating-point parameters of mode
5108 @code{in} should be validity checked.
5110 @item -gnatVi
5111 @emph{Validity checks for @code{in} mode parameters}
5112 @cindex @option{-gnatVi} (@code{gcc})
5113 Arguments for parameters of mode @code{in} are validity checked in function
5114 and procedure calls at the point of call.
5116 @item -gnatVm
5117 @emph{Validity checks for @code{in out} mode parameters.}
5118 @cindex @option{-gnatVm} (@code{gcc})
5119 Arguments for parameters of mode @code{in out} are validity checked in
5120 procedure calls at the point of call. The @code{'m'} here stands for
5121 modify, since this concerns parameters that can be modified by the call.
5122 Note that there is no specific option to test @code{out} parameters,
5123 but any reference within the subprogram will be tested in the usual
5124 manner, and if an invalid value is copied back, any reference to it
5125 will be subject to validity checking.
5127 @item -gnatVn
5128 @emph{No validity checks.}
5129 @cindex @option{-gnatVn} (@code{gcc})
5130 This switch turns off all validity checking, including the default checking
5131 for case statements and left hand side subscripts. Note that the use of
5132 the switch @option{-gnatp} suppresses all run-time checks, including
5133 validity checks, and thus implies @option{-gnatVn}. When this switch
5134 is used, it cancels any other @option{-gnatV} previously issued.
5136 @item -gnatVo
5137 @emph{Validity checks for operator and attribute operands.}
5138 @cindex @option{-gnatVo} (@code{gcc})
5139 Arguments for predefined operators and attributes are validity checked.
5140 This includes all operators in package @code{Standard},
5141 the shift operators defined as intrinsic in package @code{Interfaces}
5142 and operands for attributes such as @code{Pos}. Checks are also made
5143 on individual component values for composite comparisons.
5145 @item -gnatVp
5146 @emph{Validity checks for parameters.}
5147 @cindex @option{-gnatVp} (@code{gcc})
5148 This controls the treatment of parameters within a subprogram (as opposed
5149 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5150 of parameters on a call. If either of these call options is used, then
5151 normally an assumption is made within a subprogram that the input arguments
5152 have been validity checking at the point of call, and do not need checking
5153 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5154 is not made, and parameters are not assumed to be valid, so their validity
5155 will be checked (or rechecked) within the subprogram.
5157 @item -gnatVr
5158 @emph{Validity checks for function returns.}
5159 @cindex @option{-gnatVr} (@code{gcc})
5160 The expression in @code{return} statements in functions is validity
5161 checked.
5163 @item -gnatVs
5164 @emph{Validity checks for subscripts.}
5165 @cindex @option{-gnatVs} (@code{gcc})
5166 All subscripts expressions are checked for validity, whether they appear
5167 on the right side or left side (in default mode only left side subscripts
5168 are validity checked).
5170 @item -gnatVt
5171 @emph{Validity checks for tests.}
5172 @cindex @option{-gnatVt} (@code{gcc})
5173 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5174 statements are checked, as well as guard expressions in entry calls.
5176 @end table
5178 @noindent
5179 The @option{-gnatV} switch may be followed by
5180 ^a string of letters^a list of options^
5181 to turn on a series of validity checking options.
5182 For example,
5183 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5184 specifies that in addition to the default validity checking, copies and
5185 function return expressions are to be validity checked.
5186 In order to make it easier
5187 to specify the desired combination of effects,
5188 @ifclear vms
5189 the upper case letters @code{CDFIMORST} may
5190 be used to turn off the corresponding lower case option.
5191 @end ifclear
5192 @ifset vms
5193 the prefix @code{NO} on an option turns off the corresponding validity
5194 checking:
5195 @itemize @bullet
5196 @item @code{NOCOPIES}
5197 @item @code{NODEFAULT}
5198 @item @code{NOFLOATS}
5199 @item @code{NOIN_PARAMS}
5200 @item @code{NOMOD_PARAMS}
5201 @item @code{NOOPERANDS}
5202 @item @code{NORETURNS}
5203 @item @code{NOSUBSCRIPTS}
5204 @item @code{NOTESTS}
5205 @end itemize
5206 @end ifset
5207 Thus
5208 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5209 turns on all validity checking options except for
5210 checking of @code{@b{in out}} procedure arguments.
5212 The specification of additional validity checking generates extra code (and
5213 in the case of @option{-gnatVa} the code expansion can be substantial.
5214 However, these additional checks can be very useful in detecting
5215 uninitialized variables, incorrect use of unchecked conversion, and other
5216 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5217 is useful in conjunction with the extra validity checking, since this
5218 ensures that wherever possible uninitialized variables have invalid values.
5220 See also the pragma @code{Validity_Checks} which allows modification of
5221 the validity checking mode at the program source level, and also allows for
5222 temporary disabling of validity checks.
5225 @node Style Checking
5226 @subsection Style Checking
5227 @findex Style checking
5229 @noindent
5230 The @option{-gnaty^x^(option,option,...)^} switch
5231 @cindex @option{-gnaty} (@code{gcc})
5232 causes the compiler to
5233 enforce specified style rules. A limited set of style rules has been used
5234 in writing the GNAT sources themselves. This switch allows user programs
5235 to activate all or some of these checks. If the source program fails a
5236 specified style check, an appropriate warning message is given, preceded by
5237 the character sequence ``(style)''.
5238 @ifset vms
5239 @code{(option,option,...)} is a sequence of keywords
5240 @end ifset
5241 @ifclear vms
5242 The string @var{x} is a sequence of letters or digits
5243 @end ifclear
5244 indicating the particular style
5245 checks to be performed. The following checks are defined:
5247 @table @option
5248 @c !sort!
5249 @item 1-9
5250 @emph{Specify indentation level.}
5251 If a digit from 1-9 appears
5252 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5253 then proper indentation is checked, with the digit indicating the
5254 indentation level required.
5255 The general style of required indentation is as specified by
5256 the examples in the Ada Reference Manual. Full line comments must be
5257 aligned with the @code{--} starting on a column that is a multiple of
5258 the alignment level.
5260 @item ^a^ATTRIBUTE^
5261 @emph{Check attribute casing.}
5262 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5263 then attribute names, including the case of keywords such as @code{digits}
5264 used as attributes names, must be written in mixed case, that is, the
5265 initial letter and any letter following an underscore must be uppercase.
5266 All other letters must be lowercase.
5268 @item ^b^BLANKS^
5269 @emph{Blanks not allowed at statement end.}
5270 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5271 trailing blanks are not allowed at the end of statements. The purpose of this
5272 rule, together with h (no horizontal tabs), is to enforce a canonical format
5273 for the use of blanks to separate source tokens.
5275 @item ^c^COMMENTS^
5276 @emph{Check comments.}
5277 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5278 then comments must meet the following set of rules:
5280 @itemize @bullet
5282 @item
5283 The ``@code{--}'' that starts the column must either start in column one,
5284 or else at least one blank must precede this sequence.
5286 @item
5287 Comments that follow other tokens on a line must have at least one blank
5288 following the ``@code{--}'' at the start of the comment.
5290 @item
5291 Full line comments must have two blanks following the ``@code{--}'' that
5292 starts the comment, with the following exceptions.
5294 @item
5295 A line consisting only of the ``@code{--}'' characters, possibly preceded
5296 by blanks is permitted.
5298 @item
5299 A comment starting with ``@code{--x}'' where @code{x} is a special character
5300 is permitted.
5301 This allows proper processing of the output generated by specialized tools
5302 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5303 annotation
5304 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5305 special character is defined as being in one of the ASCII ranges
5306 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5307 Note that this usage is not permitted
5308 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5310 @item
5311 A line consisting entirely of minus signs, possibly preceded by blanks, is
5312 permitted. This allows the construction of box comments where lines of minus
5313 signs are used to form the top and bottom of the box.
5315 @item
5316 If a comment starts and ends with ``@code{--}'' is permitted as long as at
5317 least one blank follows the initial ``@code{--}''. Together with the preceding
5318 rule, this allows the construction of box comments, as shown in the following
5319 example:
5320 @smallexample
5321 ---------------------------
5322 -- This is a box comment --
5323 -- with two text lines.  --
5324 ---------------------------
5325 @end smallexample
5326 @end itemize
5328 @item ^e^END^
5329 @emph{Check end/exit labels.}
5330 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5331 optional labels on @code{end} statements ending subprograms and on
5332 @code{exit} statements exiting named loops, are required to be present.
5334 @item ^f^VTABS^
5335 @emph{No form feeds or vertical tabs.}
5336 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5337 neither form feeds nor vertical tab characters are not permitted
5338 in the source text.
5340 @item ^h^HTABS^
5341 @emph{No horizontal tabs.}
5342 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5343 horizontal tab characters are not permitted in the source text.
5344 Together with the b (no blanks at end of line) check, this
5345 enforces a canonical form for the use of blanks to separate
5346 source tokens.
5348 @item ^i^IF_THEN^
5349 @emph{Check if-then layout.}
5350 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5351 then the keyword @code{then} must appear either on the same
5352 line as corresponding @code{if}, or on a line on its own, lined
5353 up under the @code{if} with at least one non-blank line in between
5354 containing all or part of the condition to be tested.
5356 @item ^k^KEYWORD^
5357 @emph{Check keyword casing.}
5358 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5359 all keywords must be in lower case (with the exception of keywords
5360 such as @code{digits} used as attribute names to which this check
5361 does not apply).
5363 @item ^l^LAYOUT^
5364 @emph{Check layout.}
5365 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5366 layout of statement and declaration constructs must follow the
5367 recommendations in the Ada Reference Manual, as indicated by the
5368 form of the syntax rules. For example an @code{else} keyword must
5369 be lined up with the corresponding @code{if} keyword.
5371 There are two respects in which the style rule enforced by this check
5372 option are more liberal than those in the Ada Reference Manual. First
5373 in the case of record declarations, it is permissible to put the
5374 @code{record} keyword on the same line as the @code{type} keyword, and
5375 then the @code{end} in @code{end record} must line up under @code{type}.
5376 For example, either of the following two layouts is acceptable:
5378 @smallexample @c ada
5379 @cartouche
5380 type q is record
5381    a : integer;
5382    b : integer;
5383 end record;
5385 type q is
5386    record
5387       a : integer;
5388       b : integer;
5389    end record;
5390 @end cartouche
5391 @end smallexample
5393 @noindent
5394 Second, in the case of a block statement, a permitted alternative
5395 is to put the block label on the same line as the @code{declare} or
5396 @code{begin} keyword, and then line the @code{end} keyword up under
5397 the block label. For example both the following are permitted:
5399 @smallexample @c ada
5400 @cartouche
5401 Block : declare
5402    A : Integer := 3;
5403 begin
5404    Proc (A, A);
5405 end Block;
5407 Block :
5408    declare
5409       A : Integer := 3;
5410    begin
5411       Proc (A, A);
5412    end Block;
5413 @end cartouche
5414 @end smallexample
5416 @noindent
5417 The same alternative format is allowed for loops. For example, both of
5418 the following are permitted:
5420 @smallexample @c ada
5421 @cartouche
5422 Clear : while J < 10 loop
5423    A (J) := 0;
5424 end loop Clear;
5426 Clear :
5427    while J < 10 loop
5428       A (J) := 0;
5429    end loop Clear;
5430 @end cartouche
5431 @end smallexample
5433 @item ^Lnnn^MAX_NESTING=nnn^
5434 @emph{Set maximum nesting level}
5435 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5436 the range 0-999, appears in the string after @option{-gnaty} then the
5437 maximum level of nesting of constructs (including subprograms, loops,
5438 blocks, packages, and conditionals) may not exceed the given value. A
5439 value of zero disconnects this style check.
5441 @item ^m^LINE_LENGTH^
5442 @emph{Check maximum line length.}
5443 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5444 then the length of source lines must not exceed 79 characters, including
5445 any trailing blanks. The value of 79 allows convenient display on an
5446 80 character wide device or window, allowing for possible special
5447 treatment of 80 character lines. Note that this count is of raw
5448 characters in the source text. This means that a tab character counts
5449 as one character in this count and a wide character sequence counts as
5450 several characters (however many are needed in the encoding).
5452 @item ^Mnnn^MAX_LENGTH=nnn^
5453 @emph{Set maximum line length.}
5454 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5455 the string after @option{-gnaty} then the length of lines must not exceed the
5456 given value.
5458 @item ^n^STANDARD_CASING^
5459 @emph{Check casing of entities in Standard.}
5460 If the ^letter n^word STANDARD_CASING^ appears in the string
5461 after @option{-gnaty} then any identifier from Standard must be cased
5462 to match the presentation in the Ada Reference Manual (for example,
5463 @code{Integer} and @code{ASCII.NUL}).
5465 @item ^o^ORDERED_SUBPROGRAMS^
5466 @emph{Check order of subprogram bodies.}
5467 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5468 after @option{-gnaty} then all subprogram bodies in a given scope
5469 (e.g. a package body) must be in alphabetical order. The ordering
5470 rule uses normal Ada rules for comparing strings, ignoring casing
5471 of letters, except that if there is a trailing numeric suffix, then
5472 the value of this suffix is used in the ordering (e.g. Junk2 comes
5473 before Junk10).
5475 @item ^p^PRAGMA^
5476 @emph{Check pragma casing.}
5477 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5478 pragma names must be written in mixed case, that is, the
5479 initial letter and any letter following an underscore must be uppercase.
5480 All other letters must be lowercase.
5482 @item ^r^REFERENCES^
5483 @emph{Check references.}
5484 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5485 then all identifier references must be cased in the same way as the
5486 corresponding declaration. No specific casing style is imposed on
5487 identifiers. The only requirement is for consistency of references
5488 with declarations.
5490 @item ^s^SPECS^
5491 @emph{Check separate specs.}
5492 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5493 separate declarations (``specs'') are required for subprograms (a
5494 body is not allowed to serve as its own declaration). The only
5495 exception is that parameterless library level procedures are
5496 not required to have a separate declaration. This exception covers
5497 the most frequent form of main program procedures.
5499 @item ^t^TOKEN^
5500 @emph{Check token spacing.}
5501 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5502 the following token spacing rules are enforced:
5504 @itemize @bullet
5506 @item
5507 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5509 @item
5510 The token @code{=>} must be surrounded by spaces.
5512 @item
5513 The token @code{<>} must be preceded by a space or a left parenthesis.
5515 @item
5516 Binary operators other than @code{**} must be surrounded by spaces.
5517 There is no restriction on the layout of the @code{**} binary operator.
5519 @item
5520 Colon must be surrounded by spaces.
5522 @item
5523 Colon-equal (assignment, initialization) must be surrounded by spaces.
5525 @item
5526 Comma must be the first non-blank character on the line, or be
5527 immediately preceded by a non-blank character, and must be followed
5528 by a space.
5530 @item
5531 If the token preceding a left parenthesis ends with a letter or digit, then
5532 a space must separate the two tokens.
5534 @item
5535 A right parenthesis must either be the first non-blank character on
5536 a line, or it must be preceded by a non-blank character.
5538 @item
5539 A semicolon must not be preceded by a space, and must not be followed by
5540 a non-blank character.
5542 @item
5543 A unary plus or minus may not be followed by a space.
5545 @item
5546 A vertical bar must be surrounded by spaces.
5547 @end itemize
5549 @noindent
5550 In the above rules, appearing in column one is always permitted, that is,
5551 counts as meeting either a requirement for a required preceding space,
5552 or as meeting a requirement for no preceding space.
5554 Appearing at the end of a line is also always permitted, that is, counts
5555 as meeting either a requirement for a following space, or as meeting
5556 a requirement for no following space.
5558 @end table
5560 @noindent
5561 If any of these style rules is violated, a message is generated giving
5562 details on the violation. The initial characters of such messages are
5563 always ``@code{(style)}''. Note that these messages are treated as warning
5564 messages, so they normally do not prevent the generation of an object
5565 file. The @option{-gnatwe} switch can be used to treat warning messages,
5566 including style messages, as fatal errors.
5568 The switch
5569 @ifclear vms
5570 @option{-gnaty} on its own (that is not
5571 followed by any letters or digits),
5572 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
5573 options enabled with the exception of -gnatyo,
5574 @end ifclear
5575 @ifset vms
5576 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5577 the exception of ORDERED_SUBPROGRAMS,
5578 @end ifset
5579 with an indentation level of 3. This is the standard
5580 checking option that is used for the GNAT sources.
5582 The switch
5583 @ifclear vms
5584 @option{-gnatyN}
5585 @end ifclear
5586 @ifset vms
5587 /STYLE_CHECKS=NONE
5588 @end ifset
5589 clears any previously set style checks.
5591 @node Run-Time Checks
5592 @subsection Run-Time Checks
5593 @cindex Division by zero
5594 @cindex Access before elaboration
5595 @cindex Checks, division by zero
5596 @cindex Checks, access before elaboration
5598 @noindent
5599 If you compile with the default options, GNAT will insert many run-time
5600 checks into the compiled code, including code that performs range
5601 checking against constraints, but not arithmetic overflow checking for
5602 integer operations (including division by zero) or checks for access
5603 before elaboration on subprogram calls. All other run-time checks, as
5604 required by the Ada 95 Reference Manual, are generated by default.
5605 The following @code{gcc} switches refine this default behavior:
5607 @table @option
5608 @c !sort!
5609 @item -gnatp
5610 @cindex @option{-gnatp} (@code{gcc})
5611 @cindex Suppressing checks
5612 @cindex Checks, suppressing
5613 @findex Suppress
5614 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5615 had been present in the source. Validity checks are also suppressed (in
5616 other words @option{-gnatp} also implies @option{-gnatVn}.
5617 Use this switch to improve the performance
5618 of the code at the expense of safety in the presence of invalid data or
5619 program bugs.
5621 @item -gnato
5622 @cindex @option{-gnato} (@code{gcc})
5623 @cindex Overflow checks
5624 @cindex Check, overflow
5625 Enables overflow checking for integer operations.
5626 This causes GNAT to generate slower and larger executable
5627 programs by adding code to check for overflow (resulting in raising
5628 @code{Constraint_Error} as required by standard Ada
5629 semantics). These overflow checks correspond to situations in which
5630 the true value of the result of an operation may be outside the base
5631 range of the result type. The following example shows the distinction:
5633 @smallexample @c ada
5634 X1 : Integer := Integer'Last;
5635 X2 : Integer range 1 .. 5 := 5;
5636 X3 : Integer := Integer'Last;
5637 X4 : Integer range 1 .. 5 := 5;
5638 F  : Float := 2.0E+20;
5640 X1 := X1 + 1;
5641 X2 := X2 + 1;
5642 X3 := Integer (F);
5643 X4 := Integer (F);
5644 @end smallexample
5646 @noindent
5647 Here the first addition results in a value that is outside the base range
5648 of Integer, and hence requires an overflow check for detection of the
5649 constraint error. Thus the first assignment to @code{X1} raises a
5650 @code{Constraint_Error} exception only if @option{-gnato} is set.
5652 The second increment operation results in a violation
5653 of the explicit range constraint, and such range checks are always
5654 performed (unless specifically suppressed with a pragma @code{suppress}
5655 or the use of @option{-gnatp}).
5657 The two conversions of @code{F} both result in values that are outside
5658 the base range of type @code{Integer} and thus will raise
5659 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5660 The fact that the result of the second conversion is assigned to
5661 variable @code{X4} with a restricted range is irrelevant, since the problem
5662 is in the conversion, not the assignment.
5664 Basically the rule is that in the default mode (@option{-gnato} not
5665 used), the generated code assures that all integer variables stay
5666 within their declared ranges, or within the base range if there is
5667 no declared range. This prevents any serious problems like indexes
5668 out of range for array operations.
5670 What is not checked in default mode is an overflow that results in
5671 an in-range, but incorrect value. In the above example, the assignments
5672 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5673 range of the target variable, but the result is wrong in the sense that
5674 it is too large to be represented correctly. Typically the assignment
5675 to @code{X1} will result in wrap around to the largest negative number.
5676 The conversions of @code{F} will result in some @code{Integer} value
5677 and if that integer value is out of the @code{X4} range then the
5678 subsequent assignment would generate an exception.
5680 @findex Machine_Overflows
5681 Note that the @option{-gnato} switch does not affect the code generated
5682 for any floating-point operations; it applies only to integer
5683 semantics).
5684 For floating-point, GNAT has the @code{Machine_Overflows}
5685 attribute set to @code{False} and the normal mode of operation is to
5686 generate IEEE NaN and infinite values on overflow or invalid operations
5687 (such as dividing 0.0 by 0.0).
5689 The reason that we distinguish overflow checking from other kinds of
5690 range constraint checking is that a failure of an overflow check can
5691 generate an incorrect value, but cannot cause erroneous behavior. This
5692 is unlike the situation with a constraint check on an array subscript,
5693 where failure to perform the check can result in random memory description,
5694 or the range check on a case statement, where failure to perform the check
5695 can cause a wild jump.
5697 Note again that @option{-gnato} is off by default, so overflow checking is
5698 not performed in default mode. This means that out of the box, with the
5699 default settings, GNAT does not do all the checks expected from the
5700 language description in the Ada Reference Manual. If you want all constraint
5701 checks to be performed, as described in this Manual, then you must
5702 explicitly use the -gnato switch either on the @code{gnatmake} or
5703 @code{gcc} command.
5705 @item -gnatE
5706 @cindex @option{-gnatE} (@code{gcc})
5707 @cindex Elaboration checks
5708 @cindex Check, elaboration
5709 Enables dynamic checks for access-before-elaboration
5710 on subprogram calls and generic instantiations.
5711 For full details of the effect and use of this switch,
5712 @xref{Compiling Using gcc}.
5713 @end table
5715 @findex Unsuppress
5716 @noindent
5717 The setting of these switches only controls the default setting of the
5718 checks. You may modify them using either @code{Suppress} (to remove
5719 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5720 the program source.
5722 @node Stack Overflow Checking
5723 @subsection Stack Overflow Checking
5724 @cindex Stack Overflow Checking
5725 @cindex -fstack-check
5727 @noindent
5728 For most operating systems, @code{gcc} does not perform stack overflow
5729 checking by default. This means that if the main environment task or
5730 some other task exceeds the available stack space, then unpredictable
5731 behavior will occur.
5733 To activate stack checking, compile all units with the gcc option
5734 @option{-fstack-check}. For example:
5736 @smallexample
5737 gcc -c -fstack-check package1.adb
5738 @end smallexample
5740 @noindent
5741 Units compiled with this option will generate extra instructions to check
5742 that any use of the stack (for procedure calls or for declaring local
5743 variables in declare blocks) do not exceed the available stack space.
5744 If the space is exceeded, then a @code{Storage_Error} exception is raised.
5746 For declared tasks, the stack size is always controlled by the size
5747 given in an applicable @code{Storage_Size} pragma (or is set to
5748 the default size if no pragma is used.
5750 For the environment task, the stack size depends on
5751 system defaults and is unknown to the compiler. The stack
5752 may even dynamically grow on some systems, precluding the
5753 normal Ada semantics for stack overflow. In the worst case,
5754 unbounded stack usage, causes unbounded stack expansion
5755 resulting in the system running out of virtual memory.
5757 The stack checking may still work correctly if a fixed
5758 size stack is allocated, but this cannot be guaranteed.
5759 To ensure that a clean exception is signalled for stack
5760 overflow, set the environment variable
5761 @code{GNAT_STACK_LIMIT} to indicate the maximum
5762 stack area that can be used, as in:
5763 @cindex GNAT_STACK_LIMIT
5765 @smallexample
5766 SET GNAT_STACK_LIMIT 1600
5767 @end smallexample
5769 @noindent
5770 The limit is given in kilobytes, so the above declaration would
5771 set the stack limit of the environment task to 1.6 megabytes.
5772 Note that the only purpose of this usage is to limit the amount
5773 of stack used by the environment task. If it is necessary to
5774 increase the amount of stack for the environment task, then this
5775 is an operating systems issue, and must be addressed with the
5776 appropriate operating systems commands.
5779 @node Using gcc for Syntax Checking
5780 @subsection Using @code{gcc} for Syntax Checking
5781 @table @option
5782 @item -gnats
5783 @cindex @option{-gnats} (@code{gcc})
5784 @ifclear vms
5786 @noindent
5787 The @code{s} stands for ``syntax''.
5788 @end ifclear
5790 Run GNAT in syntax checking only mode. For
5791 example, the command
5793 @smallexample
5794 $ gcc -c -gnats x.adb
5795 @end smallexample
5797 @noindent
5798 compiles file @file{x.adb} in syntax-check-only mode. You can check a
5799 series of files in a single command
5800 @ifclear vms
5801 , and can use wild cards to specify such a group of files.
5802 Note that you must specify the @option{-c} (compile
5803 only) flag in addition to the @option{-gnats} flag.
5804 @end ifclear
5806 You may use other switches in conjunction with @option{-gnats}. In
5807 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5808 format of any generated error messages.
5810 When the source file is empty or contains only empty lines and/or comments,
5811 the output is a warning:
5813 @smallexample
5814 $ gcc -c -gnats -x ada toto.txt
5815 toto.txt:1:01: warning: empty file, contains no compilation units
5817 @end smallexample
5819 Otherwise, the output is simply the error messages, if any. No object file or
5820 ALI file is generated by a syntax-only compilation. Also, no units other
5821 than the one specified are accessed. For example, if a unit @code{X}
5822 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5823 check only mode does not access the source file containing unit
5824 @code{Y}.
5826 @cindex Multiple units, syntax checking
5827 Normally, GNAT allows only a single unit in a source file. However, this
5828 restriction does not apply in syntax-check-only mode, and it is possible
5829 to check a file containing multiple compilation units concatenated
5830 together. This is primarily used by the @code{gnatchop} utility
5831 (@pxref{Renaming Files Using gnatchop}).
5832 @end table
5835 @node Using gcc for Semantic Checking
5836 @subsection Using @code{gcc} for Semantic Checking
5837 @table @option
5838 @item -gnatc
5839 @cindex @option{-gnatc} (@code{gcc})
5841 @ifclear vms
5842 @noindent
5843 The @code{c} stands for ``check''.
5844 @end ifclear
5845 Causes the compiler to operate in semantic check mode,
5846 with full checking for all illegalities specified in the
5847 Ada 95 Reference Manual, but without generation of any object code
5848 (no object file is generated).
5850 Because dependent files must be accessed, you must follow the GNAT
5851 semantic restrictions on file structuring to operate in this mode:
5853 @itemize @bullet
5854 @item
5855 The needed source files must be accessible
5856 (@pxref{Search Paths and the Run-Time Library (RTL)}).
5858 @item
5859 Each file must contain only one compilation unit.
5861 @item
5862 The file name and unit name must match (@pxref{File Naming Rules}).
5863 @end itemize
5865 The output consists of error messages as appropriate. No object file is
5866 generated. An @file{ALI} file is generated for use in the context of
5867 cross-reference tools, but this file is marked as not being suitable
5868 for binding (since no object file is generated).
5869 The checking corresponds exactly to the notion of
5870 legality in the Ada 95 Reference Manual.
5872 Any unit can be compiled in semantics-checking-only mode, including
5873 units that would not normally be compiled (subunits,
5874 and specifications where a separate body is present).
5875 @end table
5877 @node Compiling Ada 83 Programs
5878 @subsection Compiling Ada 83 Programs
5879 @table @option
5880 @cindex Ada 83 compatibility
5881 @item -gnat83
5882 @cindex @option{-gnat83} (@code{gcc})
5883 @cindex ACVC, Ada 83 tests
5885 @noindent
5886 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
5887 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
5888 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
5889 where this can be done easily.
5890 It is not possible to guarantee this switch does a perfect
5891 job; for example, some subtle tests, such as are
5892 found in earlier ACVC tests (and that have been removed from the ACATS suite
5893 for Ada 95), might not compile correctly.
5894 Nevertheless, this switch may be useful in some circumstances, for example
5895 where, due to contractual reasons, legacy code needs to be maintained
5896 using only Ada 83 features.
5898 With few exceptions (most notably the need to use @code{<>} on
5899 @cindex Generic formal parameters
5900 unconstrained generic formal parameters, the use of the new Ada 95
5901 reserved words, and the use of packages
5902 with optional bodies), it is not necessary to use the
5903 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
5904 exceptions, Ada 95 is upwardly compatible with Ada 83. This
5905 means that a correct Ada 83 program is usually also a correct Ada 95
5906 program.
5907 For further information, please refer to @ref{Compatibility and Porting Guide}.
5909 @end table
5911 @node Character Set Control
5912 @subsection Character Set Control
5913 @table @option
5914 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
5915 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
5917 @noindent
5918 Normally GNAT recognizes the Latin-1 character set in source program
5919 identifiers, as described in the Ada 95 Reference Manual.
5920 This switch causes
5921 GNAT to recognize alternate character sets in identifiers. @var{c} is a
5922 single character ^^or word^ indicating the character set, as follows:
5924 @table @code
5925 @item 1
5926 ISO 8859-1 (Latin-1) identifiers
5928 @item 2
5929 ISO 8859-2 (Latin-2) letters allowed in identifiers
5931 @item 3
5932 ISO 8859-3 (Latin-3) letters allowed in identifiers
5934 @item 4
5935 ISO 8859-4 (Latin-4) letters allowed in identifiers
5937 @item 5
5938 ISO 8859-5 (Cyrillic) letters allowed in identifiers
5940 @item 9
5941 ISO 8859-15 (Latin-9) letters allowed in identifiers
5943 @item ^p^PC^
5944 IBM PC letters (code page 437) allowed in identifiers
5946 @item ^8^PC850^
5947 IBM PC letters (code page 850) allowed in identifiers
5949 @item ^f^FULL_UPPER^
5950 Full upper-half codes allowed in identifiers
5952 @item ^n^NO_UPPER^
5953 No upper-half codes allowed in identifiers
5955 @item ^w^WIDE^
5956 Wide-character codes (that is, codes greater than 255)
5957 allowed in identifiers
5958 @end table
5960 @xref{Foreign Language Representation}, for full details on the
5961 implementation of these character sets.
5963 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
5964 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
5965 Specify the method of encoding for wide characters.
5966 @var{e} is one of the following:
5968 @table @code
5970 @item ^h^HEX^
5971 Hex encoding (brackets coding also recognized)
5973 @item ^u^UPPER^
5974 Upper half encoding (brackets encoding also recognized)
5976 @item ^s^SHIFT_JIS^
5977 Shift/JIS encoding (brackets encoding also recognized)
5979 @item ^e^EUC^
5980 EUC encoding (brackets encoding also recognized)
5982 @item ^8^UTF8^
5983 UTF-8 encoding (brackets encoding also recognized)
5985 @item ^b^BRACKETS^
5986 Brackets encoding only (default value)
5987 @end table
5988 For full details on the these encoding
5989 methods see @xref{Wide Character Encodings}.
5990 Note that brackets coding is always accepted, even if one of the other
5991 options is specified, so for example @option{-gnatW8} specifies that both
5992 brackets and @code{UTF-8} encodings will be recognized. The units that are
5993 with'ed directly or indirectly will be scanned using the specified
5994 representation scheme, and so if one of the non-brackets scheme is
5995 used, it must be used consistently throughout the program. However,
5996 since brackets encoding is always recognized, it may be conveniently
5997 used in standard libraries, allowing these libraries to be used with
5998 any of the available coding schemes.
5999 scheme. If no @option{-gnatW?} parameter is present, then the default
6000 representation is Brackets encoding only.
6002 Note that the wide character representation that is specified (explicitly
6003 or by default) for the main program also acts as the default encoding used
6004 for Wide_Text_IO files if not specifically overridden by a WCEM form
6005 parameter.
6007 @end table
6008 @node File Naming Control
6009 @subsection File Naming Control
6011 @table @option
6012 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6013 @cindex @option{-gnatk} (@code{gcc})
6014 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6015 1-999, indicates the maximum allowable length of a file name (not
6016 including the @file{.ads} or @file{.adb} extension). The default is not
6017 to enable file name krunching.
6019 For the source file naming rules, @xref{File Naming Rules}.
6020 @end table
6023 @node Subprogram Inlining Control
6024 @subsection Subprogram Inlining Control
6026 @table @option
6027 @c !sort!
6028 @item -gnatn
6029 @cindex @option{-gnatn} (@code{gcc})
6030 @ifclear vms
6031 The @code{n} here is intended to suggest the first syllable of the
6032 word ``inline''.
6033 @end ifclear
6034 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6035 inlining to actually occur, optimization must be enabled. To enable
6036 inlining of subprograms specified by pragma @code{Inline},
6037 you must also specify this switch.
6038 In the absence of this switch, GNAT does not attempt
6039 inlining and does not need to access the bodies of
6040 subprograms for which @code{pragma Inline} is specified if they are not
6041 in the current unit.
6043 If you specify this switch the compiler will access these bodies,
6044 creating an extra source dependency for the resulting object file, and
6045 where possible, the call will be inlined.
6046 For further details on when inlining is possible
6047 see @xref{Inlining of Subprograms}.
6049 @item -gnatN
6050 @cindex @option{-gnatN} (@code{gcc})
6051 The front end inlining activated by this switch is generally more extensive,
6052 and quite often more effective than the standard @option{-gnatn} inlining mode.
6053 It will also generate additional dependencies.
6054 Note that
6055 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6056 to specify both options.
6057 @end table
6059 @node Auxiliary Output Control
6060 @subsection Auxiliary Output Control
6062 @table @option
6063 @item -gnatt
6064 @cindex @option{-gnatt} (@code{gcc})
6065 @cindex Writing internal trees
6066 @cindex Internal trees, writing to file
6067 Causes GNAT to write the internal tree for a unit to a file (with the
6068 extension @file{.adt}.
6069 This not normally required, but is used by separate analysis tools.
6070 Typically
6071 these tools do the necessary compilations automatically, so you should
6072 not have to specify this switch in normal operation.
6074 @item -gnatu
6075 @cindex @option{-gnatu} (@code{gcc})
6076 Print a list of units required by this compilation on @file{stdout}.
6077 The listing includes all units on which the unit being compiled depends
6078 either directly or indirectly.
6080 @ifclear vms
6081 @item -pass-exit-codes
6082 @cindex @option{-pass-exit-codes} (@code{gcc})
6083 If this switch is not used, the exit code returned by @code{gcc} when
6084 compiling multiple files indicates whether all source files have
6085 been successfully used to generate object files or not.
6087 When @option{-pass-exit-codes} is used, @code{gcc} exits with an extended
6088 exit status and allows an integrated development environment to better
6089 react to a compilation failure. Those exit status are:
6091 @table @asis
6092 @item 5
6093 There was an error in at least one source file.
6094 @item 3
6095 At least one source file did not generate an object file.
6096 @item 2
6097 The compiler died unexpectedly (internal error for example).
6098 @item 0
6099 An object file has been generated for every source file.
6100 @end table
6101 @end ifclear
6102 @end table
6104 @node Debugging Control
6105 @subsection Debugging Control
6107 @table @option
6108 @c !sort!
6109 @cindex Debugging options
6110 @ifclear vms
6111 @item -gnatd@var{x}
6112 @cindex @option{-gnatd} (@code{gcc})
6113 Activate internal debugging switches. @var{x} is a letter or digit, or
6114 string of letters or digits, which specifies the type of debugging
6115 outputs desired. Normally these are used only for internal development
6116 or system debugging purposes. You can find full documentation for these
6117 switches in the body of the @code{Debug} unit in the compiler source
6118 file @file{debug.adb}.
6119 @end ifclear
6121 @item -gnatG
6122 @cindex @option{-gnatG} (@code{gcc})
6123 This switch causes the compiler to generate auxiliary output containing
6124 a pseudo-source listing of the generated expanded code. Like most Ada
6125 compilers, GNAT works by first transforming the high level Ada code into
6126 lower level constructs. For example, tasking operations are transformed
6127 into calls to the tasking run-time routines. A unique capability of GNAT
6128 is to list this expanded code in a form very close to normal Ada source.
6129 This is very useful in understanding the implications of various Ada
6130 usage on the efficiency of the generated code. There are many cases in
6131 Ada (e.g. the use of controlled types), where simple Ada statements can
6132 generate a lot of run-time code. By using @option{-gnatG} you can identify
6133 these cases, and consider whether it may be desirable to modify the coding
6134 approach to improve efficiency.
6136 The format of the output is very similar to standard Ada source, and is
6137 easily understood by an Ada programmer. The following special syntactic
6138 additions correspond to low level features used in the generated code that
6139 do not have any exact analogies in pure Ada source form. The following
6140 is a partial list of these special constructions. See the specification
6141 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6143 @table @code
6144 @item new @var{xxx} [storage_pool = @var{yyy}]
6145 Shows the storage pool being used for an allocator.
6147 @item at end @var{procedure-name};
6148 Shows the finalization (cleanup) procedure for a scope.
6150 @item (if @var{expr} then @var{expr} else @var{expr})
6151 Conditional expression equivalent to the @code{x?y:z} construction in C.
6153 @item @var{target}^^^(@var{source})
6154 A conversion with floating-point truncation instead of rounding.
6156 @item @var{target}?(@var{source})
6157 A conversion that bypasses normal Ada semantic checking. In particular
6158 enumeration types and fixed-point types are treated simply as integers.
6160 @item @var{target}?^^^(@var{source})
6161 Combines the above two cases.
6163 @item @var{x} #/ @var{y}
6164 @itemx @var{x} #mod @var{y}
6165 @itemx @var{x} #* @var{y}
6166 @itemx @var{x} #rem @var{y}
6167 A division or multiplication of fixed-point values which are treated as
6168 integers without any kind of scaling.
6170 @item free @var{expr} [storage_pool = @var{xxx}]
6171 Shows the storage pool associated with a @code{free} statement.
6173 @item freeze @var{typename} [@var{actions}]
6174 Shows the point at which @var{typename} is frozen, with possible
6175 associated actions to be performed at the freeze point.
6177 @item reference @var{itype}
6178 Reference (and hence definition) to internal type @var{itype}.
6180 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6181 Intrinsic function call.
6183 @item @var{labelname} : label
6184 Declaration of label @var{labelname}.
6186 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6187 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6188 @var{expr}, but handled more efficiently).
6190 @item [constraint_error]
6191 Raise the @code{Constraint_Error} exception.
6193 @item @var{expression}'reference
6194 A pointer to the result of evaluating @var{expression}.
6196 @item @var{target-type}!(@var{source-expression})
6197 An unchecked conversion of @var{source-expression} to @var{target-type}.
6199 @item [@var{numerator}/@var{denominator}]
6200 Used to represent internal real literals (that) have no exact
6201 representation in base 2-16 (for example, the result of compile time
6202 evaluation of the expression 1.0/27.0).
6203 @end table
6205 @item -gnatD
6206 @cindex @option{-gnatD} (@code{gcc})
6207 When used in conjunction with @option{-gnatG}, this switch causes
6208 the expanded source, as described above for
6209 @option{-gnatG} to be written to files with names
6210 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6211 instead of to the standard ooutput file. For
6212 example, if the source file name is @file{hello.adb}, then a file
6213 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6214 information generated by the @code{gcc} @option{^-g^/DEBUG^} switch
6215 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6216 you to do source level debugging using the generated code which is
6217 sometimes useful for complex code, for example to find out exactly
6218 which part of a complex construction raised an exception. This switch
6219 also suppress generation of cross-reference information (see
6220 @option{-gnatx}) since otherwise the cross-reference information
6221 would refer to the @file{^.dg^.DG^} file, which would cause
6222 confusion since this is not the original source file.
6224 Note that @option{-gnatD} actually implies @option{-gnatG}
6225 automatically, so it is not necessary to give both options.
6226 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6228 @ifclear vms
6229 @item -gnatR[0|1|2|3[s]]
6230 @cindex @option{-gnatR} (@code{gcc})
6231 This switch controls output from the compiler of a listing showing
6232 representation information for declared types and objects. For
6233 @option{-gnatR0}, no information is output (equivalent to omitting
6234 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6235 so @option{-gnatR} with no parameter has the same effect), size and alignment
6236 information is listed for declared array and record types. For
6237 @option{-gnatR2}, size and alignment information is listed for all
6238 expression information for values that are computed at run time for
6239 variant records. These symbolic expressions have a mostly obvious
6240 format with #n being used to represent the value of the n'th
6241 discriminant. See source files @file{repinfo.ads/adb} in the
6242 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6243 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6244 the output is to a file with the name @file{^file.rep^file_REP^} where
6245 file is the name of the corresponding source file.
6246 @end ifclear
6247 @ifset vms
6248 @item /REPRESENTATION_INFO
6249 @cindex @option{/REPRESENTATION_INFO} (@code{gcc})
6250 This qualifier controls output from the compiler of a listing showing
6251 representation information for declared types and objects. For
6252 @option{/REPRESENTATION_INFO=NONE}, no information is output
6253 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6254 @option{/REPRESENTATION_INFO} without option is equivalent to
6255 @option{/REPRESENTATION_INFO=ARRAYS}.
6256 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6257 information is listed for declared array and record types. For
6258 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6259 is listed for all expression information for values that are computed
6260 at run time for variant records. These symbolic expressions have a mostly
6261 obvious format with #n being used to represent the value of the n'th
6262 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6263 @code{GNAT} sources for full details on the format of
6264 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6265 If _FILE is added at the end of an option
6266 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6267 then the output is to a file with the name @file{file_REP} where
6268 file is the name of the corresponding source file.
6269 @end ifset
6271 @item -gnatS
6272 @cindex @option{-gnatS} (@code{gcc})
6273 The use of the switch @option{-gnatS} for an
6274 Ada compilation will cause the compiler to output a
6275 representation of package Standard in a form very
6276 close to standard Ada. It is not quite possible to
6277 do this entirely in standard Ada (since new
6278 numeric base types cannot be created in standard
6279 Ada), but the output is easily
6280 readable to any Ada programmer, and is useful to
6281 determine the characteristics of target dependent
6282 types in package Standard.
6284 @item -gnatx
6285 @cindex @option{-gnatx} (@code{gcc})
6286 Normally the compiler generates full cross-referencing information in
6287 the @file{ALI} file. This information is used by a number of tools,
6288 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6289 suppresses this information. This saves some space and may slightly
6290 speed up compilation, but means that these tools cannot be used.
6291 @end table
6293 @node Exception Handling Control
6294 @subsection Exception Handling Control
6296 @noindent
6297 GNAT uses two methods for handling exceptions at run-time. The
6298 @code{longjmp/setjmp} method saves the context when entering
6299 a frame with an exception handler. Then when an exception is
6300 raised, the context can be restored immediately, without the
6301 need for tracing stack frames. This method provides very fast
6302 exception propagation, but introduces significant overhead for
6303 the use of exception handlers, even if no exception is raised.
6305 The other approach is called ``zero cost'' exception handling.
6306 With this method, the compiler builds static tables to describe
6307 the exception ranges. No dynamic code is required when entering
6308 a frame containing an exception handler. When an exception is
6309 raised, the tables are used to control a back trace of the
6310 subprogram invocation stack to locate the required exception
6311 handler. This method has considerably poorer performance for
6312 the propagation of exceptions, but there is no overhead for
6313 exception handlers if no exception is raised.
6315 The following switches can be used to control which of the
6316 two exception handling methods is used.
6318 @table @option
6319 @c !sort!
6321 @item -gnatL
6322 @cindex @option{-gnatL} (@code{gcc})
6323 This switch causes the longjmp/setjmp approach to be used
6324 for exception handling. If this is the default mechanism for the
6325 target (see below), then this has no effect. If the default
6326 mechanism for the target is zero cost exceptions, then
6327 this switch can be used to modify this default, but it must be
6328 used for all units in the partition, including all run-time
6329 library units. One way to achieve this is to use the
6330 @option{-a} and @option{-f} switches for @code{gnatmake}.
6331 This option is rarely used. One case in which it may be
6332 advantageous is if you have an application where exception
6333 raising is common and the overall performance of the
6334 application is improved by favoring exception propagation.
6336 @item -gnatZ
6337 @cindex @option{-gnatZ} (@code{gcc})
6338 @cindex Zero Cost Exceptions
6339 This switch causes the zero cost approach to be sed
6340 for exception handling. If this is the default mechanism for the
6341 target (see below), then this has no effect. If the default
6342 mechanism for the target is longjmp/setjmp exceptions, then
6343 this switch can be used to modify this default, but it must be
6344 used for all units in the partition, including all run-time
6345 library units. One way to achieve this is to use the
6346 @option{-a} and @option{-f} switches for @code{gnatmake}.
6347 This option can only be used if the zero cost approach
6348 is available for the target in use (see below).
6349 @end table
6351 @noindent
6352 The @code{longjmp/setjmp} approach is available on all targets, but
6353 the @code{zero cost} approach is only available on selected targets.
6354 To determine whether zero cost exceptions can be used for a
6355 particular target, look at the private part of the file system.ads.
6356 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6357 be True to use the zero cost approach. If both of these switches
6358 are set to False, this means that zero cost exception handling
6359 is not yet available for that target. The switch
6360 @code{ZCX_By_Default} indicates the default approach. If this
6361 switch is set to True, then the @code{zero cost} approach is
6362 used by default.
6364 @node Units to Sources Mapping Files
6365 @subsection Units to Sources Mapping Files
6367 @table @option
6369 @item -gnatem^^=^@var{path}
6370 @cindex @option{-gnatem} (@code{gcc})
6371 A mapping file is a way to communicate to the compiler two mappings:
6372 from unit names to file names (without any directory information) and from
6373 file names to path names (with full directory information). These mappings
6374 are used by the compiler to short-circuit the path search.
6376 The use of mapping files is not required for correct operation of the
6377 compiler, but mapping files can improve efficiency, particularly when
6378 sources are read over a slow network connection. In normal operation,
6379 you need not be concerned with the format or use of mapping files,
6380 and the @option{-gnatem} switch is not a switch that you would use
6381 explicitly. it is intended only for use by automatic tools such as
6382 @code{gnatmake} running under the project file facility. The
6383 description here of the format of mapping files is provided
6384 for completeness and for possible use by other tools.
6386 A mapping file is a sequence of sets of three lines. In each set,
6387 the first line is the unit name, in lower case, with ``@code{%s}''
6388 appended for
6389 specifications and ``@code{%b}'' appended for bodies; the second line is the
6390 file name; and the third line is the path name.
6392 Example:
6393 @smallexample
6394    main%b
6395    main.2.ada
6396    /gnat/project1/sources/main.2.ada
6397 @end smallexample
6399 When the switch @option{-gnatem} is specified, the compiler will create
6400 in memory the two mappings from the specified file. If there is any problem
6401 (non existent file, truncated file or duplicate entries), no mapping
6402 will be created.
6404 Several @option{-gnatem} switches may be specified; however, only the last
6405 one on the command line will be taken into account.
6407 When using a project file, @code{gnatmake} create a temporary mapping file
6408 and communicates it to the compiler using this switch.
6410 @end table
6413 @node Integrated Preprocessing
6414 @subsection Integrated Preprocessing
6416 @noindent
6417 GNAT sources may be preprocessed immediately before compilation; the actual
6418 text of the source is not the text of the source file, but is derived from it
6419 through a process called preprocessing. Integrated preprocessing is specified
6420 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6421 indicates, through a text file, the preprocessing data to be used.
6422 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6424 @noindent
6425 It is recommended that @code{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6426 used when Integrated Preprocessing is used. The reason is that preprocessing
6427 with another Preprocessing Data file without changing the sources will
6428 not trigger recompilation without this switch.
6430 @noindent
6431 Note that @code{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6432 always trigger recompilation for sources that are preprocessed,
6433 because @code{gnatmake} cannot compute the checksum of the source after
6434 preprocessing.
6436 @noindent
6437 The actual preprocessing function is described in details in section
6438 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6439 preprocessing is triggered and parameterized.
6441 @table @code
6443 @item -gnatep=@var{file}
6444 @cindex @option{-gnatep} (@code{gcc})
6445 This switch indicates to the compiler the file name (without directory
6446 information) of the preprocessor data file to use. The preprocessor data file
6447 should be found in the source directories.
6449 @noindent
6450 A preprocessing data file is a text file with significant lines indicating
6451 how should be preprocessed either a specific source or all sources not
6452 mentioned in other lines. A significant line is a non empty, non comment line.
6453 Comments are similar to Ada comments.
6455 @noindent
6456 Each significant line starts with either a literal string or the character '*'.
6457 A literal string is the file name (without directory information) of the source
6458 to preprocess. A character '*' indicates the preprocessing for all the sources
6459 that are not specified explicitly on other lines (order of the lines is not
6460 significant). It is an error to have two lines with the same file name or two
6461 lines starting with the character '*'.
6463 @noindent
6464 After the file name or the character '*', another optional literal string
6465 indicating the file name of the definition file to be used for preprocessing.
6466 (see @ref{Form of Definitions File}. The definition files are found by the
6467 compiler in one of the source directories. In some cases, when compiling
6468 a source in a directory other than the current directory, if the definition
6469 file is in the current directory, it may be necessary to add the current
6470 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6471 the compiler would not find the definition file.
6473 @noindent
6474 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6475 be found. Those ^switches^switches^ are:
6477 @table @code
6479 @item -b
6480 Causes both preprocessor lines and the lines deleted by
6481 preprocessing to be replaced by blank lines, preserving the line number.
6482 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6483 it cancels the effect of @option{-c}.
6485 @item -c
6486 Causes both preprocessor lines and the lines deleted
6487 by preprocessing to be retained as comments marked
6488 with the special string ``@code{--! }''.
6490 @item -Dsymbol=value
6491 Define or redefine a symbol, associated with value. A symbol is an Ada
6492 identifier, or an Ada reserved word, with the exception of @code{if},
6493 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6494 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6495 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6496 same name defined in a definition file.
6498 @item -s
6499 Causes a sorted list of symbol names and values to be
6500 listed on the standard output file.
6502 @item -u
6503 Causes undefined symbols to be treated as having the value @code{FALSE}
6504 in the context
6505 of a preprocessor test. In the absence of this option, an undefined symbol in
6506 a @code{#if} or @code{#elsif} test will be treated as an error.
6508 @end table
6510 @noindent
6511 Examples of valid lines in a preprocessor data file:
6513 @smallexample
6514   "toto.adb"  "prep.def" -u
6515   --  preprocess "toto.adb", using definition file "prep.def",
6516   --  undefined symbol are False.
6518   * -c -DVERSION=V101
6519   --  preprocess all other sources without a definition file;
6520   --  suppressed lined are commented; symbol VERSION has the value V101.
6522   "titi.adb" "prep2.def" -s
6523   --  preprocess "titi.adb", using definition file "prep2.def";
6524   --  list all symbols with their values.
6525 @end smallexample
6527 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6528 @cindex @option{-gnateD} (@code{gcc})
6529 Define or redefine a preprocessing symbol, associated with value. If no value
6530 is given on the command line, then the value of the symbol is @code{True}.
6531 A symbol is an identifier, following normal Ada (case-insensitive)
6532 rules for its syntax, and value is any sequence (including an empty sequence)
6533 of characters from the set (letters, digits, period, underline).
6534 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6535 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6537 @noindent
6538 A symbol declared with this ^switch^switch^ on the command line replaces a
6539 symbol with the same name either in a definition file or specified with a
6540 ^switch^switch^ -D in the preprocessor data file.
6542 @noindent
6543 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6545 @end table
6547 @node Code Generation Control
6548 @subsection Code Generation Control
6550 @noindent
6552 The GCC technology provides a wide range of target dependent
6553 @option{-m} switches for controlling
6554 details of code generation with respect to different versions of
6555 architectures. This includes variations in instruction sets (e.g.
6556 different members of the power pc family), and different requirements
6557 for optimal arrangement of instructions (e.g. different members of
6558 the x86 family). The list of available @option{-m} switches may be
6559 found in the GCC documentation.
6561 Use of the these @option{-m} switches may in some cases result in improved
6562 code performance.
6564 The GNAT Pro technology is tested and qualified without any
6565 @option{-m} switches,
6566 so generally the most reliable approach is to avoid the use of these
6567 switches. However, we generally expect most of these switches to work
6568 successfully with GNAT Pro, and many customers have reported successful
6569 use of these options.
6571 Our general advice is to avoid the use of @option{-m} switches unless
6572 special needs lead to requirements in this area. In particular,
6573 there is no point in using @option{-m} switches to improve performance
6574 unless you actually see a performance improvement.
6576 @ifset vms
6577 @node Return Codes
6578 @subsection Return Codes
6579 @cindex Return Codes
6580 @cindex @option{/RETURN_CODES=VMS}
6582 @noindent
6583 On VMS, GNAT compiled programs return POSIX-style codes by default,
6584 e.g. @option{/RETURN_CODES=POSIX}.
6586 To enable VMS style return codes, GNAT LINK with the option
6587 @option{/RETURN_CODES=VMS}. For example:
6589 @smallexample
6590 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6591 @end smallexample
6593 @noindent
6594 Programs built with /RETURN_CODES=VMS are suitable to be called in
6595 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6596 are suitable for spawning with appropriate GNAT RTL routines.
6598 @end ifset
6601 @node Search Paths and the Run-Time Library (RTL)
6602 @section Search Paths and the Run-Time Library (RTL)
6604 @noindent
6605 With the GNAT source-based library system, the compiler must be able to
6606 find source files for units that are needed by the unit being compiled.
6607 Search paths are used to guide this process.
6609 The compiler compiles one source file whose name must be given
6610 explicitly on the command line. In other words, no searching is done
6611 for this file. To find all other source files that are needed (the most
6612 common being the specs of units), the compiler examines the following
6613 directories, in the following order:
6615 @enumerate
6616 @item
6617 The directory containing the source file of the main unit being compiled
6618 (the file name on the command line).
6620 @item
6621 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6622 @code{gcc} command line, in the order given.
6624 @item
6625 @findex ADA_INCLUDE_PATH
6626 Each of the directories listed in the value of the
6627 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6628 @ifclear vms
6629 Construct this value
6630 exactly as the @code{PATH} environment variable: a list of directory
6631 names separated by colons (semicolons when working with the NT version).
6632 @end ifclear
6633 @ifset vms
6634 Normally, define this value as a logical name containing a comma separated
6635 list of directory names.
6637 This variable can also be defined by means of an environment string
6638 (an argument to the DEC C exec* set of functions).
6640 Logical Name:
6641 @smallexample
6642 DEFINE ANOTHER_PATH FOO:[BAG]
6643 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6644 @end smallexample
6646 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6647 first, followed by the standard Ada 95
6648 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6649 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
6650 (Text_IO, Sequential_IO, etc)
6651 instead of the Ada95 packages. Thus, in order to get the Ada 95
6652 packages by default, ADA_INCLUDE_PATH must be redefined.
6653 @end ifset
6655 @item
6656 @findex ADA_PRJ_INCLUDE_FILE
6657 Each of the directories listed in the text file whose name is given
6658 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6660 @noindent
6661 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6662 driver when project files are used. It should not normally be set
6663 by other means.
6665 @item
6666 The content of the @file{ada_source_path} file which is part of the GNAT
6667 installation tree and is used to store standard libraries such as the
6668 GNAT Run Time Library (RTL) source files.
6669 @ifclear vms
6670 @ref{Installing the library}
6671 @end ifclear
6672 @end enumerate
6674 @noindent
6675 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6676 inhibits the use of the directory
6677 containing the source file named in the command line. You can still
6678 have this directory on your search path, but in this case it must be
6679 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6681 Specifying the switch @option{-nostdinc}
6682 inhibits the search of the default location for the GNAT Run Time
6683 Library (RTL) source files.
6685 The compiler outputs its object files and ALI files in the current
6686 working directory.
6687 @ifclear vms
6688 Caution: The object file can be redirected with the @option{-o} switch;
6689 however, @code{gcc} and @code{gnat1} have not been coordinated on this
6690 so the @file{ALI} file will not go to the right place. Therefore, you should
6691 avoid using the @option{-o} switch.
6692 @end ifclear
6694 @findex System.IO
6695 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6696 children make up the GNAT RTL, together with the simple @code{System.IO}
6697 package used in the @code{"Hello World"} example. The sources for these units
6698 are needed by the compiler and are kept together in one directory. Not
6699 all of the bodies are needed, but all of the sources are kept together
6700 anyway. In a normal installation, you need not specify these directory
6701 names when compiling or binding. Either the environment variables or
6702 the built-in defaults cause these files to be found.
6704 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6705 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6706 consisting of child units of @code{GNAT}. This is a collection of generally
6707 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6708 further details.
6710 Besides simplifying access to the RTL, a major use of search paths is
6711 in compiling sources from multiple directories. This can make
6712 development environments much more flexible.
6715 @node Order of Compilation Issues
6716 @section Order of Compilation Issues
6718 @noindent
6719 If, in our earlier example, there was a spec for the @code{hello}
6720 procedure, it would be contained in the file @file{hello.ads}; yet this
6721 file would not have to be explicitly compiled. This is the result of the
6722 model we chose to implement library management. Some of the consequences
6723 of this model are as follows:
6725 @itemize @bullet
6726 @item
6727 There is no point in compiling specs (except for package
6728 specs with no bodies) because these are compiled as needed by clients. If
6729 you attempt a useless compilation, you will receive an error message.
6730 It is also useless to compile subunits because they are compiled as needed
6731 by the parent.
6733 @item
6734 There are no order of compilation requirements: performing a
6735 compilation never obsoletes anything. The only way you can obsolete
6736 something and require recompilations is to modify one of the
6737 source files on which it depends.
6739 @item
6740 There is no library as such, apart from the ALI files
6741 (@pxref{The Ada Library Information Files}, for information on the format
6742 of these files). For now we find it convenient to create separate ALI files,
6743 but eventually the information therein may be incorporated into the object
6744 file directly.
6746 @item
6747 When you compile a unit, the source files for the specs of all units
6748 that it @code{with}'s, all its subunits, and the bodies of any generics it
6749 instantiates must be available (reachable by the search-paths mechanism
6750 described above), or you will receive a fatal error message.
6751 @end itemize
6753 @node Examples
6754 @section Examples
6756 @noindent
6757 The following are some typical Ada compilation command line examples:
6759 @table @code
6760 @item $ gcc -c xyz.adb
6761 Compile body in file @file{xyz.adb} with all default options.
6763 @ifclear vms
6764 @item $ gcc -c -O2 -gnata xyz-def.adb
6765 @end ifclear
6766 @ifset vms
6767 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6768 @end ifset
6770 Compile the child unit package in file @file{xyz-def.adb} with extensive
6771 optimizations, and pragma @code{Assert}/@code{Debug} statements
6772 enabled.
6774 @item $ gcc -c -gnatc abc-def.adb
6775 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6776 mode.
6777 @end table
6779 @node Binding Using gnatbind
6780 @chapter Binding Using @code{gnatbind}
6781 @findex gnatbind
6783 @menu
6784 * Running gnatbind::
6785 * Switches for gnatbind::
6786 * Command-Line Access::
6787 * Search Paths for gnatbind::
6788 * Examples of gnatbind Usage::
6789 @end menu
6791 @noindent
6792 This chapter describes the GNAT binder, @code{gnatbind}, which is used
6793 to bind compiled GNAT objects. The @code{gnatbind} program performs
6794 four separate functions:
6796 @enumerate
6797 @item
6798 Checks that a program is consistent, in accordance with the rules in
6799 Chapter 10 of the Ada 95 Reference Manual. In particular, error
6800 messages are generated if a program uses inconsistent versions of a
6801 given unit.
6803 @item
6804 Checks that an acceptable order of elaboration exists for the program
6805 and issues an error message if it cannot find an order of elaboration
6806 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6808 @item
6809 Generates a main program incorporating the given elaboration order.
6810 This program is a small Ada package (body and spec) that
6811 must be subsequently compiled
6812 using the GNAT compiler. The necessary compilation step is usually
6813 performed automatically by @code{gnatlink}. The two most important
6814 functions of this program
6815 are to call the elaboration routines of units in an appropriate order
6816 and to call the main program.
6818 @item
6819 Determines the set of object files required by the given main program.
6820 This information is output in the forms of comments in the generated program,
6821 to be read by the @code{gnatlink} utility used to link the Ada application.
6822 @end enumerate
6825 @node Running gnatbind
6826 @section Running @code{gnatbind}
6828 @noindent
6829 The form of the @code{gnatbind} command is
6831 @smallexample
6832 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
6833 @end smallexample
6835 @noindent
6836 where @file{@i{mainprog}.adb} is the Ada file containing the main program
6837 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
6838 package in two files whose names are
6839 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
6840 For example, if given the
6841 parameter @file{hello.ali}, for a main program contained in file
6842 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
6843 and @file{b~hello.adb}.
6845 When doing consistency checking, the binder takes into consideration
6846 any source files it can locate. For example, if the binder determines
6847 that the given main program requires the package @code{Pack}, whose
6848 @file{.ALI}
6849 file is @file{pack.ali} and whose corresponding source spec file is
6850 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
6851 (using the same search path conventions as previously described for the
6852 @code{gcc} command). If it can locate this source file, it checks that
6853 the time stamps
6854 or source checksums of the source and its references to in @file{ALI} files
6855 match. In other words, any @file{ALI} files that mentions this spec must have
6856 resulted from compiling this version of the source file (or in the case
6857 where the source checksums match, a version close enough that the
6858 difference does not matter).
6860 @cindex Source files, use by binder
6861 The effect of this consistency checking, which includes source files, is
6862 that the binder ensures that the program is consistent with the latest
6863 version of the source files that can be located at bind time. Editing a
6864 source file without compiling files that depend on the source file cause
6865 error messages to be generated by the binder.
6867 For example, suppose you have a main program @file{hello.adb} and a
6868 package @code{P}, from file @file{p.ads} and you perform the following
6869 steps:
6871 @enumerate
6872 @item
6873 Enter @code{gcc -c hello.adb} to compile the main program.
6875 @item
6876 Enter @code{gcc -c p.ads} to compile package @code{P}.
6878 @item
6879 Edit file @file{p.ads}.
6881 @item
6882 Enter @code{gnatbind hello}.
6883 @end enumerate
6885 @noindent
6886 At this point, the file @file{p.ali} contains an out-of-date time stamp
6887 because the file @file{p.ads} has been edited. The attempt at binding
6888 fails, and the binder generates the following error messages:
6890 @smallexample
6891 error: "hello.adb" must be recompiled ("p.ads" has been modified)
6892 error: "p.ads" has been modified and must be recompiled
6893 @end smallexample
6895 @noindent
6896 Now both files must be recompiled as indicated, and then the bind can
6897 succeed, generating a main program. You need not normally be concerned
6898 with the contents of this file, but for reference purposes a sample
6899 binder output file is given in @ref{Example of Binder Output File}.
6901 In most normal usage, the default mode of @command{gnatbind} which is to
6902 generate the main package in Ada, as described in the previous section.
6903 In particular, this means that any Ada programmer can read and understand
6904 the generated main program. It can also be debugged just like any other
6905 Ada code provided the @option{^-g^/DEBUG^} switch is used for
6906 @command{gnatbind} and @command{gnatlink}.
6908 However for some purposes it may be convenient to generate the main
6909 program in C rather than Ada. This may for example be helpful when you
6910 are generating a mixed language program with the main program in C. The
6911 GNAT compiler itself is an example.
6912 The use of the @option{^-C^/BIND_FILE=C^} switch
6913 for both @code{gnatbind} and @code{gnatlink} will cause the program to
6914 be generated in C (and compiled using the gnu C compiler).
6917 @node Switches for gnatbind
6918 @section Switches for @command{gnatbind}
6920 @noindent
6921 The following switches are available with @code{gnatbind}; details will
6922 be presented in subsequent sections.
6924 @menu
6925 * Consistency-Checking Modes::
6926 * Binder Error Message Control::
6927 * Elaboration Control::
6928 * Output Control::
6929 * Binding with Non-Ada Main Programs::
6930 * Binding Programs with No Main Subprogram::
6931 @end menu
6933 @table @option
6934 @c !sort!
6935 @item ^-aO^/OBJECT_SEARCH^
6936 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
6937 Specify directory to be searched for ALI files.
6939 @item ^-aI^/SOURCE_SEARCH^
6940 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
6941 Specify directory to be searched for source file.
6943 @item ^-A^/BIND_FILE=ADA^
6944 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
6945 Generate binder program in Ada (default)
6947 @item ^-b^/REPORT_ERRORS=BRIEF^
6948 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
6949 Generate brief messages to @file{stderr} even if verbose mode set.
6951 @item ^-c^/NOOUTPUT^
6952 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
6953 Check only, no generation of binder output file.
6955 @item ^-C^/BIND_FILE=C^
6956 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
6957 Generate binder program in C
6959 @item ^-e^/ELABORATION_DEPENDENCIES^
6960 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
6961 Output complete list of elaboration-order dependencies.
6963 @item ^-E^/STORE_TRACEBACKS^
6964 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
6965 Store tracebacks in exception occurrences when the target supports it.
6966 This is the default with the zero cost exception mechanism.
6967 @ignore
6968 @c The following may get moved to an appendix
6969 This option is currently supported on the following targets:
6970 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6971 @end ignore
6972 See also the packages @code{GNAT.Traceback} and
6973 @code{GNAT.Traceback.Symbolic} for more information.
6974 @ifclear vms
6975 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
6976 @code{gcc} option.
6977 @end ifclear
6979 @item ^-F^/FORCE_ELABS_FLAGS^
6980 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
6981 Force the checks of elaboration flags. @command{gnatbind} does not normally
6982 generate checks of elaboration flags for the main executable, except when
6983 a Stand-Alone Library is used. However, there are cases when this cannot be
6984 detected by gnatbind. An example is importing an interface of a Stand-Alone
6985 Library through a pragma Import and only specifying through a linker switch
6986 this Stand-Alone Library. This switch is used to guarantee that elaboration
6987 flag checks are generated.
6989 @item ^-h^/HELP^
6990 @cindex @option{^-h^/HELP^} (@command{gnatbind})
6991 Output usage (help) information
6993 @item ^-I^/SEARCH^
6994 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
6995 Specify directory to be searched for source and ALI files.
6997 @item ^-I-^/NOCURRENT_DIRECTORY^
6998 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
6999 Do not look for sources in the current directory where @code{gnatbind} was
7000 invoked, and do not look for ALI files in the directory containing the
7001 ALI file named in the @code{gnatbind} command line.
7003 @item ^-l^/ORDER_OF_ELABORATION^
7004 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7005 Output chosen elaboration order.
7007 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7008 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7009 Binds the units for library building. In this case the adainit and
7010 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
7011 are renamed to ^xxxinit^XXXINIT^ and
7012 ^xxxfinal^XXXFINAL^.
7013 Implies ^-n^/NOCOMPILE^.
7014 @ifclear vms
7015 (@pxref{GNAT and Libraries}, for more details.)
7016 @end ifclear
7017 @ifset vms
7018 On OpenVMS, these init and final procedures are exported in uppercase
7019 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7020 the init procedure will be "TOTOINIT" and the exported name of the final
7021 procedure will be "TOTOFINAL".
7022 @end ifset
7024 @item ^-Mxyz^/RENAME_MAIN=xyz^
7025 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7026 Rename generated main program from main to xyz
7028 @item ^-m^/ERROR_LIMIT=^@var{n}
7029 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7030 Limit number of detected errors to @var{n}, where @var{n} is
7031 in the range 1..999_999. The default value if no switch is
7032 given is 9999. Binding is terminated if the limit is exceeded.
7033 @ifset unw
7034 Furthermore, under Windows, the sources pointed to by the libraries path
7035 set in the registry are not searched for.
7036 @end ifset
7038 @item ^-n^/NOMAIN^
7039 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7040 No main program.
7042 @item -nostdinc
7043 @cindex @option{-nostdinc} (@command{gnatbind})
7044 Do not look for sources in the system default directory.
7046 @item -nostdlib
7047 @cindex @option{-nostdlib} (@command{gnatbind})
7048 Do not look for library files in the system default directory.
7050 @item --RTS=@var{rts-path}
7051 @cindex @option{--RTS} (@code{gnatbind})
7052 Specifies the default location of the runtime library. Same meaning as the
7053 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
7055 @item ^-o ^/OUTPUT=^@var{file}
7056 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7057 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7058 Note that if this option is used, then linking must be done manually,
7059 gnatlink cannot be used.
7061 @item ^-O^/OBJECT_LIST^
7062 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7063 Output object list.
7065 @item ^-p^/PESSIMISTIC_ELABORATION^
7066 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7067 Pessimistic (worst-case) elaboration order
7069 @item ^-s^/READ_SOURCES=ALL^
7070 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7071 Require all source files to be present.
7073 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7074 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7075 Specifies the value to be used when detecting uninitialized scalar
7076 objects with pragma Initialize_Scalars.
7077 The @var{xxx} ^string specified with the switch^option^ may be either
7078 @itemize @bullet
7079 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7080 @item ``@option{^lo^LOW^}'' for the lowest possible value
7081 possible, and the low
7082 @item ``@option{^hi^HIGH^}'' for the highest possible value
7083 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7084 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7085 @end itemize
7087 In addition, you can specify @option{-Sev} to indicate that the value is
7088 to be set at run time. In this case, the program will look for an environment
7089 @cindex GNAT_INIT_SCALARS
7090 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7091 of @option{in/lo/hi/xx} with the same meanings as above.
7092 If no environment variable is found, or if it does not have a valid value,
7093 then the default is @option{in} (invalid values).
7095 @ifclear vms
7096 @item -static
7097 @cindex @option{-static} (@code{gnatbind})
7098 Link against a static GNAT run time.
7100 @item -shared
7101 @cindex @option{-shared} (@code{gnatbind})
7102 Link against a shared GNAT run time when available.
7103 @end ifclear
7105 @item ^-t^/NOTIME_STAMP_CHECK^
7106 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7107 Tolerate time stamp and other consistency errors
7109 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7110 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7111 Set the time slice value to @var{n} milliseconds. If the system supports
7112 the specification of a specific time slice value, then the indicated value
7113 is used. If the system does not support specific time slice values, but
7114 does support some general notion of round-robin scheduling, then any
7115 non-zero value will activate round-robin scheduling.
7117 A value of zero is treated specially. It turns off time
7118 slicing, and in addition, indicates to the tasking run time that the
7119 semantics should match as closely as possible the Annex D
7120 requirements of the Ada RM, and in particular sets the default
7121 scheduling policy to @code{FIFO_Within_Priorities}.
7123 @item ^-v^/REPORT_ERRORS=VERBOSE^
7124 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7125 Verbose mode. Write error messages, header, summary output to
7126 @file{stdout}.
7128 @ifclear vms
7129 @item -w@var{x}
7130 @cindex @option{-w} (@code{gnatbind})
7131 Warning mode (@var{x}=s/e for suppress/treat as error)
7132 @end ifclear
7134 @ifset vms
7135 @item /WARNINGS=NORMAL
7136 @cindex @option{/WARNINGS} (@code{gnatbind})
7137 Normal warnings mode. Warnings are issued but ignored
7139 @item /WARNINGS=SUPPRESS
7140 @cindex @option{/WARNINGS} (@code{gnatbind})
7141 All warning messages are suppressed
7143 @item /WARNINGS=ERROR
7144 @cindex @option{/WARNINGS} (@code{gnatbind})
7145 Warning messages are treated as fatal errors
7146 @end ifset
7148 @item ^-x^/READ_SOURCES=NONE^
7149 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7150 Exclude source files (check object consistency only).
7152 @ifset vms
7153 @item /READ_SOURCES=AVAILABLE
7154 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7155 Default mode, in which sources are checked for consistency only if
7156 they are available.
7157 @end ifset
7159 @item ^-z^/ZERO_MAIN^
7160 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7161 No main subprogram.
7162 @end table
7164 @ifclear vms
7165 @noindent
7166 You may obtain this listing of switches by running @code{gnatbind} with
7167 no arguments.
7168 @end ifclear
7171 @node Consistency-Checking Modes
7172 @subsection Consistency-Checking Modes
7174 @noindent
7175 As described earlier, by default @code{gnatbind} checks
7176 that object files are consistent with one another and are consistent
7177 with any source files it can locate. The following switches control binder
7178 access to sources.
7180 @table @option
7181 @c !sort!
7182 @item ^-s^/READ_SOURCES=ALL^
7183 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7184 Require source files to be present. In this mode, the binder must be
7185 able to locate all source files that are referenced, in order to check
7186 their consistency. In normal mode, if a source file cannot be located it
7187 is simply ignored. If you specify this switch, a missing source
7188 file is an error.
7190 @item ^-x^/READ_SOURCES=NONE^
7191 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7192 Exclude source files. In this mode, the binder only checks that ALI
7193 files are consistent with one another. Source files are not accessed.
7194 The binder runs faster in this mode, and there is still a guarantee that
7195 the resulting program is self-consistent.
7196 If a source file has been edited since it was last compiled, and you
7197 specify this switch, the binder will not detect that the object
7198 file is out of date with respect to the source file. Note that this is the
7199 mode that is automatically used by @code{gnatmake} because in this
7200 case the checking against sources has already been performed by
7201 @code{gnatmake} in the course of compilation (i.e. before binding).
7203 @ifset vms
7204 @item /READ_SOURCES=AVAILABLE
7205 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7206 This is the default mode in which source files are checked if they are
7207 available, and ignored if they are not available.
7208 @end ifset
7209 @end table
7211 @node Binder Error Message Control
7212 @subsection Binder Error Message Control
7214 @noindent
7215 The following switches provide control over the generation of error
7216 messages from the binder:
7218 @table @option
7219 @c !sort!
7220 @item ^-v^/REPORT_ERRORS=VERBOSE^
7221 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7222 Verbose mode. In the normal mode, brief error messages are generated to
7223 @file{stderr}. If this switch is present, a header is written
7224 to @file{stdout} and any error messages are directed to @file{stdout}.
7225 All that is written to @file{stderr} is a brief summary message.
7227 @item ^-b^/REPORT_ERRORS=BRIEF^
7228 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7229 Generate brief error messages to @file{stderr} even if verbose mode is
7230 specified. This is relevant only when used with the
7231 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7233 @ifclear vms
7234 @item -m@var{n}
7235 @cindex @option{-m} (@code{gnatbind})
7236 Limits the number of error messages to @var{n}, a decimal integer in the
7237 range 1-999. The binder terminates immediately if this limit is reached.
7239 @item -M@var{xxx}
7240 @cindex @option{-M} (@code{gnatbind})
7241 Renames the generated main program from @code{main} to @code{xxx}.
7242 This is useful in the case of some cross-building environments, where
7243 the actual main program is separate from the one generated
7244 by @code{gnatbind}.
7245 @end ifclear
7247 @item ^-ws^/WARNINGS=SUPPRESS^
7248 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7249 @cindex Warnings
7250 Suppress all warning messages.
7252 @item ^-we^/WARNINGS=ERROR^
7253 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7254 Treat any warning messages as fatal errors.
7256 @ifset vms
7257 @item /WARNINGS=NORMAL
7258 Standard mode with warnings generated, but warnings do not get treated
7259 as errors.
7260 @end ifset
7262 @item ^-t^/NOTIME_STAMP_CHECK^
7263 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7264 @cindex Time stamp checks, in binder
7265 @cindex Binder consistency checks
7266 @cindex Consistency checks, in binder
7267 The binder performs a number of consistency checks including:
7269 @itemize @bullet
7270 @item
7271 Check that time stamps of a given source unit are consistent
7272 @item
7273 Check that checksums of a given source unit are consistent
7274 @item
7275 Check that consistent versions of @code{GNAT} were used for compilation
7276 @item
7277 Check consistency of configuration pragmas as required
7278 @end itemize
7280 @noindent
7281 Normally failure of such checks, in accordance with the consistency
7282 requirements of the Ada Reference Manual, causes error messages to be
7283 generated which abort the binder and prevent the output of a binder
7284 file and subsequent link to obtain an executable.
7286 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7287 into warnings, so that
7288 binding and linking can continue to completion even in the presence of such
7289 errors. The result may be a failed link (due to missing symbols), or a
7290 non-functional executable which has undefined semantics.
7291 @emph{This means that
7292 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7293 with extreme care.}
7294 @end table
7296 @node Elaboration Control
7297 @subsection Elaboration Control
7299 @noindent
7300 The following switches provide additional control over the elaboration
7301 order. For full details see @xref{Elaboration Order Handling in GNAT}.
7303 @table @option
7304 @item ^-p^/PESSIMISTIC_ELABORATION^
7305 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7306 Normally the binder attempts to choose an elaboration order that is
7307 likely to minimize the likelihood of an elaboration order error resulting
7308 in raising a @code{Program_Error} exception. This switch reverses the
7309 action of the binder, and requests that it deliberately choose an order
7310 that is likely to maximize the likelihood of an elaboration error.
7311 This is useful in ensuring portability and avoiding dependence on
7312 accidental fortuitous elaboration ordering.
7314 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7315 switch if dynamic
7316 elaboration checking is used (@option{-gnatE} switch used for compilation).
7317 This is because in the default static elaboration mode, all necessary
7318 @code{Elaborate_All} pragmas are implicitly inserted.
7319 These implicit pragmas are still respected by the binder in
7320 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7321 safe elaboration order is assured.
7322 @end table
7324 @node Output Control
7325 @subsection Output Control
7327 @noindent
7328 The following switches allow additional control over the output
7329 generated by the binder.
7331 @table @option
7332 @c !sort!
7334 @item ^-A^/BIND_FILE=ADA^
7335 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7336 Generate binder program in Ada (default). The binder program is named
7337 @file{b~@var{mainprog}.adb} by default. This can be changed with
7338 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7340 @item ^-c^/NOOUTPUT^
7341 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7342 Check only. Do not generate the binder output file. In this mode the
7343 binder performs all error checks but does not generate an output file.
7345 @item ^-C^/BIND_FILE=C^
7346 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7347 Generate binder program in C. The binder program is named
7348 @file{b_@var{mainprog}.c}.
7349 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7350 option.
7352 @item ^-e^/ELABORATION_DEPENDENCIES^
7353 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7354 Output complete list of elaboration-order dependencies, showing the
7355 reason for each dependency. This output can be rather extensive but may
7356 be useful in diagnosing problems with elaboration order. The output is
7357 written to @file{stdout}.
7359 @item ^-h^/HELP^
7360 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7361 Output usage information. The output is written to @file{stdout}.
7363 @item ^-K^/LINKER_OPTION_LIST^
7364 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7365 Output linker options to @file{stdout}. Includes library search paths,
7366 contents of pragmas Ident and Linker_Options, and libraries added
7367 by @code{gnatbind}.
7369 @item ^-l^/ORDER_OF_ELABORATION^
7370 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7371 Output chosen elaboration order. The output is written to @file{stdout}.
7373 @item ^-O^/OBJECT_LIST^
7374 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7375 Output full names of all the object files that must be linked to provide
7376 the Ada component of the program. The output is written to @file{stdout}.
7377 This list includes the files explicitly supplied and referenced by the user
7378 as well as implicitly referenced run-time unit files. The latter are
7379 omitted if the corresponding units reside in shared libraries. The
7380 directory names for the run-time units depend on the system configuration.
7382 @item ^-o ^/OUTPUT=^@var{file}
7383 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7384 Set name of output file to @var{file} instead of the normal
7385 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7386 binder generated body filename. In C mode you would normally give
7387 @var{file} an extension of @file{.c} because it will be a C source program.
7388 Note that if this option is used, then linking must be done manually.
7389 It is not possible to use gnatlink in this case, since it cannot locate
7390 the binder file.
7392 @item ^-r^/RESTRICTION_LIST^
7393 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7394 Generate list of @code{pragma Restrictions} that could be applied to
7395 the current unit. This is useful for code audit purposes, and also may
7396 be used to improve code generation in some cases.
7398 @end table
7400 @node Binding with Non-Ada Main Programs
7401 @subsection Binding with Non-Ada Main Programs
7403 @noindent
7404 In our description so far we have assumed that the main
7405 program is in Ada, and that the task of the binder is to generate a
7406 corresponding function @code{main} that invokes this Ada main
7407 program. GNAT also supports the building of executable programs where
7408 the main program is not in Ada, but some of the called routines are
7409 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7410 The following switch is used in this situation:
7412 @table @option
7413 @item ^-n^/NOMAIN^
7414 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7415 No main program. The main program is not in Ada.
7416 @end table
7418 @noindent
7419 In this case, most of the functions of the binder are still required,
7420 but instead of generating a main program, the binder generates a file
7421 containing the following callable routines:
7423 @table @code
7424 @item adainit
7425 @findex adainit
7426 You must call this routine to initialize the Ada part of the program by
7427 calling the necessary elaboration routines. A call to @code{adainit} is
7428 required before the first call to an Ada subprogram.
7430 Note that it is assumed that the basic execution environment must be setup
7431 to be appropriate for Ada execution at the point where the first Ada
7432 subprogram is called. In particular, if the Ada code will do any
7433 floating-point operations, then the FPU must be setup in an appropriate
7434 manner. For the case of the x86, for example, full precision mode is
7435 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7436 that the FPU is in the right state.
7438 @item adafinal
7439 @findex adafinal
7440 You must call this routine to perform any library-level finalization
7441 required by the Ada subprograms. A call to @code{adafinal} is required
7442 after the last call to an Ada subprogram, and before the program
7443 terminates.
7444 @end table
7446 @noindent
7447 If the @option{^-n^/NOMAIN^} switch
7448 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7449 @cindex Binder, multiple input files
7450 is given, more than one ALI file may appear on
7451 the command line for @code{gnatbind}. The normal @dfn{closure}
7452 calculation is performed for each of the specified units. Calculating
7453 the closure means finding out the set of units involved by tracing
7454 @code{with} references. The reason it is necessary to be able to
7455 specify more than one ALI file is that a given program may invoke two or
7456 more quite separate groups of Ada units.
7458 The binder takes the name of its output file from the last specified ALI
7459 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7460 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7461 The output is an Ada unit in source form that can
7462 be compiled with GNAT unless the -C switch is used in which case the
7463 output is a C source file, which must be compiled using the C compiler.
7464 This compilation occurs automatically as part of the @code{gnatlink}
7465 processing.
7467 Currently the GNAT run time requires a FPU using 80 bits mode
7468 precision. Under targets where this is not the default it is required to
7469 call GNAT.Float_Control.Reset before using floating point numbers (this
7470 include float computation, float input and output) in the Ada code. A
7471 side effect is that this could be the wrong mode for the foreign code
7472 where floating point computation could be broken after this call.
7474 @node Binding Programs with No Main Subprogram
7475 @subsection Binding Programs with No Main Subprogram
7477 @noindent
7478 It is possible to have an Ada program which does not have a main
7479 subprogram. This program will call the elaboration routines of all the
7480 packages, then the finalization routines.
7482 The following switch is used to bind programs organized in this manner:
7484 @table @option
7485 @item ^-z^/ZERO_MAIN^
7486 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7487 Normally the binder checks that the unit name given on the command line
7488 corresponds to a suitable main subprogram. When this switch is used,
7489 a list of ALI files can be given, and the execution of the program
7490 consists of elaboration of these units in an appropriate order.
7491 @end table
7494 @node Command-Line Access
7495 @section Command-Line Access
7497 @noindent
7498 The package @code{Ada.Command_Line} provides access to the command-line
7499 arguments and program name. In order for this interface to operate
7500 correctly, the two variables
7502 @smallexample
7503 @group
7504 int gnat_argc;
7505 char **gnat_argv;
7506 @end group
7507 @end smallexample
7509 @noindent
7510 @findex gnat_argv
7511 @findex gnat_argc
7512 are declared in one of the GNAT library routines. These variables must
7513 be set from the actual @code{argc} and @code{argv} values passed to the
7514 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7515 generates the C main program to automatically set these variables.
7516 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7517 set these variables. If they are not set, the procedures in
7518 @code{Ada.Command_Line} will not be available, and any attempt to use
7519 them will raise @code{Constraint_Error}. If command line access is
7520 required, your main program must set @code{gnat_argc} and
7521 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7525 @node Search Paths for gnatbind
7526 @section Search Paths for @code{gnatbind}
7528 @noindent
7529 The binder takes the name of an ALI file as its argument and needs to
7530 locate source files as well as other ALI files to verify object consistency.
7532 For source files, it follows exactly the same search rules as @code{gcc}
7533 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7534 directories searched are:
7536 @enumerate
7537 @item
7538 The directory containing the ALI file named in the command line, unless
7539 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7541 @item
7542 All directories specified by @option{^-I^/SEARCH^}
7543 switches on the @code{gnatbind}
7544 command line, in the order given.
7546 @item
7547 @findex ADA_OBJECTS_PATH
7548 Each of the directories listed in the value of the
7549 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7550 @ifset unw
7551 Construct this value
7552 exactly as the @code{PATH} environment variable: a list of directory
7553 names separated by colons (semicolons when working with the NT version
7554 of GNAT).
7555 @end ifset
7556 @ifset vms
7557 Normally, define this value as a logical name containing a comma separated
7558 list of directory names.
7560 This variable can also be defined by means of an environment string
7561 (an argument to the DEC C exec* set of functions).
7563 Logical Name:
7564 @smallexample
7565 DEFINE ANOTHER_PATH FOO:[BAG]
7566 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7567 @end smallexample
7569 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7570 first, followed by the standard Ada 95
7571 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7572 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
7573 (Text_IO, Sequential_IO, etc)
7574 instead of the Ada95 packages. Thus, in order to get the Ada 95
7575 packages by default, ADA_OBJECTS_PATH must be redefined.
7576 @end ifset
7578 @item
7579 @findex ADA_PRJ_OBJECTS_FILE
7580 Each of the directories listed in the text file whose name is given
7581 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7583 @noindent
7584 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7585 driver when project files are used. It should not normally be set
7586 by other means.
7588 @item
7589 The content of the @file{ada_object_path} file which is part of the GNAT
7590 installation tree and is used to store standard libraries such as the
7591 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7592 specified.
7593 @ifclear vms
7594 @ref{Installing the library}
7595 @end ifclear
7596 @end enumerate
7598 @noindent
7599 In the binder the switch @option{^-I^/SEARCH^}
7600 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7601 is used to specify both source and
7602 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7603 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7604 instead if you want to specify
7605 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7606 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7607 if you want to specify library paths
7608 only. This means that for the binder
7609 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7610 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7611 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7612 The binder generates the bind file (a C language source file) in the
7613 current working directory.
7615 @findex Ada
7616 @findex System
7617 @findex Interfaces
7618 @findex GNAT
7619 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7620 children make up the GNAT Run-Time Library, together with the package
7621 GNAT and its children, which contain a set of useful additional
7622 library functions provided by GNAT. The sources for these units are
7623 needed by the compiler and are kept together in one directory. The ALI
7624 files and object files generated by compiling the RTL are needed by the
7625 binder and the linker and are kept together in one directory, typically
7626 different from the directory containing the sources. In a normal
7627 installation, you need not specify these directory names when compiling
7628 or binding. Either the environment variables or the built-in defaults
7629 cause these files to be found.
7631 Besides simplifying access to the RTL, a major use of search paths is
7632 in compiling sources from multiple directories. This can make
7633 development environments much more flexible.
7635 @node Examples of gnatbind Usage
7636 @section Examples of @code{gnatbind} Usage
7638 @noindent
7639 This section contains a number of examples of using the GNAT binding
7640 utility @code{gnatbind}.
7642 @table @code
7643 @item gnatbind hello
7644 The main program @code{Hello} (source program in @file{hello.adb}) is
7645 bound using the standard switch settings. The generated main program is
7646 @file{b~hello.adb}. This is the normal, default use of the binder.
7648 @ifclear vms
7649 @item gnatbind hello -o mainprog.adb
7650 @end ifclear
7651 @ifset vms
7652 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7653 @end ifset
7654 The main program @code{Hello} (source program in @file{hello.adb}) is
7655 bound using the standard switch settings. The generated main program is
7656 @file{mainprog.adb} with the associated spec in
7657 @file{mainprog.ads}. Note that you must specify the body here not the
7658 spec, in the case where the output is in Ada. Note that if this option
7659 is used, then linking must be done manually, since gnatlink will not
7660 be able to find the generated file.
7662 @ifclear vms
7663 @item gnatbind main -C -o mainprog.c -x
7664 @end ifclear
7665 @ifset vms
7666 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7667 @end ifset
7668 The main program @code{Main} (source program in
7669 @file{main.adb}) is bound, excluding source files from the
7670 consistency checking, generating
7671 the file @file{mainprog.c}.
7673 @ifclear vms
7674 @item gnatbind -x main_program -C -o mainprog.c
7675 This command is exactly the same as the previous example. Switches may
7676 appear anywhere in the command line, and single letter switches may be
7677 combined into a single switch.
7678 @end ifclear
7680 @ifclear vms
7681 @item gnatbind -n math dbase -C -o ada-control.c
7682 @end ifclear
7683 @ifset vms
7684 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7685 @end ifset
7686 The main program is in a language other than Ada, but calls to
7687 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7688 to @code{gnatbind} generates the file @file{ada-control.c} containing
7689 the @code{adainit} and @code{adafinal} routines to be called before and
7690 after accessing the Ada units.
7691 @end table
7694 @c ------------------------------------
7695 @node Linking Using gnatlink
7696 @chapter Linking Using @code{gnatlink}
7697 @c ------------------------------------
7698 @findex gnatlink
7700 @noindent
7701 This chapter discusses @code{gnatlink}, a tool that links
7702 an Ada program and builds an executable file. This utility
7703 invokes the system linker ^(via the @code{gcc} command)^^
7704 with a correct list of object files and library references.
7705 @code{gnatlink} automatically determines the list of files and
7706 references for the Ada part of a program. It uses the binder file
7707 generated by the @command{gnatbind} to determine this list.
7709 @menu
7710 * Running gnatlink::
7711 * Switches for gnatlink::
7712 * Setting Stack Size from gnatlink::
7713 * Setting Heap Size from gnatlink::
7714 @end menu
7716 @node Running gnatlink
7717 @section Running @code{gnatlink}
7719 @noindent
7720 The form of the @code{gnatlink} command is
7722 @smallexample
7723 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
7724            [@var{non-Ada objects}] [@var{linker options}]
7725 @end smallexample
7727 @noindent
7728 The arguments of @code{gnatlink} (switches, main @file{ALI} file,
7729 non-Ada objects
7730 or linker options) may be in any order, provided that no non-Ada object may
7731 be mistaken for a main @file{ALI} file.
7732 Any file name @file{F} without the @file{.ali}
7733 extension will be taken as the main @file{ALI} file if a file exists
7734 whose name is the concatenation of @file{F} and @file{.ali}.
7736 @noindent
7737 @file{@var{mainprog}.ali} references the ALI file of the main program.
7738 The @file{.ali} extension of this file can be omitted. From this
7739 reference, @code{gnatlink} locates the corresponding binder file
7740 @file{b~@var{mainprog}.adb} and, using the information in this file along
7741 with the list of non-Ada objects and linker options, constructs a
7742 linker command file to create the executable.
7744 The arguments other than the @code{gnatlink} switches and the main @file{ALI}
7745 file are passed to the linker uninterpreted.
7746 They typically include the names of
7747 object files for units written in other languages than Ada and any library
7748 references required to resolve references in any of these foreign language
7749 units, or in @code{Import} pragmas in any Ada units.
7751 @var{linker options} is an optional list of linker specific
7752 switches.
7753 The default linker called by gnatlink is @var{gcc} which in
7754 turn calls the appropriate system linker.
7755 Standard options for the linker such as @option{-lmy_lib} or
7756 @option{-Ldir} can be added as is.
7757 For options that are not recognized by
7758 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7759 @option{-Wl,}.
7760 Refer to the GCC documentation for
7761 details. Here is an example showing how to generate a linker map:
7763 @ifclear vms
7764 @smallexample
7765 $ gnatlink my_prog -Wl,-Map,MAPFILE
7766 @end smallexample
7767 @end ifclear
7769 @ifset vms
7770 <<Need example for VMS>>
7771 @end ifset
7773 Using @var{linker options} it is possible to set the program stack and
7774 heap size. See @ref{Setting Stack Size from gnatlink}, and
7775 @ref{Setting Heap Size from gnatlink}.
7777 @code{gnatlink} determines the list of objects required by the Ada
7778 program and prepends them to the list of objects passed to the linker.
7779 @code{gnatlink} also gathers any arguments set by the use of
7780 @code{pragma Linker_Options} and adds them to the list of arguments
7781 presented to the linker.
7783 @ifset vms
7784 @code{gnatlink} accepts the following types of extra files on the command
7785 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7786 options files (.OPT). These are recognized and handled according to their
7787 extension.
7788 @end ifset
7790 @node Switches for gnatlink
7791 @section Switches for @code{gnatlink}
7793 @noindent
7794 The following switches are available with the @code{gnatlink} utility:
7796 @table @option
7797 @c !sort!
7799 @item ^-A^/BIND_FILE=ADA^
7800 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatlink})
7801 The binder has generated code in Ada. This is the default.
7803 @item ^-C^/BIND_FILE=C^
7804 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatlink})
7805 If instead of generating a file in Ada, the binder has generated one in
7806 C, then the linker needs to know about it. Use this switch to signal
7807 to @code{gnatlink} that the binder has generated C code rather than
7808 Ada code.
7810 @item ^-f^/FORCE_OBJECT_FILE_LIST^
7811 @cindex Command line length
7812 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@code{gnatlink})
7813 On some targets, the command line length is limited, and @code{gnatlink}
7814 will generate a separate file for the linker if the list of object files
7815 is too long.
7816 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
7817 to be generated even if
7818 the limit is not exceeded. This is useful in some cases to deal with
7819 special situations where the command line length is exceeded.
7821 @item ^-g^/DEBUG^
7822 @cindex Debugging information, including
7823 @cindex @option{^-g^/DEBUG^} (@code{gnatlink})
7824 The option to include debugging information causes the Ada bind file (in
7825 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7826 @option{^-g^/DEBUG^}.
7827 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7828 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7829 Without @option{^-g^/DEBUG^}, the binder removes these files by
7830 default. The same procedure apply if a C bind file was generated using
7831 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
7832 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7834 @item ^-n^/NOCOMPILE^
7835 @cindex @option{^-n^/NOCOMPILE^} (@code{gnatlink})
7836 Do not compile the file generated by the binder. This may be used when
7837 a link is rerun with different options, but there is no need to recompile
7838 the binder file.
7840 @item ^-v^/VERBOSE^
7841 @cindex @option{^-v^/VERBOSE^} (@code{gnatlink})
7842 Causes additional information to be output, including a full list of the
7843 included object files. This switch option is most useful when you want
7844 to see what set of object files are being used in the link step.
7846 @item ^-v -v^/VERBOSE/VERBOSE^
7847 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@code{gnatlink})
7848 Very verbose mode. Requests that the compiler operate in verbose mode when
7849 it compiles the binder file, and that the system linker run in verbose mode.
7851 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7852 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatlink})
7853 @var{exec-name} specifies an alternate name for the generated
7854 executable program. If this switch is omitted, the executable has the same
7855 name as the main unit. For example, @code{gnatlink try.ali} creates
7856 an executable called @file{^try^TRY.EXE^}.
7858 @ifclear vms
7859 @item -b @var{target}
7860 @cindex @option{-b} (@code{gnatlink})
7861 Compile your program to run on @var{target}, which is the name of a
7862 system configuration. You must have a GNAT cross-compiler built if
7863 @var{target} is not the same as your host system.
7865 @item -B@var{dir}
7866 @cindex @option{-B} (@code{gnatlink})
7867 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7868 from @var{dir} instead of the default location. Only use this switch
7869 when multiple versions of the GNAT compiler are available. See the
7870 @code{gcc} manual page for further details. You would normally use the
7871 @option{-b} or @option{-V} switch instead.
7873 @item --GCC=@var{compiler_name}
7874 @cindex @option{--GCC=compiler_name} (@code{gnatlink})
7875 Program used for compiling the binder file. The default is
7876 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
7877 @code{compiler_name} contains spaces or other separator characters. As
7878 an example @option{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
7879 @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
7880 inserted after your command name. Thus in the above example the compiler
7881 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
7882 If several @option{--GCC=compiler_name} are used, only the last
7883 @var{compiler_name} is taken into account. However, all the additional
7884 switches are also taken into account. Thus,
7885 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7886 @option{--GCC="bar -x -y -z -t"}.
7888 @item --LINK=@var{name}
7889 @cindex @option{--LINK=} (@code{gnatlink})
7890 @var{name} is the name of the linker to be invoked. This is especially
7891 useful in mixed language programs since languages such as C++ require
7892 their own linker to be used. When this switch is omitted, the default
7893 name for the linker is (@file{gcc}). When this switch is used, the
7894 specified linker is called instead of (@file{gcc}) with exactly the same
7895 parameters that would have been passed to (@file{gcc}) so if the desired
7896 linker requires different parameters it is necessary to use a wrapper
7897 script that massages the parameters before invoking the real linker. It
7898 may be useful to control the exact invocation by using the verbose
7899 switch.
7901 @end ifclear
7903 @ifset vms
7904 @item /DEBUG=TRACEBACK
7905 @cindex @code{/DEBUG=TRACEBACK} (@code{gnatlink})
7906 This qualifier causes sufficient information to be included in the
7907 executable file to allow a traceback, but does not include the full
7908 symbol information needed by the debugger.
7910 @item /IDENTIFICATION="<string>"
7911 @code{"<string>"} specifies the string to be stored in the image file
7912 identification field in the image header.
7913 It overrides any pragma @code{Ident} specified string.
7915 @item /NOINHIBIT-EXEC
7916 Generate the executable file even if there are linker warnings.
7918 @item /NOSTART_FILES
7919 Don't link in the object file containing the ``main'' transfer address.
7920 Used when linking with a foreign language main program compiled with a
7921 Digital compiler.
7923 @item /STATIC
7924 Prefer linking with object libraries over sharable images, even without
7925 /DEBUG.
7926 @end ifset
7928 @end table
7930 @node Setting Stack Size from gnatlink
7931 @section Setting Stack Size from @code{gnatlink}
7933 @noindent
7934 Under Windows systems, it is possible to specify the program stack size from
7935 @code{gnatlink} using either:
7937 @itemize @bullet
7939 @item using @option{-Xlinker} linker option
7941 @smallexample
7942 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
7943 @end smallexample
7945 This sets the stack reserve size to 0x10000 bytes and the stack commit
7946 size to 0x1000 bytes.
7948 @item using @option{-Wl} linker option
7950 @smallexample
7951 $ gnatlink hello -Wl,--stack=0x1000000
7952 @end smallexample
7954 This sets the stack reserve size to 0x1000000 bytes. Note that with
7955 @option{-Wl} option it is not possible to set the stack commit size
7956 because the coma is a separator for this option.
7958 @end itemize
7960 @node Setting Heap Size from gnatlink
7961 @section Setting Heap Size from @code{gnatlink}
7963 @noindent
7964 Under Windows systems, it is possible to specify the program heap size from
7965 @code{gnatlink} using either:
7967 @itemize @bullet
7969 @item using @option{-Xlinker} linker option
7971 @smallexample
7972 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
7973 @end smallexample
7975 This sets the heap reserve size to 0x10000 bytes and the heap commit
7976 size to 0x1000 bytes.
7978 @item using @option{-Wl} linker option
7980 @smallexample
7981 $ gnatlink hello -Wl,--heap=0x1000000
7982 @end smallexample
7984 This sets the heap reserve size to 0x1000000 bytes. Note that with
7985 @option{-Wl} option it is not possible to set the heap commit size
7986 because the coma is a separator for this option.
7988 @end itemize
7990 @node The GNAT Make Program gnatmake
7991 @chapter The GNAT Make Program @code{gnatmake}
7992 @findex gnatmake
7994 @menu
7995 * Running gnatmake::
7996 * Switches for gnatmake::
7997 * Mode Switches for gnatmake::
7998 * Notes on the Command Line::
7999 * How gnatmake Works::
8000 * Examples of gnatmake Usage::
8001 @end menu
8002 @noindent
8003 A typical development cycle when working on an Ada program consists of
8004 the following steps:
8006 @enumerate
8007 @item
8008 Edit some sources to fix bugs.
8010 @item
8011 Add enhancements.
8013 @item
8014 Compile all sources affected.
8016 @item
8017 Rebind and relink.
8019 @item
8020 Test.
8021 @end enumerate
8023 @noindent
8024 The third step can be tricky, because not only do the modified files
8025 @cindex Dependency rules
8026 have to be compiled, but any files depending on these files must also be
8027 recompiled. The dependency rules in Ada can be quite complex, especially
8028 in the presence of overloading, @code{use} clauses, generics and inlined
8029 subprograms.
8031 @code{gnatmake} automatically takes care of the third and fourth steps
8032 of this process. It determines which sources need to be compiled,
8033 compiles them, and binds and links the resulting object files.
8035 Unlike some other Ada make programs, the dependencies are always
8036 accurately recomputed from the new sources. The source based approach of
8037 the GNAT compilation model makes this possible. This means that if
8038 changes to the source program cause corresponding changes in
8039 dependencies, they will always be tracked exactly correctly by
8040 @code{gnatmake}.
8042 @node Running gnatmake
8043 @section Running @code{gnatmake}
8045 @noindent
8046 The usual form of the @code{gnatmake} command is
8048 @smallexample
8049 $ gnatmake [@var{switches}] @var{file_name}
8050       [@var{file_names}] [@var{mode_switches}]
8051 @end smallexample
8053 @noindent
8054 The only required argument is one @var{file_name}, which specifies
8055 a compilation unit that is a main program. Several @var{file_names} can be
8056 specified: this will result in several executables being built.
8057 If @code{switches} are present, they can be placed before the first
8058 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8059 If @var{mode_switches} are present, they must always be placed after
8060 the last @var{file_name} and all @code{switches}.
8062 If you are using standard file extensions (.adb and .ads), then the
8063 extension may be omitted from the @var{file_name} arguments. However, if
8064 you are using non-standard extensions, then it is required that the
8065 extension be given. A relative or absolute directory path can be
8066 specified in a @var{file_name}, in which case, the input source file will
8067 be searched for in the specified directory only. Otherwise, the input
8068 source file will first be searched in the directory where
8069 @code{gnatmake} was invoked and if it is not found, it will be search on
8070 the source path of the compiler as described in
8071 @ref{Search Paths and the Run-Time Library (RTL)}.
8073 All @code{gnatmake} output (except when you specify
8074 @option{^-M^/DEPENDENCIES_LIST^}) is to
8075 @file{stderr}. The output produced by the
8076 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8077 @file{stdout}.
8079 @node Switches for gnatmake
8080 @section Switches for @code{gnatmake}
8082 @noindent
8083 You may specify any of the following switches to @code{gnatmake}:
8085 @table @option
8086 @c !sort!
8087 @ifclear vms
8088 @item --GCC=@var{compiler_name}
8089 @cindex @option{--GCC=compiler_name} (@code{gnatmake})
8090 Program used for compiling. The default is `@code{gcc}'. You need to use
8091 quotes around @var{compiler_name} if @code{compiler_name} contains
8092 spaces or other separator characters. As an example @option{--GCC="foo -x
8093 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
8094 compiler. Note that switch @option{-c} is always inserted after your
8095 command name. Thus in the above example the compiler command that will
8096 be used by @code{gnatmake} will be @code{foo -c -x -y}.
8097 If several @option{--GCC=compiler_name} are used, only the last
8098 @var{compiler_name} is taken into account. However, all the additional
8099 switches are also taken into account. Thus,
8100 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8101 @option{--GCC="bar -x -y -z -t"}.
8103 @item --GNATBIND=@var{binder_name}
8104 @cindex @option{--GNATBIND=binder_name} (@code{gnatmake})
8105 Program used for binding. The default is `@code{gnatbind}'. You need to
8106 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8107 or other separator characters. As an example @option{--GNATBIND="bar -x
8108 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
8109 binder. Binder switches that are normally appended by @code{gnatmake} to
8110 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8112 @item --GNATLINK=@var{linker_name}
8113 @cindex @option{--GNATLINK=linker_name} (@code{gnatmake})
8114 Program used for linking. The default is `@code{gnatlink}'. You need to
8115 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8116 or other separator characters. As an example @option{--GNATLINK="lan -x
8117 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
8118 linker. Linker switches that are normally appended by @code{gnatmake} to
8119 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
8121 @end ifclear
8123 @item ^-a^/ALL_FILES^
8124 @cindex @option{^-a^/ALL_FILES^} (@code{gnatmake})
8125 Consider all files in the make process, even the GNAT internal system
8126 files (for example, the predefined Ada library files), as well as any
8127 locked files. Locked files are files whose ALI file is write-protected.
8128 By default,
8129 @code{gnatmake} does not check these files,
8130 because the assumption is that the GNAT internal files are properly up
8131 to date, and also that any write protected ALI files have been properly
8132 installed. Note that if there is an installation problem, such that one
8133 of these files is not up to date, it will be properly caught by the
8134 binder.
8135 You may have to specify this switch if you are working on GNAT
8136 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8137 in conjunction with @option{^-f^/FORCE_COMPILE^}
8138 if you need to recompile an entire application,
8139 including run-time files, using special configuration pragmas,
8140 such as a @code{Normalize_Scalars} pragma.
8142 By default
8143 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8144 internal files with
8145 @ifclear vms
8146 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8147 @end ifclear
8148 @ifset vms
8149 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8150 @end ifset
8152 @item ^-b^/ACTIONS=BIND^
8153 @cindex @option{^-b^/ACTIONS=BIND^} (@code{gnatmake})
8154 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8155 compilation and binding, but no link.
8156 Can be combined with @option{^-l^/ACTIONS=LINK^}
8157 to do binding and linking. When not combined with
8158 @option{^-c^/ACTIONS=COMPILE^}
8159 all the units in the closure of the main program must have been previously
8160 compiled and must be up to date. The root unit specified by @var{file_name}
8161 may be given without extension, with the source extension or, if no GNAT
8162 Project File is specified, with the ALI file extension.
8164 @item ^-c^/ACTIONS=COMPILE^
8165 @cindex @option{^-c^/ACTIONS=COMPILE^} (@code{gnatmake})
8166 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8167 is also specified. Do not perform linking, except if both
8168 @option{^-b^/ACTIONS=BIND^} and
8169  @option{^-l^/ACTIONS=LINK^} are also specified.
8170 If the root unit specified by @var{file_name} is not a main unit, this is the
8171 default. Otherwise @code{gnatmake} will attempt binding and linking
8172 unless all objects are up to date and the executable is more recent than
8173 the objects.
8175 @item ^-C^/MAPPING^
8176 @cindex @option{^-C^/MAPPING^} (@code{gnatmake})
8177 Use a temporary mapping file. A mapping file is a way to communicate to the
8178 compiler two mappings: from unit names to file names (without any directory
8179 information) and from file names to path names (with full directory
8180 information). These mappings are used by the compiler to short-circuit the path
8181 search. When @code{gnatmake} is invoked with this switch, it will create
8182 a temporary mapping file, initially populated by the project manager,
8183 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8184 Each invocation of the compiler will add the newly accessed sources to the
8185 mapping file. This will improve the source search during the next invocation
8186 of the compiler.
8188 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8189 @cindex @option{^-C=^/USE_MAPPING^} (@code{gnatmake})
8190 Use a specific mapping file. The file, specified as a path name (absolute or
8191 relative) by this switch, should already exist, otherwise the switch is
8192 ineffective. The specified mapping file will be communicated to the compiler.
8193 This switch is not compatible with a project file
8194 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8195 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8197 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8198 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatmake})
8199 Put all object files and ALI file in directory @var{dir}.
8200 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8201 and ALI files go in the current working directory.
8203 This switch cannot be used when using a project file.
8205 @ifclear vms
8206 @item -eL
8207 @cindex @option{-eL} (@code{gnatmake})
8208 Follow all symbolic links when processing project files.
8209 @end ifclear
8211 @item ^-f^/FORCE_COMPILE^
8212 @cindex @option{^-f^/FORCE_COMPILE^} (@code{gnatmake})
8213 Force recompilations. Recompile all sources, even though some object
8214 files may be up to date, but don't recompile predefined or GNAT internal
8215 files or locked files (files with a write-protected ALI file),
8216 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8218 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8219 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatmake})
8220 When using project files, if some errors or warnings are detected during
8221 parsing and verbose mode is not in effect (no use of switch
8222 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8223 file, rather than its simple file name.
8225 @item ^-i^/IN_PLACE^
8226 @cindex @option{^-i^/IN_PLACE^} (@code{gnatmake})
8227 In normal mode, @code{gnatmake} compiles all object files and ALI files
8228 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8229 then instead object files and ALI files that already exist are overwritten
8230 in place. This means that once a large project is organized into separate
8231 directories in the desired manner, then @code{gnatmake} will automatically
8232 maintain and update this organization. If no ALI files are found on the
8233 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8234 the new object and ALI files are created in the
8235 directory containing the source being compiled. If another organization
8236 is desired, where objects and sources are kept in different directories,
8237 a useful technique is to create dummy ALI files in the desired directories.
8238 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
8239 the corresponding source file, and it will be put the resulting object
8240 and ALI files in the directory where it found the dummy file.
8242 @item ^-j^/PROCESSES=^@var{n}
8243 @cindex @option{^-j^/PROCESSES^} (@code{gnatmake})
8244 @cindex Parallel make
8245 Use @var{n} processes to carry out the (re)compilations. On a
8246 multiprocessor machine compilations will occur in parallel. In the
8247 event of compilation errors, messages from various compilations might
8248 get interspersed (but @code{gnatmake} will give you the full ordered
8249 list of failing compiles at the end). If this is problematic, rerun
8250 the make process with n set to 1 to get a clean list of messages.
8252 @item ^-k^/CONTINUE_ON_ERROR^
8253 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@code{gnatmake})
8254 Keep going. Continue as much as possible after a compilation error. To
8255 ease the programmer's task in case of compilation errors, the list of
8256 sources for which the compile fails is given when @code{gnatmake}
8257 terminates.
8259 If @code{gnatmake} is invoked with several @file{file_names} and with this
8260 switch, if there are compilation errors when building an executable,
8261 @code{gnatmake} will not attempt to build the following executables.
8263 @item ^-l^/ACTIONS=LINK^
8264 @cindex @option{^-l^/ACTIONS=LINK^} (@code{gnatmake})
8265 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8266 and linking. Linking will not be performed if combined with
8267 @option{^-c^/ACTIONS=COMPILE^}
8268 but not with @option{^-b^/ACTIONS=BIND^}.
8269 When not combined with @option{^-b^/ACTIONS=BIND^}
8270 all the units in the closure of the main program must have been previously
8271 compiled and must be up to date, and the main program need to have been bound.
8272 The root unit specified by @var{file_name}
8273 may be given without extension, with the source extension or, if no GNAT
8274 Project File is specified, with the ALI file extension.
8276 @item ^-m^/MINIMAL_RECOMPILATION^
8277 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@code{gnatmake})
8278 Specifies that the minimum necessary amount of recompilations
8279 be performed. In this mode @code{gnatmake} ignores time
8280 stamp differences when the only
8281 modifications to a source file consist in adding/removing comments,
8282 empty lines, spaces or tabs. This means that if you have changed the
8283 comments in a source file or have simply reformatted it, using this
8284 switch will tell gnatmake not to recompile files that depend on it
8285 (provided other sources on which these files depend have undergone no
8286 semantic modifications). Note that the debugging information may be
8287 out of date with respect to the sources if the @option{-m} switch causes
8288 a compilation to be switched, so the use of this switch represents a
8289 trade-off between compilation time and accurate debugging information.
8291 @item ^-M^/DEPENDENCIES_LIST^
8292 @cindex Dependencies, producing list
8293 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@code{gnatmake})
8294 Check if all objects are up to date. If they are, output the object
8295 dependences to @file{stdout} in a form that can be directly exploited in
8296 a @file{Makefile}. By default, each source file is prefixed with its
8297 (relative or absolute) directory name. This name is whatever you
8298 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8299 and @option{^-I^/SEARCH^} switches. If you use
8300 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8301 @option{^-q^/QUIET^}
8302 (see below), only the source file names,
8303 without relative paths, are output. If you just specify the
8304 @option{^-M^/DEPENDENCIES_LIST^}
8305 switch, dependencies of the GNAT internal system files are omitted. This
8306 is typically what you want. If you also specify
8307 the @option{^-a^/ALL_FILES^} switch,
8308 dependencies of the GNAT internal files are also listed. Note that
8309 dependencies of the objects in external Ada libraries (see switch
8310 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8311 are never reported.
8313 @item ^-n^/DO_OBJECT_CHECK^
8314 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@code{gnatmake})
8315 Don't compile, bind, or link. Checks if all objects are up to date.
8316 If they are not, the full name of the first file that needs to be
8317 recompiled is printed.
8318 Repeated use of this option, followed by compiling the indicated source
8319 file, will eventually result in recompiling all required units.
8321 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8322 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatmake})
8323 Output executable name. The name of the final executable program will be
8324 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8325 name for the executable will be the name of the input file in appropriate form
8326 for an executable file on the host system.
8328 This switch cannot be used when invoking @code{gnatmake} with several
8329 @file{file_names}.
8331 @item ^-P^/PROJECT_FILE=^@var{project}
8332 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatmake})
8333 Use project file @var{project}. Only one such switch can be used.
8334 See @ref{gnatmake and Project Files}.
8336 @item ^-q^/QUIET^
8337 @cindex @option{^-q^/QUIET^} (@code{gnatmake})
8338 Quiet. When this flag is not set, the commands carried out by
8339 @code{gnatmake} are displayed.
8341 @item ^-s^/SWITCH_CHECK/^
8342 @cindex @option{^-s^/SWITCH_CHECK^} (@code{gnatmake})
8343 Recompile if compiler switches have changed since last compilation.
8344 All compiler switches but -I and -o are taken into account in the
8345 following way:
8346 orders between different ``first letter'' switches are ignored, but
8347 orders between same switches are taken into account. For example,
8348 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8349 is equivalent to @option{-O -g}.
8351 This switch is recommended when Integrated Preprocessing is used.
8353 @item ^-u^/UNIQUE^
8354 @cindex @option{^-u^/UNIQUE^} (@code{gnatmake})
8355 Unique. Recompile at most the main files. It implies -c. Combined with
8356 -f, it is equivalent to calling the compiler directly. Note that using
8357 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8358 (see @ref{Project Files and Main Subprograms}).
8360 @item ^-U^/ALL_PROJECTS^
8361 @cindex @option{^-U^/ALL_PROJECTS^} (@code{gnatmake})
8362 When used without a project file or with one or several mains on the command
8363 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8364 on the command line, all sources of all project files are checked and compiled
8365 if not up to date, and libraries are rebuilt, if necessary.
8367 @item ^-v^/REASONS^
8368 @cindex @option{^-v^/REASONS^} (@code{gnatmake})
8369 Verbose. Displays the reason for all recompilations @code{gnatmake}
8370 decides are necessary.
8372 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8373 Indicates the verbosity of the parsing of GNAT project files.
8374 See @ref{Switches Related to Project Files}.
8376 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8377 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@code{gnatmake})
8378 Indicates that sources that are not part of any Project File may be compiled.
8379 Normally, when using Project Files, only sources that are part of a Project
8380 File may be compile. When this switch is used, a source outside of all Project
8381 Files may be compiled. The ALI file and the object file will be put in the
8382 object directory of the main Project. The compilation switches used will only
8383 be those specified on the command line.
8385 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8386 Indicates that external variable @var{name} has the value @var{value}.
8387 The Project Manager will use this value for occurrences of
8388 @code{external(name)} when parsing the project file.
8389 See @ref{Switches Related to Project Files}.
8391 @item ^-z^/NOMAIN^
8392 @cindex @option{^-z^/NOMAIN^} (@code{gnatmake})
8393 No main subprogram. Bind and link the program even if the unit name
8394 given on the command line is a package name. The resulting executable
8395 will execute the elaboration routines of the package and its closure,
8396 then the finalization routines.
8398 @item ^-g^/DEBUG^
8399 @cindex @option{^-g^/DEBUG^} (@code{gnatmake})
8400 Enable debugging. This switch is simply passed to the compiler and to the
8401 linker.
8403 @end table
8405 @table @asis
8406 @item @code{gcc} @asis{switches}
8407 @ifclear vms
8408 Any uppercase or multi-character switch that is not a @code{gnatmake} switch
8409 is passed to @code{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8410 @end ifclear
8411 @ifset vms
8412 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8413 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8414 automatically treated as a compiler switch, and passed on to all
8415 compilations that are carried out.
8416 @end ifset
8417 @end table
8419 @noindent
8420 Source and library search path switches:
8422 @table @option
8423 @c !sort!
8424 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8425 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatmake})
8426 When looking for source files also look in directory @var{dir}.
8427 The order in which source files search is undertaken is
8428 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8430 @item ^-aL^/SKIP_MISSING=^@var{dir}
8431 @cindex @option{^-aL^/SKIP_MISSING^} (@code{gnatmake})
8432 Consider @var{dir} as being an externally provided Ada library.
8433 Instructs @code{gnatmake} to skip compilation units whose @file{.ALI}
8434 files have been located in directory @var{dir}. This allows you to have
8435 missing bodies for the units in @var{dir} and to ignore out of date bodies
8436 for the same units. You still need to specify
8437 the location of the specs for these units by using the switches
8438 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8439 or @option{^-I^/SEARCH=^@var{dir}}.
8440 Note: this switch is provided for compatibility with previous versions
8441 of @code{gnatmake}. The easier method of causing standard libraries
8442 to be excluded from consideration is to write-protect the corresponding
8443 ALI files.
8445 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8446 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatmake})
8447 When searching for library and object files, look in directory
8448 @var{dir}. The order in which library files are searched is described in
8449 @ref{Search Paths for gnatbind}.
8451 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8452 @cindex Search paths, for @code{gnatmake}
8453 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@code{gnatmake})
8454 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8455 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8457 @item ^-I^/SEARCH=^@var{dir}
8458 @cindex @option{^-I^/SEARCH^} (@code{gnatmake})
8459 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8460 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8462 @item ^-I-^/NOCURRENT_DIRECTORY^
8463 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatmake})
8464 @cindex Source files, suppressing search
8465 Do not look for source files in the directory containing the source
8466 file named in the command line.
8467 Do not look for ALI or object files in the directory
8468 where @code{gnatmake} was invoked.
8470 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8471 @cindex @option{^-L^/LIBRARY_SEARCH^} (@code{gnatmake})
8472 @cindex Linker libraries
8473 Add directory @var{dir} to the list of directories in which the linker
8474 will search for libraries. This is equivalent to
8475 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8476 @ifclear vms
8477 Furthermore, under Windows, the sources pointed to by the libraries path
8478 set in the registry are not searched for.
8479 @end ifclear
8481 @item -nostdinc
8482 @cindex @option{-nostdinc} (@code{gnatmake})
8483 Do not look for source files in the system default directory.
8485 @item -nostdlib
8486 @cindex @option{-nostdlib} (@code{gnatmake})
8487 Do not look for library files in the system default directory.
8489 @item --RTS=@var{rts-path}
8490 @cindex @option{--RTS} (@code{gnatmake})
8491 Specifies the default location of the runtime library. GNAT looks for the
8492 runtime
8493 in the following directories, and stops as soon as a valid runtime is found
8494 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8495 @file{ada_object_path} present):
8497 @itemize @bullet
8498 @item <current directory>/$rts_path
8500 @item <default-search-dir>/$rts_path
8502 @item <default-search-dir>/rts-$rts_path
8503 @end itemize
8505 @noindent
8506 The selected path is handled like a normal RTS path.
8508 @end table
8510 @node Mode Switches for gnatmake
8511 @section Mode Switches for @code{gnatmake}
8513 @noindent
8514 The mode switches (referred to as @code{mode_switches}) allow the
8515 inclusion of switches that are to be passed to the compiler itself, the
8516 binder or the linker. The effect of a mode switch is to cause all
8517 subsequent switches up to the end of the switch list, or up to the next
8518 mode switch, to be interpreted as switches to be passed on to the
8519 designated component of GNAT.
8521 @table @option
8522 @c !sort!
8523 @item -cargs @var{switches}
8524 @cindex @option{-cargs} (@code{gnatmake})
8525 Compiler switches. Here @var{switches} is a list of switches
8526 that are valid switches for @code{gcc}. They will be passed on to
8527 all compile steps performed by @code{gnatmake}.
8529 @item -bargs @var{switches}
8530 @cindex @option{-bargs} (@code{gnatmake})
8531 Binder switches. Here @var{switches} is a list of switches
8532 that are valid switches for @code{gnatbind}. They will be passed on to
8533 all bind steps performed by @code{gnatmake}.
8535 @item -largs @var{switches}
8536 @cindex @option{-largs} (@code{gnatmake})
8537 Linker switches. Here @var{switches} is a list of switches
8538 that are valid switches for @code{gnatlink}. They will be passed on to
8539 all link steps performed by @code{gnatmake}.
8541 @item -margs @var{switches}
8542 @cindex @option{-margs} (@code{gnatmake})
8543 Make switches. The switches are directly interpreted by @code{gnatmake},
8544 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8545 or @option{-largs}.
8546 @end table
8548 @node Notes on the Command Line
8549 @section Notes on the Command Line
8551 @noindent
8552 This section contains some additional useful notes on the operation
8553 of the @code{gnatmake} command.
8555 @itemize @bullet
8556 @item
8557 @cindex Recompilation, by @code{gnatmake}
8558 If @code{gnatmake} finds no ALI files, it recompiles the main program
8559 and all other units required by the main program.
8560 This means that @code{gnatmake}
8561 can be used for the initial compile, as well as during subsequent steps of
8562 the development cycle.
8564 @item
8565 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8566 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8567 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8568 warning.
8570 @item
8571 In @code{gnatmake} the switch @option{^-I^/SEARCH^}
8572 is used to specify both source and
8573 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8574 instead if you just want to specify
8575 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8576 if you want to specify library paths
8577 only.
8579 @item
8580 @code{gnatmake} examines both an ALI file and its corresponding object file
8581 for consistency. If an ALI is more recent than its corresponding object,
8582 or if the object file is missing, the corresponding source will be recompiled.
8583 Note that @code{gnatmake} expects an ALI and the corresponding object file
8584 to be in the same directory.
8586 @item
8587 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8588 This may conveniently be used to exclude standard libraries from
8589 consideration and in particular it means that the use of the
8590 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8591 unless @option{^-a^/ALL_FILES^} is also specified.
8593 @item
8594 @code{gnatmake} has been designed to make the use of Ada libraries
8595 particularly convenient. Assume you have an Ada library organized
8596 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8597 of your Ada compilation units,
8598 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8599 specs of these units, but no bodies. Then to compile a unit
8600 stored in @code{main.adb}, which uses this Ada library you would just type
8602 @smallexample
8603 @ifclear vms
8604 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8605 @end ifclear
8606 @ifset vms
8607 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8608            /SKIP_MISSING=@i{[OBJ_DIR]} main
8609 @end ifset
8610 @end smallexample
8612 @item
8613 Using @code{gnatmake} along with the
8614 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8615 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8616 this switch,
8617 you can update the comments/format of your
8618 source files without having to recompile everything. Note, however, that
8619 adding or deleting lines in a source files may render its debugging
8620 info obsolete. If the file in question is a spec, the impact is rather
8621 limited, as that debugging info will only be useful during the
8622 elaboration phase of your program. For bodies the impact can be more
8623 significant. In all events, your debugger will warn you if a source file
8624 is more recent than the corresponding object, and alert you to the fact
8625 that the debugging information may be out of date.
8626 @end itemize
8628 @node How gnatmake Works
8629 @section How @code{gnatmake} Works
8631 @noindent
8632 Generally @code{gnatmake} automatically performs all necessary
8633 recompilations and you don't need to worry about how it works. However,
8634 it may be useful to have some basic understanding of the @code{gnatmake}
8635 approach and in particular to understand how it uses the results of
8636 previous compilations without incorrectly depending on them.
8638 First a definition: an object file is considered @dfn{up to date} if the
8639 corresponding ALI file exists and its time stamp predates that of the
8640 object file and if all the source files listed in the
8641 dependency section of this ALI file have time stamps matching those in
8642 the ALI file. This means that neither the source file itself nor any
8643 files that it depends on have been modified, and hence there is no need
8644 to recompile this file.
8646 @code{gnatmake} works by first checking if the specified main unit is up
8647 to date. If so, no compilations are required for the main unit. If not,
8648 @code{gnatmake} compiles the main program to build a new ALI file that
8649 reflects the latest sources. Then the ALI file of the main unit is
8650 examined to find all the source files on which the main program depends,
8651 and @code{gnatmake} recursively applies the above procedure on all these files.
8653 This process ensures that @code{gnatmake} only trusts the dependencies
8654 in an existing ALI file if they are known to be correct. Otherwise it
8655 always recompiles to determine a new, guaranteed accurate set of
8656 dependencies. As a result the program is compiled ``upside down'' from what may
8657 be more familiar as the required order of compilation in some other Ada
8658 systems. In particular, clients are compiled before the units on which
8659 they depend. The ability of GNAT to compile in any order is critical in
8660 allowing an order of compilation to be chosen that guarantees that
8661 @code{gnatmake} will recompute a correct set of new dependencies if
8662 necessary.
8664 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
8665 imported by several of the executables, it will be recompiled at most once.
8667 Note: when using non-standard naming conventions
8668 (See @ref{Using Other File Names}), changing through a configuration pragmas
8669 file the version of a source and invoking @code{gnatmake} to recompile may
8670 have no effect, if the previous version of the source is still accessible
8671 by @code{gnatmake}. It may be necessary to use the switch ^-f^/FORCE_COMPILE^.
8673 @node Examples of gnatmake Usage
8674 @section Examples of @code{gnatmake} Usage
8676 @table @code
8677 @item gnatmake hello.adb
8678 Compile all files necessary to bind and link the main program
8679 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8680 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8682 @item gnatmake main1 main2 main3
8683 Compile all files necessary to bind and link the main programs
8684 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8685 (containing unit @code{Main2}) and @file{main3.adb}
8686 (containing unit @code{Main3}) and bind and link the resulting object files
8687 to generate three executable files @file{^main1^MAIN1.EXE^},
8688 @file{^main2^MAIN2.EXE^}
8689 and @file{^main3^MAIN3.EXE^}.
8691 @ifclear vms
8692 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8693 @end ifclear
8695 @ifset vms
8696 @item gnatmake Main_Unit /QUIET
8697    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8698    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8699 @end ifset
8700 Compile all files necessary to bind and link the main program unit
8701 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8702 be done with optimization level 2 and the order of elaboration will be
8703 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8704 displaying commands it is executing.
8705 @end table
8708 @c *************************
8709 @node Improving Performance
8710 @chapter Improving Performance
8711 @cindex Improving performance
8713 @noindent
8714 This chapter presents several topics related to program performance.
8715 It first describes some of the tradeoffs that need to be considered
8716 and some of the techniques for making your program run faster.
8717 It then documents the @command{gnatelim} tool, which can reduce
8718 the size of program executables.
8720 @ifnottex
8721 @menu
8722 * Performance Considerations::
8723 * Reducing the Size of Ada Executables with gnatelim::
8724 @end menu
8725 @end ifnottex
8728 @c *****************************
8729 @node Performance Considerations
8730 @section Performance Considerations
8732 @noindent
8733 The GNAT system provides a number of options that allow a trade-off
8734 between
8736 @itemize @bullet
8737 @item
8738 performance of the generated code
8740 @item
8741 speed of compilation
8743 @item
8744 minimization of dependences and recompilation
8746 @item
8747 the degree of run-time checking.
8748 @end itemize
8750 @noindent
8751 The defaults (if no options are selected) aim at improving the speed
8752 of compilation and minimizing dependences, at the expense of performance
8753 of the generated code:
8755 @itemize @bullet
8756 @item
8757 no optimization
8759 @item
8760 no inlining of subprogram calls
8762 @item
8763 all run-time checks enabled except overflow and elaboration checks
8764 @end itemize
8766 @noindent
8767 These options are suitable for most program development purposes. This
8768 chapter describes how you can modify these choices, and also provides
8769 some guidelines on debugging optimized code.
8771 @menu
8772 * Controlling Run-Time Checks::
8773 * Use of Restrictions::
8774 * Optimization Levels::
8775 * Debugging Optimized Code::
8776 * Inlining of Subprograms::
8777 * Optimization and Strict Aliasing::
8778 @ifset vms
8779 * Coverage Analysis::
8780 @end ifset
8781 @end menu
8783 @node Controlling Run-Time Checks
8784 @subsection Controlling Run-Time Checks
8786 @noindent
8787 By default, GNAT generates all run-time checks, except arithmetic overflow
8788 checking for integer operations and checks for access before elaboration on
8789 subprogram calls. The latter are not required in default mode, because all
8790 necessary checking is done at compile time.
8791 @cindex @option{-gnatp} (@code{gcc})
8792 @cindex @option{-gnato} (@code{gcc})
8793 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8794 be modified. @xref{Run-Time Checks}.
8796 Our experience is that the default is suitable for most development
8797 purposes.
8799 We treat integer overflow specially because these
8800 are quite expensive and in our experience are not as important as other
8801 run-time checks in the development process. Note that division by zero
8802 is not considered an overflow check, and divide by zero checks are
8803 generated where required by default.
8805 Elaboration checks are off by default, and also not needed by default, since
8806 GNAT uses a static elaboration analysis approach that avoids the need for
8807 run-time checking. This manual contains a full chapter discussing the issue
8808 of elaboration checks, and if the default is not satisfactory for your use,
8809 you should read this chapter.
8811 For validity checks, the minimal checks required by the Ada Reference
8812 Manual (for case statements and assignments to array elements) are on
8813 by default. These can be suppressed by use of the @option{-gnatVn} switch.
8814 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8815 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8816 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8817 are also suppressed entirely if @option{-gnatp} is used.
8819 @cindex Overflow checks
8820 @cindex Checks, overflow
8821 @findex Suppress
8822 @findex Unsuppress
8823 @cindex pragma Suppress
8824 @cindex pragma Unsuppress
8825 Note that the setting of the switches controls the default setting of
8826 the checks. They may be modified using either @code{pragma Suppress} (to
8827 remove checks) or @code{pragma Unsuppress} (to add back suppressed
8828 checks) in the program source.
8830 @node Use of Restrictions
8831 @subsection Use of Restrictions
8833 @noindent
8834 The use of pragma Restrictions allows you to control which features are
8835 permitted in your program. Apart from the obvious point that if you avoid
8836 relatively expensive features like finalization (enforceable by the use
8837 of pragma Restrictions (No_Finalization), the use of this pragma does not
8838 affect the generated code in most cases.
8840 One notable exception to this rule is that the possibility of task abort
8841 results in some distributed overhead, particularly if finalization or
8842 exception handlers are used. The reason is that certain sections of code
8843 have to be marked as non-abortable.
8845 If you use neither the @code{abort} statement, nor asynchronous transfer
8846 of control (@code{select .. then abort}), then this distributed overhead
8847 is removed, which may have a general positive effect in improving
8848 overall performance.  Especially code involving frequent use of tasking
8849 constructs and controlled types will show much improved performance.
8850 The relevant restrictions pragmas are
8852 @smallexample
8853    pragma Restrictions (No_Abort_Statements);
8854    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
8855 @end smallexample
8857 @noindent
8858 It is recommended that these restriction pragmas be used if possible. Note
8859 that this also means that you can write code without worrying about the
8860 possibility of an immediate abort at any point.
8862 @node Optimization Levels
8863 @subsection Optimization Levels
8864 @cindex @option{^-O^/OPTIMIZE^} (@code{gcc})
8866 @noindent
8867 The default is optimization off. This results in the fastest compile
8868 times, but GNAT makes absolutely no attempt to optimize, and the
8869 generated programs are considerably larger and slower than when
8870 optimization is enabled. You can use the
8871 @ifclear vms
8872 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
8873 @end ifclear
8874 @ifset vms
8875 @code{OPTIMIZE} qualifier
8876 @end ifset
8877 to @code{gcc} to control the optimization level:
8879 @table @option
8880 @item ^-O0^/OPTIMIZE=NONE^
8881 No optimization (the default);
8882 generates unoptimized code but has
8883 the fastest compilation time.
8885 @item ^-O1^/OPTIMIZE=SOME^
8886 Medium level optimization;
8887 optimizes reasonably well but does not
8888 degrade compilation time significantly.
8890 @item ^-O2^/OPTIMIZE=ALL^
8891 @ifset vms
8892 @itemx /OPTIMIZE=DEVELOPMENT
8893 @end ifset
8894 Full optimization;
8895 generates highly optimized code and has
8896 the slowest compilation time.
8898 @item ^-O3^/OPTIMIZE=INLINING^
8899 Full optimization as in @option{-O2},
8900 and also attempts automatic inlining of small
8901 subprograms within a unit (@pxref{Inlining of Subprograms}).
8902 @end table
8904 @noindent
8905 Higher optimization levels perform more global transformations on the
8906 program and apply more expensive analysis algorithms in order to generate
8907 faster and more compact code. The price in compilation time, and the
8908 resulting improvement in execution time,
8909 both depend on the particular application and the hardware environment.
8910 You should experiment to find the best level for your application.
8912 Since the precise set of optimizations done at each level will vary from
8913 release to release (and sometime from target to target), it is best to think
8914 of the optimization settings in general terms.
8915 The @cite{Using GNU GCC} manual contains details about
8916 ^the @option{-O} settings and a number of @option{-f} options that^how to^
8917 individually enable or disable specific optimizations.
8919 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
8920 been tested extensively at all optimization levels. There are some bugs
8921 which appear only with optimization turned on, but there have also been
8922 bugs which show up only in @emph{unoptimized} code. Selecting a lower
8923 level of optimization does not improve the reliability of the code
8924 generator, which in practice is highly reliable at all optimization
8925 levels.
8927 Note regarding the use of @option{-O3}: The use of this optimization level
8928 is generally discouraged with GNAT, since it often results in larger
8929 executables which run more slowly. See further discussion of this point
8930 in @pxref{Inlining of Subprograms}.
8933 @node Debugging Optimized Code
8934 @subsection Debugging Optimized Code
8935 @cindex Debugging optimized code
8936 @cindex Optimization and debugging
8938 @noindent
8939 Although it is possible to do a reasonable amount of debugging at
8940 @ifclear vms
8941 non-zero optimization levels,
8942 the higher the level the more likely that
8943 @end ifclear
8944 @ifset vms
8945 @option{/OPTIMIZE} settings other than @code{NONE},
8946 such settings will make it more likely that
8947 @end ifset
8948 source-level constructs will have been eliminated by optimization.
8949 For example, if a loop is strength-reduced, the loop
8950 control variable may be completely eliminated and thus cannot be
8951 displayed in the debugger.
8952 This can only happen at @option{-O2} or @option{-O3}.
8953 Explicit temporary variables that you code might be eliminated at
8954 ^level^setting^ @option{-O1} or higher.
8956 The use of the @option{^-g^/DEBUG^} switch,
8957 @cindex @option{^-g^/DEBUG^} (@code{gcc})
8958 which is needed for source-level debugging,
8959 affects the size of the program executable on disk,
8960 and indeed the debugging information can be quite large.
8961 However, it has no effect on the generated code (and thus does not
8962 degrade performance)
8964 Since the compiler generates debugging tables for a compilation unit before
8965 it performs optimizations, the optimizing transformations may invalidate some
8966 of the debugging data.  You therefore need to anticipate certain
8967 anomalous situations that may arise while debugging optimized code.
8968 These are the most common cases:
8970 @enumerate
8971 @item
8972 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
8973 commands show
8974 the PC bouncing back and forth in the code.  This may result from any of
8975 the following optimizations:
8977 @itemize @bullet
8978 @item
8979 @i{Common subexpression elimination:} using a single instance of code for a
8980 quantity that the source computes several times.  As a result you
8981 may not be able to stop on what looks like a statement.
8983 @item
8984 @i{Invariant code motion:} moving an expression that does not change within a
8985 loop, to the beginning of the loop.
8987 @item
8988 @i{Instruction scheduling:} moving instructions so as to
8989 overlap loads and stores (typically) with other code, or in
8990 general to move computations of values closer to their uses. Often
8991 this causes you to pass an assignment statement without the assignment
8992 happening and then later bounce back to the statement when the
8993 value is actually needed.  Placing a breakpoint on a line of code
8994 and then stepping over it may, therefore, not always cause all the
8995 expected side-effects.
8996 @end itemize
8998 @item
8999 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9000 two identical pieces of code are merged and the program counter suddenly
9001 jumps to a statement that is not supposed to be executed, simply because
9002 it (and the code following) translates to the same thing as the code
9003 that @emph{was} supposed to be executed.  This effect is typically seen in
9004 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9005 a @code{break} in a C @code{^switch^switch^} statement.
9007 @item
9008 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9009 There are various reasons for this effect:
9011 @itemize @bullet
9012 @item
9013 In a subprogram prologue, a parameter may not yet have been moved to its
9014 ``home''.
9016 @item
9017 A variable may be dead, and its register re-used.  This is
9018 probably the most common cause.
9020 @item
9021 As mentioned above, the assignment of a value to a variable may
9022 have been moved.
9024 @item
9025 A variable may be eliminated entirely by value propagation or
9026 other means.  In this case, GCC may incorrectly generate debugging
9027 information for the variable
9028 @end itemize
9030 @noindent
9031 In general, when an unexpected value appears for a local variable or parameter
9032 you should first ascertain if that value was actually computed by
9033 your program, as opposed to being incorrectly reported by the debugger.
9034 Record fields or
9035 array elements in an object designated by an access value
9036 are generally less of a problem, once you have ascertained that the access
9037 value is sensible.
9038 Typically, this means checking variables in the preceding code and in the
9039 calling subprogram to verify that the value observed is explainable from other
9040 values (one must apply the procedure recursively to those
9041 other values); or re-running the code and stopping a little earlier
9042 (perhaps before the call) and stepping to better see how the variable obtained
9043 the value in question; or continuing to step @emph{from} the point of the
9044 strange value to see if code motion had simply moved the variable's
9045 assignments later.
9046 @end enumerate
9048 @noindent
9049 In light of such anomalies, a recommended technique is to use @option{-O0}
9050 early in the software development cycle, when extensive debugging capabilities
9051 are most needed, and then move to @option{-O1} and later @option{-O2} as
9052 the debugger becomes less critical.
9053 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9054 a release management issue.
9055 @ifclear vms
9056 Note that if you use @option{-g} you can then use the @command{strip} program
9057 on the resulting executable,
9058 which removes both debugging information and global symbols.
9059 @end ifclear
9062 @node Inlining of Subprograms
9063 @subsection Inlining of Subprograms
9065 @noindent
9066 A call to a subprogram in the current unit is inlined if all the
9067 following conditions are met:
9069 @itemize @bullet
9070 @item
9071 The optimization level is at least @option{-O1}.
9073 @item
9074 The called subprogram is suitable for inlining: It must be small enough
9075 and not contain nested subprograms or anything else that @code{gcc}
9076 cannot support in inlined subprograms.
9078 @item
9079 The call occurs after the definition of the body of the subprogram.
9081 @item
9082 @cindex pragma Inline
9083 @findex Inline
9084 Either @code{pragma Inline} applies to the subprogram or it is
9085 small and automatic inlining (optimization level @option{-O3}) is
9086 specified.
9087 @end itemize
9089 @noindent
9090 Calls to subprograms in @code{with}'ed units are normally not inlined.
9091 To achieve this level of inlining, the following conditions must all be
9092 true:
9094 @itemize @bullet
9095 @item
9096 The optimization level is at least @option{-O1}.
9098 @item
9099 The called subprogram is suitable for inlining: It must be small enough
9100 and not contain nested subprograms or anything else @code{gcc} cannot
9101 support in inlined subprograms.
9103 @item
9104 The call appears in a body (not in a package spec).
9106 @item
9107 There is a @code{pragma Inline} for the subprogram.
9109 @item
9110 @cindex @option{-gnatn} (@code{gcc})
9111 The @option{^-gnatn^/INLINE^} switch
9112 is used in the @code{gcc} command line
9113 @end itemize
9115 Note that specifying the @option{-gnatn} switch causes additional
9116 compilation dependencies. Consider the following:
9118 @smallexample @c ada
9119 @cartouche
9120 package R is
9121    procedure Q;
9122    pragma Inline (Q);
9123 end R;
9124 package body R is
9125    ...
9126 end R;
9128 with R;
9129 procedure Main is
9130 begin
9131    ...
9132    R.Q;
9133 end Main;
9134 @end cartouche
9135 @end smallexample
9137 @noindent
9138 With the default behavior (no @option{-gnatn} switch specified), the
9139 compilation of the @code{Main} procedure depends only on its own source,
9140 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9141 means that editing the body of @code{R} does not require recompiling
9142 @code{Main}.
9144 On the other hand, the call @code{R.Q} is not inlined under these
9145 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9146 is compiled, the call will be inlined if the body of @code{Q} is small
9147 enough, but now @code{Main} depends on the body of @code{R} in
9148 @file{r.adb} as well as on the spec. This means that if this body is edited,
9149 the main program must be recompiled. Note that this extra dependency
9150 occurs whether or not the call is in fact inlined by @code{gcc}.
9152 The use of front end inlining with @option{-gnatN} generates similar
9153 additional dependencies.
9155 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@code{gcc})
9156 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9157 can be used to prevent
9158 all inlining. This switch overrides all other conditions and ensures
9159 that no inlining occurs. The extra dependences resulting from
9160 @option{-gnatn} will still be active, even if
9161 this switch is used to suppress the resulting inlining actions.
9163 Note regarding the use of @option{-O3}: There is no difference in inlining
9164 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9165 pragma @code{Inline} assuming the use of @option{-gnatn}
9166 or @option{-gnatN} (the switches that activate inlining). If you have used
9167 pragma @code{Inline} in appropriate cases, then it is usually much better
9168 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9169 in this case only has the effect of inlining subprograms you did not
9170 think should be inlined. We often find that the use of @option{-O3} slows
9171 down code by performing excessive inlining, leading to increased instruction
9172 cache pressure from the increased code size. So the bottom line here is
9173 that you should not automatically assume that @option{-O3} is better than
9174 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9175 it actually improves performance.
9177 @node Optimization and Strict Aliasing
9178 @subsection Optimization and Strict Aliasing
9179 @cindex Aliasing
9180 @cindex Strict Aliasing
9181 @cindex No_Strict_Aliasing
9183 @noindent
9184 The strong typing capabilities of Ada allow an optimizer to generate
9185 efficient code in situations where other languages would be forced to
9186 make worst case assumptions preventing such optimizations. Consider
9187 the following example:
9189 @smallexample @c ada
9190 @cartouche
9191 procedure R is
9192    type Int1 is new Integer;
9193    type Int2 is new Integer;
9194    type Int1A is access Int1;
9195    type Int2A is access Int2;
9196    Int1V : Int1A;
9197    Int2V : Int2A;
9198    ...
9200 begin
9201    ...
9202    for J in Data'Range loop
9203       if Data (J) = Int1V.all then
9204          Int2V.all := Int2V.all + 1;
9205       end if;
9206    end loop;
9207    ...
9208 end R;
9209 @end cartouche
9210 @end smallexample
9212 @noindent
9213 In this example, since the variable @code{Int1V} can only access objects
9214 of type @code{Int1}, and @code{Int2V} can only access objects of type
9215 @code{Int2}, there is no possibility that the assignment to
9216 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9217 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9218 for all iterations of the loop and avoid the extra memory reference
9219 required to dereference it each time through the loop.
9221 This kind of optimziation, called strict aliasing analysis, is
9222 triggered by specifying an optimization level of @option{-O2} or
9223 higher and allows @code{GNAT} to generate more efficient code
9224 when access values are involved.
9226 However, although this optimization is always correct in terms of
9227 the formal semantics of the Ada Reference Manual, difficulties can
9228 arise if features like @code{Unchecked_Conversion} are used to break
9229 the typing system. Consider the following complete program example:
9231 @smallexample @c ada
9232 @cartouche
9233 package p1 is
9234    type int1 is new integer;
9235    type int2 is new integer;
9236    type a1 is access int1;
9237    type a2 is access int2;
9238 end p1;
9240 with p1; use p1;
9241 package p2 is
9242    function to_a2 (Input : a1) return a2;
9243 end p2;
9245 with Unchecked_Conversion;
9246 package body p2 is
9247    function to_a2 (Input : a1) return a2 is
9248       function to_a2u is
9249         new Unchecked_Conversion (a1, a2);
9250    begin
9251       return to_a2u (Input);
9252    end to_a2;
9253 end p2;
9255 with p2; use p2;
9256 with p1; use p1;
9257 with Text_IO; use Text_IO;
9258 procedure m is
9259    v1 : a1 := new int1;
9260    v2 : a2 := to_a2 (v1);
9261 begin
9262    v1.all := 1;
9263    v2.all := 0;
9264    put_line (int1'image (v1.all));
9265 end;
9266 @end cartouche
9267 @end smallexample
9269 @noindent
9270 This program prints out 0 in @code{-O0} or @code{-O1}
9271 mode, but it prints out 1 in @code{-O2} mode. That's
9272 because in strict aliasing mode, the compiler can and
9273 does assume that the assignment to @code{v2.all} could not
9274 affect the value of @code{v1.all}, since different types
9275 are involved.
9277 This behavior is not a case of non-conformance with the standard, since
9278 the Ada RM specifies that an unchecked conversion where the resulting
9279 bit pattern is not a correct value of the target type can result in an
9280 abnormal value and attempting to reference an abnormal value makes the
9281 execution of a program erroneous.  That's the case here since the result
9282 does not point to an object of type @code{int2}.  This means that the
9283 effect is entirely unpredictable.
9285 However, although that explanation may satisfy a language
9286 lawyer, in practice an applications programmer expects an
9287 unchecked conversion involving pointers to create true
9288 aliases and the behavior of printing 1 seems plain wrong.
9289 In this case, the strict aliasing optimization is unwelcome.
9291 Indeed the compiler recognizes this possibility, and the
9292 unchecked conversion generates a warning:
9294 @smallexample
9295 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9296 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9297 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9298 @end smallexample
9300 @noindent
9301 Unfortunately the problem is recognized when compiling the body of
9302 package @code{p2}, but the actual "bad" code is generated while
9303 compiling the body of @code{m} and this latter compilation does not see
9304 the suspicious @code{Unchecked_Conversion}.
9306 As implied by the warning message, there are approaches you can use to
9307 avoid the unwanted strict aliasing optimization in a case like this.
9309 One possibility is to simply avoid the use of @code{-O2}, but
9310 that is a bit drastic, since it throws away a number of useful
9311 optimizations that do not involve strict aliasing assumptions.
9313 A less drastic approach is to compile the program using the
9314 option @code{-fno-strict-aliasing}. Actually it is only the
9315 unit containing the dereferencing of the suspicious pointer
9316 that needs to be compiled. So in this case, if we compile
9317 unit @code{m} with this switch, then we get the expected
9318 value of zero printed. Analyzing which units might need
9319 the switch can be painful, so a more reasonable approach
9320 is to compile the entire program with options @code{-O2}
9321 and @code{-fno-strict-aliasing}. If the performance is
9322 satisfactory with this combination of options, then the
9323 advantage is that the entire issue of possible "wrong"
9324 optimization due to strict aliasing is avoided.
9326 To avoid the use of compiler switches, the configuration
9327 pragma @code{No_Strict_Aliasing} with no parameters may be
9328 used to specify that for all access types, the strict
9329 aliasing optimization should be suppressed.
9331 However, these approaches are still overkill, in that they causes
9332 all manipulations of all access values to be deoptimized. A more
9333 refined approach is to concentrate attention on the specific
9334 access type identified as problematic.
9336 First, if a careful analysis of uses of the pointer shows
9337 that there are no possible problematic references, then
9338 the warning can be suppressed by bracketing the
9339 instantiation of @code{Unchecked_Conversion} to turn
9340 the warning off:
9342 @smallexample @c ada
9343    pragma Warnings (Off);
9344    function to_a2u is
9345      new Unchecked_Conversion (a1, a2);
9346    pragma Warnings (On);
9347 @end smallexample
9349 @noindent
9350 Of course that approach is not appropriate for this particular
9351 example, since indeed there is a problematic reference. In this
9352 case we can take one of two other approaches.
9354 The first possibility is to move the instantiation of unchecked
9355 conversion to the unit in which the type is declared. In
9356 this example, we would move the instantiation of
9357 @code{Unchecked_Conversion} from the body of package
9358 @code{p2} to the spec of package @code{p1}. Now the
9359 warning disappears. That's because any use of the
9360 access type knows there is a suspicious unchecked
9361 conversion, and the strict aliasing optimization
9362 is automatically suppressed for the type.
9364 If it is not practical to move the unchecked conversion to the same unit
9365 in which the destination access type is declared (perhaps because the
9366 source type is not visible in that unit), you may use pragma
9367 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9368 same declarative sequence as the declaration of the access type:
9370 @smallexample @c ada
9371    type a2 is access int2;
9372    pragma No_Strict_Aliasing (a2);
9373 @end smallexample
9375 @noindent
9376 Here again, the compiler now knows that the strict aliasing optimization
9377 should be suppressed for any reference to type @code{a2} and the
9378 expected behavior is obtained.
9380 Finally, note that although the compiler can generate warnings for
9381 simple cases of unchecked conversions, there are tricker and more
9382 indirect ways of creating type incorrect aliases which the compiler
9383 cannot detect. Examples are the use of address overlays and unchecked
9384 conversions involving composite types containing access types as
9385 components. In such cases, no warnings are generated, but there can
9386 still be aliasing problems. One safe coding practice is to forbid the
9387 use of address clauses for type overlaying, and to allow unchecked
9388 conversion only for primitive types. This is not really a significant
9389 restriction since any possible desired effect can be achieved by
9390 unchecked conversion of access values.
9392 @ifset vms
9393 @node Coverage Analysis
9394 @subsection Coverage Analysis
9396 @noindent
9397 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
9398 the user to determine the distribution of execution time across a program,
9399 @pxref{Profiling} for details of usage.
9400 @end ifset
9402 @node Reducing the Size of Ada Executables with gnatelim
9403 @section Reducing the Size of Ada Executables with @code{gnatelim}
9404 @findex gnatelim
9406 @noindent
9407 This section describes @command{gnatelim}, a tool which detects unused
9408 subprograms and helps the compiler to create a smaller executable for your
9409 program.
9411 @menu
9412 * About gnatelim::
9413 * Running gnatelim::
9414 * Correcting the List of Eliminate Pragmas::
9415 * Making Your Executables Smaller::
9416 * Summary of the gnatelim Usage Cycle::
9417 @end menu
9419 @node About gnatelim
9420 @subsection About @code{gnatelim}
9422 @noindent
9423 When a program shares a set of Ada
9424 packages with other programs, it may happen that this program uses
9425 only a fraction of the subprograms defined in these packages. The code
9426 created for these unused subprograms increases the size of the executable.
9428 @code{gnatelim} tracks unused subprograms in an Ada program and
9429 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9430 subprograms that are declared but never called. By placing the list of
9431 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9432 recompiling your program, you may decrease the size of its executable,
9433 because the compiler will not generate the code for 'eliminated' subprograms.
9434 See GNAT Reference Manual for more information about this pragma.
9436 @code{gnatelim} needs as its input data the name of the main subprogram
9437 and a bind file for a main subprogram.
9439 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9440 the main subprogram. @code{gnatelim} can work with both Ada and C
9441 bind files; when both are present, it uses the Ada bind file.
9442 The following commands will build the program and create the bind file:
9444 @smallexample
9445 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9446 $ gnatbind main_prog
9447 @end smallexample
9449 Note that @code{gnatelim} needs neither object nor ALI files.
9451 @node Running gnatelim
9452 @subsection Running @code{gnatelim}
9454 @noindent
9455 @code{gnatelim} has the following command-line interface:
9457 @smallexample
9458 $ gnatelim [options] name
9459 @end smallexample
9461 @noindent
9462 @code{name} should be a name of a source file that contains the main subprogram
9463 of a program (partition).
9465 @code{gnatelim} has the following switches:
9467 @table @option
9468 @c !sort!
9469 @item ^-q^/QUIET^
9470 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9471 Quiet mode: by default @code{gnatelim} outputs to the standard error
9472 stream the number of program units left to be processed. This option turns
9473 this trace off.
9475 @item ^-v^/VERBOSE^
9476 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9477 Verbose mode: @code{gnatelim} version information is printed as Ada
9478 comments to the standard output stream. Also, in addition to the number of
9479 program units left @code{gnatelim} will output the name of the current unit
9480 being processed.
9482 @item ^-a^/ALL^
9483 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9484 Also look for subprograms from the GNAT run time that can be eliminated. Note
9485 that when @file{gnat.adc} is produced using this switch, the entire program
9486 must be recompiled with switch @option{^-a^/ALL_FILES^} to @code{gnatmake}.
9488 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9489 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9490 When looking for source files also look in directory @var{dir}. Specifying
9491 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9492 sources in the current directory.
9494 @item ^-b^/BIND_FILE=^@var{bind_file}
9495 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9496 Specifies @var{bind_file} as the bind file to process. If not set, the name
9497 of the bind file is computed from the full expanded Ada name
9498 of a main subprogram.
9500 @item ^-C^/CONFIG_FILE=^@var{config_file}
9501 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9502 Specifies a file @var{config_file} that contains configuration pragmas. The
9503 file must be specified with full path.
9505 @item ^--GCC^/COMPILER^=@var{compiler_name}
9506 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9507 Instructs @code{gnatelim} to use specific @code{gcc} compiler instead of one
9508 available on the path.
9510 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9511 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9512 Instructs @code{gnatelim} to use specific @code{gnatmake} instead of one
9513 available on the path.
9515 @item -d@var{x}
9516 @cindex @option{-d@var{x}} (@command{gnatelim})
9517 Activate internal debugging switches. @var{x} is a letter or digit, or
9518 string of letters or digits, which specifies the type of debugging
9519 mode desired.  Normally these are used only for internal development
9520 or system debugging purposes. You can find full documentation for these
9521 switches in the spec of the @code{Gnatelim} unit in the compiler
9522 source file @file{gnatelim.ads}.
9523 @end table
9525 @noindent
9526 @code{gnatelim} sends its output to the standard output stream, and all the
9527 tracing and debug information is sent to the standard error stream.
9528 In order to produce a proper GNAT configuration file
9529 @file{gnat.adc}, redirection must be used:
9531 @smallexample
9532 @ifset vms
9533 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9534 @end ifset
9535 @ifclear vms
9536 $ gnatelim main_prog.adb > gnat.adc
9537 @end ifclear
9538 @end smallexample
9540 @ifclear vms
9541 @noindent
9544 @smallexample
9545 $ gnatelim main_prog.adb >> gnat.adc
9546 @end smallexample
9548 @noindent
9549 in order to append the @code{gnatelim} output to the existing contents of
9550 @file{gnat.adc}.
9551 @end ifclear
9553 @node Correcting the List of Eliminate Pragmas
9554 @subsection Correcting the List of Eliminate Pragmas
9556 @noindent
9557 In some rare cases @code{gnatelim} may try to eliminate
9558 subprograms that are actually called in the program. In this case, the
9559 compiler will generate an error message of the form:
9561 @smallexample
9562 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9563 @end smallexample
9565 @noindent
9566 You will need to manually remove the wrong @code{Eliminate} pragmas from
9567 the @file{gnat.adc} file. You should recompile your program
9568 from scratch after that, because you need a consistent @file{gnat.adc} file
9569 during the entire compilation.
9572 @node Making Your Executables Smaller
9573 @subsection Making Your Executables Smaller
9575 @noindent
9576 In order to get a smaller executable for your program you now have to
9577 recompile the program completely with the new @file{gnat.adc} file
9578 created by @code{gnatelim} in your current directory:
9580 @smallexample
9581 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9582 @end smallexample
9584 @noindent
9585 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9586 recompile everything
9587 with the set of pragmas @code{Eliminate} that you have obtained with
9588 @command{gnatelim}).
9590 Be aware that the set of @code{Eliminate} pragmas is specific to each
9591 program. It is not recommended to merge sets of @code{Eliminate}
9592 pragmas created for different programs in one @file{gnat.adc} file.
9594 @node Summary of the gnatelim Usage Cycle
9595 @subsection Summary of the gnatelim Usage Cycle
9597 @noindent
9598 Here is a quick summary of the steps to be taken in order to reduce
9599 the size of your executables with @code{gnatelim}. You may use
9600 other GNAT options to control the optimization level,
9601 to produce the debugging information, to set search path, etc.
9603 @enumerate
9604 @item
9605 Produce a bind file
9607 @smallexample
9608 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9609 $ gnatbind main_prog
9610 @end smallexample
9612 @item
9613 Generate a list of @code{Eliminate} pragmas
9614 @smallexample
9615 @ifset vms
9616 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9617 @end ifset
9618 @ifclear vms
9619 $ gnatelim main_prog >[>] gnat.adc
9620 @end ifclear
9621 @end smallexample
9623 @item
9624 Recompile the application
9626 @smallexample
9627 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9628 @end smallexample
9630 @end enumerate
9635 @c ********************************
9636 @node Renaming Files Using gnatchop
9637 @chapter Renaming Files Using @code{gnatchop}
9638 @findex gnatchop
9640 @noindent
9641 This chapter discusses how to handle files with multiple units by using
9642 the @code{gnatchop} utility. This utility is also useful in renaming
9643 files to meet the standard GNAT default file naming conventions.
9645 @menu
9646 * Handling Files with Multiple Units::
9647 * Operating gnatchop in Compilation Mode::
9648 * Command Line for gnatchop::
9649 * Switches for gnatchop::
9650 * Examples of gnatchop Usage::
9651 @end menu
9653 @node Handling Files with Multiple Units
9654 @section Handling Files with Multiple Units
9656 @noindent
9657 The basic compilation model of GNAT requires that a file submitted to the
9658 compiler have only one unit and there be a strict correspondence
9659 between the file name and the unit name.
9661 The @code{gnatchop} utility allows both of these rules to be relaxed,
9662 allowing GNAT to process files which contain multiple compilation units
9663 and files with arbitrary file names. @code{gnatchop}
9664 reads the specified file and generates one or more output files,
9665 containing one unit per file. The unit and the file name correspond,
9666 as required by GNAT.
9668 If you want to permanently restructure a set of ``foreign'' files so that
9669 they match the GNAT rules, and do the remaining development using the
9670 GNAT structure, you can simply use @command{gnatchop} once, generate the
9671 new set of files and work with them from that point on.
9673 Alternatively, if you want to keep your files in the ``foreign'' format,
9674 perhaps to maintain compatibility with some other Ada compilation
9675 system, you can set up a procedure where you use @command{gnatchop} each
9676 time you compile, regarding the source files that it writes as temporary
9677 files that you throw away.
9680 @node Operating gnatchop in Compilation Mode
9681 @section Operating gnatchop in Compilation Mode
9683 @noindent
9684 The basic function of @code{gnatchop} is to take a file with multiple units
9685 and split it into separate files. The boundary between files is reasonably
9686 clear, except for the issue of comments and pragmas. In default mode, the
9687 rule is that any pragmas between units belong to the previous unit, except
9688 that configuration pragmas always belong to the following unit. Any comments
9689 belong to the following unit. These rules
9690 almost always result in the right choice of
9691 the split point without needing to mark it explicitly and most users will
9692 find this default to be what they want. In this default mode it is incorrect to
9693 submit a file containing only configuration pragmas, or one that ends in
9694 configuration pragmas, to @code{gnatchop}.
9696 However, using a special option to activate ``compilation mode'',
9697 @code{gnatchop}
9698 can perform another function, which is to provide exactly the semantics
9699 required by the RM for handling of configuration pragmas in a compilation.
9700 In the absence of configuration pragmas (at the main file level), this
9701 option has no effect, but it causes such configuration pragmas to be handled
9702 in a quite different manner.
9704 First, in compilation mode, if @code{gnatchop} is given a file that consists of
9705 only configuration pragmas, then this file is appended to the
9706 @file{gnat.adc} file in the current directory. This behavior provides
9707 the required behavior described in the RM for the actions to be taken
9708 on submitting such a file to the compiler, namely that these pragmas
9709 should apply to all subsequent compilations in the same compilation
9710 environment. Using GNAT, the current directory, possibly containing a
9711 @file{gnat.adc} file is the representation
9712 of a compilation environment. For more information on the
9713 @file{gnat.adc} file, see the section on handling of configuration
9714 pragmas @pxref{Handling of Configuration Pragmas}.
9716 Second, in compilation mode, if @code{gnatchop}
9717 is given a file that starts with
9718 configuration pragmas, and contains one or more units, then these
9719 configuration pragmas are prepended to each of the chopped files. This
9720 behavior provides the required behavior described in the RM for the
9721 actions to be taken on compiling such a file, namely that the pragmas
9722 apply to all units in the compilation, but not to subsequently compiled
9723 units.
9725 Finally, if configuration pragmas appear between units, they are appended
9726 to the previous unit. This results in the previous unit being illegal,
9727 since the compiler does not accept configuration pragmas that follow
9728 a unit. This provides the required RM behavior that forbids configuration
9729 pragmas other than those preceding the first compilation unit of a
9730 compilation.
9732 For most purposes, @code{gnatchop} will be used in default mode. The
9733 compilation mode described above is used only if you need exactly
9734 accurate behavior with respect to compilations, and you have files
9735 that contain multiple units and configuration pragmas. In this
9736 circumstance the use of @code{gnatchop} with the compilation mode
9737 switch provides the required behavior, and is for example the mode
9738 in which GNAT processes the ACVC tests.
9740 @node Command Line for gnatchop
9741 @section Command Line for @code{gnatchop}
9743 @noindent
9744 The @code{gnatchop} command has the form:
9746 @smallexample
9747 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9748       [@var{directory}]
9749 @end smallexample
9751 @noindent
9752 The only required argument is the file name of the file to be chopped.
9753 There are no restrictions on the form of this file name. The file itself
9754 contains one or more Ada units, in normal GNAT format, concatenated
9755 together. As shown, more than one file may be presented to be chopped.
9757 When run in default mode, @code{gnatchop} generates one output file in
9758 the current directory for each unit in each of the files.
9760 @var{directory}, if specified, gives the name of the directory to which
9761 the output files will be written. If it is not specified, all files are
9762 written to the current directory.
9764 For example, given a
9765 file called @file{hellofiles} containing
9767 @smallexample @c ada
9768 @group
9769 @cartouche
9770 procedure hello;
9772 with Text_IO; use Text_IO;
9773 procedure hello is
9774 begin
9775    Put_Line ("Hello");
9776 end hello;
9777 @end cartouche
9778 @end group
9779 @end smallexample
9781 @noindent
9782 the command
9784 @smallexample
9785 $ gnatchop ^hellofiles^HELLOFILES.^
9786 @end smallexample
9788 @noindent
9789 generates two files in the current directory, one called
9790 @file{hello.ads} containing the single line that is the procedure spec,
9791 and the other called @file{hello.adb} containing the remaining text. The
9792 original file is not affected. The generated files can be compiled in
9793 the normal manner.
9795 @noindent
9796 When gnatchop is invoked on a file that is empty or that contains only empty
9797 lines and/or comments, gnatchop will not fail, but will not produce any
9798 new sources.
9800 For example, given a
9801 file called @file{toto.txt} containing
9803 @smallexample @c ada
9804 @group
9805 @cartouche
9806 --  Just a comment
9807 @end cartouche
9808 @end group
9809 @end smallexample
9811 @noindent
9812 the command
9814 @smallexample
9815 $ gnatchop ^toto.txt^TOT.TXT^
9816 @end smallexample
9818 @noindent
9819 will not produce any new file and will result in the following warnings:
9821 @smallexample
9822 toto.txt:1:01: warning: empty file, contains no compilation units
9823 no compilation units found
9824 no source files written
9825 @end smallexample
9827 @node Switches for gnatchop
9828 @section Switches for @code{gnatchop}
9830 @noindent
9831 @command{gnatchop} recognizes the following switches:
9833 @table @option
9834 @c !sort!
9836 @item ^-c^/COMPILATION^
9837 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
9838 Causes @code{gnatchop} to operate in compilation mode, in which
9839 configuration pragmas are handled according to strict RM rules. See
9840 previous section for a full description of this mode.
9842 @ifclear vms
9843 @item -gnatxxx
9844 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
9845 used to parse the given file. Not all @code{xxx} options make sense,
9846 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
9847 process a source file that uses Latin-2 coding for identifiers.
9848 @end ifclear
9850 @item ^-h^/HELP^
9851 Causes @code{gnatchop} to generate a brief help summary to the standard
9852 output file showing usage information.
9854 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
9855 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
9856 Limit generated file names to the specified number @code{mm}
9857 of characters.
9858 This is useful if the
9859 resulting set of files is required to be interoperable with systems
9860 which limit the length of file names.
9861 @ifset vms
9862 If no value is given, or
9863 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
9864 a default of 39, suitable for OpenVMS Alpha
9865 Systems, is assumed
9866 @end ifset
9867 @ifclear vms
9868 No space is allowed between the @option{-k} and the numeric value. The numeric
9869 value may be omitted in which case a default of @option{-k8},
9870 suitable for use
9871 with DOS-like file systems, is used. If no @option{-k} switch
9872 is present then
9873 there is no limit on the length of file names.
9874 @end ifclear
9876 @item ^-p^/PRESERVE^
9877 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
9878 Causes the file ^modification^creation^ time stamp of the input file to be
9879 preserved and used for the time stamp of the output file(s). This may be
9880 useful for preserving coherency of time stamps in an environment where
9881 @code{gnatchop} is used as part of a standard build process.
9883 @item ^-q^/QUIET^
9884 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
9885 Causes output of informational messages indicating the set of generated
9886 files to be suppressed. Warnings and error messages are unaffected.
9888 @item ^-r^/REFERENCE^
9889 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
9890 @findex Source_Reference
9891 Generate @code{Source_Reference} pragmas. Use this switch if the output
9892 files are regarded as temporary and development is to be done in terms
9893 of the original unchopped file. This switch causes
9894 @code{Source_Reference} pragmas to be inserted into each of the
9895 generated files to refers back to the original file name and line number.
9896 The result is that all error messages refer back to the original
9897 unchopped file.
9898 In addition, the debugging information placed into the object file (when
9899 the @option{^-g^/DEBUG^} switch of @code{gcc} or @code{gnatmake} is specified)
9900 also refers back to this original file so that tools like profilers and
9901 debuggers will give information in terms of the original unchopped file.
9903 If the original file to be chopped itself contains
9904 a @code{Source_Reference}
9905 pragma referencing a third file, then gnatchop respects
9906 this pragma, and the generated @code{Source_Reference} pragmas
9907 in the chopped file refer to the original file, with appropriate
9908 line numbers. This is particularly useful when @code{gnatchop}
9909 is used in conjunction with @code{gnatprep} to compile files that
9910 contain preprocessing statements and multiple units.
9912 @item ^-v^/VERBOSE^
9913 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
9914 Causes @code{gnatchop} to operate in verbose mode. The version
9915 number and copyright notice are output, as well as exact copies of
9916 the gnat1 commands spawned to obtain the chop control information.
9918 @item ^-w^/OVERWRITE^
9919 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
9920 Overwrite existing file names. Normally @code{gnatchop} regards it as a
9921 fatal error if there is already a file with the same name as a
9922 file it would otherwise output, in other words if the files to be
9923 chopped contain duplicated units. This switch bypasses this
9924 check, and causes all but the last instance of such duplicated
9925 units to be skipped.
9927 @ifclear vms
9928 @item --GCC=xxxx
9929 @cindex @option{--GCC=} (@code{gnatchop})
9930 Specify the path of the GNAT parser to be used. When this switch is used,
9931 no attempt is made to add the prefix to the GNAT parser executable.
9932 @end ifclear
9933 @end table
9935 @node Examples of gnatchop Usage
9936 @section Examples of @code{gnatchop} Usage
9938 @table @code
9939 @ifset vms
9940 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
9941 @end ifset
9942 @ifclear vms
9943 @item gnatchop -w hello_s.ada prerelease/files
9944 @end ifclear
9946 Chops the source file @file{hello_s.ada}. The output files will be
9947 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
9948 overwriting any
9949 files with matching names in that directory (no files in the current
9950 directory are modified).
9952 @item gnatchop ^archive^ARCHIVE.^
9953 Chops the source file @file{^archive^ARCHIVE.^}
9954 into the current directory. One
9955 useful application of @code{gnatchop} is in sending sets of sources
9956 around, for example in email messages. The required sources are simply
9957 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
9958 command), and then
9959 @code{gnatchop} is used at the other end to reconstitute the original
9960 file names.
9962 @item gnatchop file1 file2 file3 direc
9963 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
9964 the resulting files in the directory @file{direc}. Note that if any units
9965 occur more than once anywhere within this set of files, an error message
9966 is generated, and no files are written. To override this check, use the
9967 @option{^-w^/OVERWRITE^} switch,
9968 in which case the last occurrence in the last file will
9969 be the one that is output, and earlier duplicate occurrences for a given
9970 unit will be skipped.
9971 @end table
9973 @node Configuration Pragmas
9974 @chapter Configuration Pragmas
9975 @cindex Configuration pragmas
9976 @cindex Pragmas, configuration
9978 @noindent
9979 In Ada 95, configuration pragmas include those pragmas described as
9980 such in the Ada 95 Reference Manual, as well as
9981 implementation-dependent pragmas that are configuration pragmas. See the
9982 individual descriptions of pragmas in the GNAT Reference Manual for
9983 details on these additional GNAT-specific configuration pragmas. Most
9984 notably, the pragma @code{Source_File_Name}, which allows
9985 specifying non-default names for source files, is a configuration
9986 pragma. The following is a complete list of configuration pragmas
9987 recognized by @code{GNAT}:
9989 @smallexample
9990    Ada_83
9991    Ada_95
9992    C_Pass_By_Copy
9993    Component_Alignment
9994    Discard_Names
9995    Elaboration_Checks
9996    Eliminate
9997    Extend_System
9998    Extensions_Allowed
9999    External_Name_Casing
10000    Float_Representation
10001    Initialize_Scalars
10002    License
10003    Locking_Policy
10004    Long_Float
10005    Normalize_Scalars
10006    Polling
10007    Profile
10008    Profile_Warnings
10009    Propagate_Exceptions
10010    Queuing_Policy
10011    Ravenscar
10012    Restricted_Run_Time
10013    Restrictions
10014    Restrictions_Warnings
10015    Reviewable
10016    Source_File_Name
10017    Style_Checks
10018    Suppress
10019    Task_Dispatching_Policy
10020    Universal_Data
10021    Unsuppress
10022    Use_VADS_Size
10023    Warnings
10024    Validity_Checks
10025 @end smallexample
10027 @menu
10028 * Handling of Configuration Pragmas::
10029 * The Configuration Pragmas Files::
10030 @end menu
10032 @node Handling of Configuration Pragmas
10033 @section Handling of Configuration Pragmas
10035 Configuration pragmas may either appear at the start of a compilation
10036 unit, in which case they apply only to that unit, or they may apply to
10037 all compilations performed in a given compilation environment.
10039 GNAT also provides the @code{gnatchop} utility to provide an automatic
10040 way to handle configuration pragmas following the semantics for
10041 compilations (that is, files with multiple units), described in the RM.
10042 See section @pxref{Operating gnatchop in Compilation Mode} for details.
10043 However, for most purposes, it will be more convenient to edit the
10044 @file{gnat.adc} file that contains configuration pragmas directly,
10045 as described in the following section.
10047 @node The Configuration Pragmas Files
10048 @section The Configuration Pragmas Files
10049 @cindex @file{gnat.adc}
10051 @noindent
10052 In GNAT a compilation environment is defined by the current
10053 directory at the time that a compile command is given. This current
10054 directory is searched for a file whose name is @file{gnat.adc}. If
10055 this file is present, it is expected to contain one or more
10056 configuration pragmas that will be applied to the current compilation.
10057 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10058 considered.
10060 Configuration pragmas may be entered into the @file{gnat.adc} file
10061 either by running @code{gnatchop} on a source file that consists only of
10062 configuration pragmas, or more conveniently  by
10063 direct editing of the @file{gnat.adc} file, which is a standard format
10064 source file.
10066 In addition to @file{gnat.adc}, one additional file containing configuration
10067 pragmas may be applied to the current compilation using the switch
10068 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10069 contains only configuration pragmas. These configuration pragmas are
10070 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10071 is present and switch @option{-gnatA} is not used).
10073 It is allowed to specify several switches @option{-gnatec}, however only
10074 the last one on the command line will be taken into account.
10076 If you are using project file, a separate mechanism is provided using
10077 project attributes, see @ref{Specifying Configuration Pragmas} for more
10078 details.
10080 @ifset vms
10081 Of special interest to GNAT OpenVMS Alpha is the following
10082 configuration pragma:
10084 @smallexample @c ada
10085 @cartouche
10086 pragma Extend_System (Aux_DEC);
10087 @end cartouche
10088 @end smallexample
10090 @noindent
10091 In the presence of this pragma, GNAT adds to the definition of the
10092 predefined package SYSTEM all the additional types and subprograms that are
10093 defined in DEC Ada. See @pxref{Compatibility with DEC Ada} for details.
10094 @end ifset
10096 @node Handling Arbitrary File Naming Conventions Using gnatname
10097 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10098 @cindex Arbitrary File Naming Conventions
10100 @menu
10101 * Arbitrary File Naming Conventions::
10102 * Running gnatname::
10103 * Switches for gnatname::
10104 * Examples of gnatname Usage::
10105 @end menu
10107 @node Arbitrary File Naming Conventions
10108 @section Arbitrary File Naming Conventions
10110 @noindent
10111 The GNAT compiler must be able to know the source file name of a compilation
10112 unit.  When using the standard GNAT default file naming conventions
10113 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10114 does not need additional information.
10116 @noindent
10117 When the source file names do not follow the standard GNAT default file naming
10118 conventions, the GNAT compiler must be given additional information through
10119 a configuration pragmas file (see @ref{Configuration Pragmas})
10120 or a project file.
10121 When the non standard file naming conventions are well-defined,
10122 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10123 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
10124 if the file naming conventions are irregular or arbitrary, a number
10125 of pragma @code{Source_File_Name} for individual compilation units
10126 must be defined.
10127 To help maintain the correspondence between compilation unit names and
10128 source file names within the compiler,
10129 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10130 set of files.
10132 @node Running gnatname
10133 @section Running @code{gnatname}
10135 @noindent
10136 The usual form of the @code{gnatname} command is
10138 @smallexample
10139 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10140 @end smallexample
10142 @noindent
10143 All of the arguments are optional. If invoked without any argument,
10144 @code{gnatname} will display its usage.
10146 @noindent
10147 When used with at least one naming pattern, @code{gnatname} will attempt to
10148 find all the compilation units in files that follow at least one of the
10149 naming patterns. To find these compilation units,
10150 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10151 regular files.
10153 @noindent
10154 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10155 Each Naming Pattern is enclosed between double quotes.
10156 A Naming Pattern is a regular expression similar to the wildcard patterns
10157 used in file names by the Unix shells or the DOS prompt.
10159 @noindent
10160 Examples of Naming Patterns are
10162 @smallexample
10163    "*.[12].ada"
10164    "*.ad[sb]*"
10165    "body_*"    "spec_*"
10166 @end smallexample
10168 @noindent
10169 For a more complete description of the syntax of Naming Patterns,
10170 see the second kind of regular expressions described in @file{g-regexp.ads}
10171 (the ``Glob'' regular expressions).
10173 @noindent
10174 When invoked with no switches, @code{gnatname} will create a configuration
10175 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10176 @code{Source_File_Name} for each file that contains a valid Ada unit.
10178 @node Switches for gnatname
10179 @section Switches for @code{gnatname}
10181 @noindent
10182 Switches for @code{gnatname} must precede any specified Naming Pattern.
10184 @noindent
10185 You may specify any of the following switches to @code{gnatname}:
10187 @table @option
10188 @c !sort!
10190 @item ^-c^/CONFIG_FILE=^@file{file}
10191 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10192 Create a configuration pragmas file @file{file} (instead of the default
10193 @file{gnat.adc}).
10194 @ifclear vms
10195 There may be zero, one or more space between @option{-c} and
10196 @file{file}.
10197 @end ifclear
10198 @file{file} may include directory information. @file{file} must be
10199 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10200 When a switch @option{^-c^/CONFIG_FILE^} is
10201 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10203 @item ^-d^/SOURCE_DIRS=^@file{dir}
10204 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10205 Look for source files in directory @file{dir}. There may be zero, one or more
10206 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10207 When a switch @option{^-d^/SOURCE_DIRS^}
10208 is specified, the current working directory will not be searched for source
10209 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10210 or @option{^-D^/DIR_FILES^} switch.
10211 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10212 If @file{dir} is a relative path, it is relative to the directory of
10213 the configuration pragmas file specified with switch
10214 @option{^-c^/CONFIG_FILE^},
10215 or to the directory of the project file specified with switch
10216 @option{^-P^/PROJECT_FILE^} or,
10217 if neither switch @option{^-c^/CONFIG_FILE^}
10218 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10219 current working directory. The directory
10220 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10222 @item ^-D^/DIRS_FILE=^@file{file}
10223 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10224 Look for source files in all directories listed in text file @file{file}.
10225 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10226 and @file{file}.
10227 @file{file} must be an existing, readable text file.
10228 Each non empty line in @file{file} must be a directory.
10229 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10230 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10231 @file{file}.
10233 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10234 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10235 Foreign patterns. Using this switch, it is possible to add sources of languages
10236 other than Ada to the list of sources of a project file.
10237 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10238 For example,
10239 @smallexample
10240 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10241 @end smallexample
10242 @noindent
10243 will look for Ada units in all files with the @file{.ada} extension,
10244 and will add to the list of file for project @file{prj.gpr} the C files
10245 with extension ".^c^C^".
10247 @item ^-h^/HELP^
10248 @cindex @option{^-h^/HELP^} (@code{gnatname})
10249 Output usage (help) information. The output is written to @file{stdout}.
10251 @item ^-P^/PROJECT_FILE=^@file{proj}
10252 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10253 Create or update project file @file{proj}. There may be zero, one or more space
10254 between @option{-P} and @file{proj}. @file{proj} may include directory
10255 information. @file{proj} must be writable.
10256 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10257 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10258 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10260 @item ^-v^/VERBOSE^
10261 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10262 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10263 This includes name of the file written, the name of the directories to search
10264 and, for each file in those directories whose name matches at least one of
10265 the Naming Patterns, an indication of whether the file contains a unit,
10266 and if so the name of the unit.
10268 @item ^-v -v^/VERBOSE /VERBOSE^
10269 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10270 Very Verbose mode. In addition to the output produced in verbose mode,
10271 for each file in the searched directories whose name matches none of
10272 the Naming Patterns, an indication is given that there is no match.
10274 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10275 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10276 Excluded patterns. Using this switch, it is possible to exclude some files
10277 that would match the name patterns. For example,
10278 @smallexample
10279 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10280 @end smallexample
10281 @noindent
10282 will look for Ada units in all files with the @file{.ada} extension,
10283 except those whose names end with @file{_nt.ada}.
10285 @end table
10287 @node Examples of gnatname Usage
10288 @section Examples of @code{gnatname} Usage
10290 @ifset vms
10291 @smallexample
10292 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10293 @end smallexample
10294 @end ifset
10296 @ifclear vms
10297 @smallexample
10298 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10299 @end smallexample
10300 @end ifclear
10302 @noindent
10303 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10304 and be writable. In addition, the directory
10305 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10306 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10308 @ifclear vms
10309 Note the optional spaces after @option{-c} and @option{-d}.
10310 @end ifclear
10312 @smallexample
10313 @ifclear vms
10314 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10315   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10316 @end ifclear
10317 @ifset vms
10318 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
10319   /EXCLUDED_PATTERN=*_nt_body.ada
10320   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10321   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10322 @end ifset
10323 @end smallexample
10325 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10326 even in conjunction with one or several switches
10327 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10328 are used in this example.
10331 @c *****************************************
10332 @c * G N A T  P r o j e c t  M a n a g e r *
10333 @c *****************************************
10334 @node GNAT Project Manager
10335 @chapter GNAT Project Manager
10337 @menu
10338 * Introduction::
10339 * Examples of Project Files::
10340 * Project File Syntax::
10341 * Objects and Sources in Project Files::
10342 * Importing Projects::
10343 * Project Extension::
10344 * External References in Project Files::
10345 * Packages in Project Files::
10346 * Variables from Imported Projects::
10347 * Naming Schemes::
10348 * Library Projects::
10349 * Using Third-Party Libraries through Projects::
10350 * Stand-alone Library Projects::
10351 * Switches Related to Project Files::
10352 * Tools Supporting Project Files::
10353 * An Extended Example::
10354 * Project File Complete Syntax::
10355 @end menu
10357 @c ****************
10358 @c * Introduction *
10359 @c ****************
10361 @node Introduction
10362 @section Introduction
10364 @noindent
10365 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10366 you to manage complex builds involving a number of source files, directories,
10367 and compilation options for different system configurations. In particular,
10368 project files allow you to specify:
10369 @itemize @bullet
10370 @item
10371 The directory or set of directories containing the source files, and/or the
10372 names of the specific source files themselves
10373 @item
10374 The directory in which the compiler's output
10375 (@file{ALI} files, object files, tree files) is to be placed
10376 @item
10377 The directory in which the executable programs is to be placed
10378 @item
10379 ^Switch^Switch^ settings for any of the project-enabled tools
10380 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10381 @code{gnatfind}); you can apply these settings either globally or to individual
10382 compilation units.
10383 @item
10384 The source files containing the main subprogram(s) to be built
10385 @item
10386 The source programming language(s) (currently Ada and/or C)
10387 @item
10388 Source file naming conventions; you can specify these either globally or for
10389 individual compilation units
10390 @end itemize
10392 @menu
10393 * Project Files::
10394 @end menu
10396 @node Project Files
10397 @subsection Project Files
10399 @noindent
10400 Project files are written in a syntax close to that of Ada, using  familiar
10401 notions such as packages, context clauses, declarations, default values,
10402 assignments, and inheritance. Finally, project files can be built
10403 hierarchically from other project files, simplifying complex system
10404 integration and project reuse.
10406 A @dfn{project} is a specific set of values for various compilation properties.
10407 The settings for a given project are described by means of
10408 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10409 Property values in project files are either strings or lists of strings.
10410 Properties that are not explicitly set receive default values.  A project
10411 file may interrogate the values of @dfn{external variables} (user-defined
10412 command-line switches or environment variables), and it may specify property
10413 settings conditionally, based on the value of such variables.
10415 In simple cases, a project's source files depend only on other source files
10416 in the same project, or on the predefined libraries.  (@emph{Dependence} is
10417 used in
10418 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10419 the Project Manager also allows more sophisticated arrangements,
10420 where the source files in one project depend on source files in other
10421 projects:
10422 @itemize @bullet
10423 @item
10424 One project can @emph{import} other projects containing needed source files.
10425 @item
10426 You can organize GNAT projects in a hierarchy: a @emph{child} project
10427 can extend a @emph{parent} project, inheriting the parent's source files and
10428 optionally overriding any of them with alternative versions
10429 @end itemize
10431 @noindent
10432 More generally, the Project Manager lets you structure large development
10433 efforts into hierarchical subsystems, where build decisions are delegated
10434 to the subsystem level, and thus different compilation environments
10435 (^switch^switch^ settings) used for different subsystems.
10437 The Project Manager is invoked through the
10438 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10439 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10440 @ifclear vms
10441 There may be zero, one or more spaces between @option{-P} and
10442 @option{@emph{projectfile}}.
10443 @end ifclear
10444 If you want to define (on the command line) an external variable that is
10445 queried by the project file, you must use the
10446 @option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10447 The Project Manager parses and interprets the project file, and drives the
10448 invoked tool based on the project settings.
10450 The Project Manager supports a wide range of development strategies,
10451 for systems of all sizes.  Here are some typical practices that are
10452 easily handled:
10453 @itemize @bullet
10454 @item
10455 Using a common set of source files, but generating object files in different
10456 directories via different ^switch^switch^ settings
10457 @item
10458 Using a mostly-shared set of source files, but with different versions of
10459 some unit or units
10460 @end itemize
10462 @noindent
10463 The destination of an executable can be controlled inside a project file
10464 using the @option{^-o^-o^}
10465 ^switch^switch^.
10466 In the absence of such a ^switch^switch^ either inside
10467 the project file or on the command line, any executable files generated by
10468 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10469 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10470 in the object directory of the project.
10472 You can use project files to achieve some of the effects of a source
10473 versioning system (for example, defining separate projects for
10474 the different sets of sources that comprise different releases) but the
10475 Project Manager is independent of any source configuration management tools
10476 that might be used by the developers.
10478 The next section introduces the main features of GNAT's project facility
10479 through a sequence of examples; subsequent sections will present the syntax
10480 and semantics in more detail. A more formal description of the project
10481 facility appears in the GNAT Reference Manual.
10483 @c *****************************
10484 @c * Examples of Project Files *
10485 @c *****************************
10487 @node Examples of Project Files
10488 @section Examples of Project Files
10489 @noindent
10490 This section illustrates some of the typical uses of project files and
10491 explains their basic structure and behavior.
10493 @menu
10494 * Common Sources with Different ^Switches^Switches^ and Directories::
10495 * Using External Variables::
10496 * Importing Other Projects::
10497 * Extending a Project::
10498 @end menu
10500 @node Common Sources with Different ^Switches^Switches^ and Directories
10501 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10503 @menu
10504 * Source Files::
10505 * Specifying the Object Directory::
10506 * Specifying the Exec Directory::
10507 * Project File Packages::
10508 * Specifying ^Switch^Switch^ Settings::
10509 * Main Subprograms::
10510 * Executable File Names::
10511 * Source File Naming Conventions::
10512 * Source Language(s)::
10513 @end menu
10515 @noindent
10516 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10517 @file{proc.adb} are in the @file{/common} directory.  The file
10518 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10519 package @code{Pack}.  We want to compile these source files under two sets
10520 of ^switches^switches^:
10521 @itemize @bullet
10522 @item
10523 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10524 and the @option{^-gnata^-gnata^},
10525 @option{^-gnato^-gnato^},
10526 and @option{^-gnatE^-gnatE^} switches to the
10527 compiler; the compiler's output is to appear in @file{/common/debug}
10528 @item
10529 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10530 to the compiler; the compiler's output is to appear in @file{/common/release}
10531 @end itemize
10533 @noindent
10534 The GNAT project files shown below, respectively @file{debug.gpr} and
10535 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10537 Schematically:
10538 @smallexample
10539 @group
10540 ^/common^[COMMON]^
10541   debug.gpr
10542   release.gpr
10543   pack.ads
10544   pack.adb
10545   proc.adb
10546 @end group
10547 @group
10548 ^/common/debug^[COMMON.DEBUG]^
10549   proc.ali, proc.o
10550   pack.ali, pack.o
10551 @end group
10552 @group
10553 ^/common/release^[COMMON.RELEASE]^
10554   proc.ali, proc.o
10555   pack.ali, pack.o
10556 @end group
10557 @end smallexample
10558 Here are the corresponding project files:
10560 @smallexample @c projectfile
10561 @group
10562 project Debug is
10563   for Object_Dir use "debug";
10564   for Main use ("proc");
10566   package Builder is
10567     for ^Default_Switches^Default_Switches^ ("Ada")
10568         use ("^-g^-g^");
10569     for Executable ("proc.adb") use "proc1";
10570   end Builder;
10571 @end group
10573 @group
10574   package Compiler is
10575     for ^Default_Switches^Default_Switches^ ("Ada")
10576        use ("-fstack-check",
10577             "^-gnata^-gnata^",
10578             "^-gnato^-gnato^",
10579             "^-gnatE^-gnatE^");
10580   end Compiler;
10581 end Debug;
10582 @end group
10583 @end smallexample
10585 @smallexample @c projectfile
10586 @group
10587 project Release is
10588   for Object_Dir use "release";
10589   for Exec_Dir use ".";
10590   for Main use ("proc");
10592   package Compiler is
10593     for ^Default_Switches^Default_Switches^ ("Ada")
10594         use ("^-O2^-O2^");
10595   end Compiler;
10596 end Release;
10597 @end group
10598 @end smallexample
10600 @noindent
10601 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10602 insensitive), and analogously the project defined by @file{release.gpr} is
10603 @code{"Release"}.  For consistency the file should have the same name as the
10604 project, and the project file's extension should be @code{"gpr"}. These
10605 conventions are not required, but a warning is issued if they are not followed.
10607 If the current directory is @file{^/temp^[TEMP]^}, then the command
10608 @smallexample
10609 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10610 @end smallexample
10612 @noindent
10613 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10614 as well as the @code{^proc1^PROC1.EXE^} executable,
10615 using the ^switch^switch^ settings defined in the project file.
10617 Likewise, the command
10618 @smallexample
10619 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10620 @end smallexample
10622 @noindent
10623 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10624 and the @code{^proc^PROC.EXE^}
10625 executable in @file{^/common^[COMMON]^},
10626 using the ^switch^switch^ settings from the project file.
10628 @node Source Files
10629 @unnumberedsubsubsec Source Files
10631 @noindent
10632 If a project file does not explicitly specify a set of source directories or
10633 a set of source files, then by default the project's source files are the
10634 Ada source files in the project file directory.  Thus @file{pack.ads},
10635 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10637 @node Specifying the Object Directory
10638 @unnumberedsubsubsec Specifying the Object Directory
10640 @noindent
10641 Several project properties are modeled by Ada-style @emph{attributes};
10642 a property is defined by supplying the equivalent of an Ada attribute
10643 definition clause in the project file.
10644 A project's object directory is another such a property; the corresponding
10645 attribute is @code{Object_Dir}, and its value is also a string expression,
10646 specified either as absolute or relative. In the later case,
10647 it is relative to the project file directory. Thus the compiler's
10648 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10649 (for the @code{Debug} project)
10650 and to @file{^/common/release^[COMMON.RELEASE]^}
10651 (for the @code{Release} project).
10652 If @code{Object_Dir} is not specified, then the default is the project file
10653 directory itself.
10655 @node Specifying the Exec Directory
10656 @unnumberedsubsubsec Specifying the Exec Directory
10658 @noindent
10659 A project's exec directory is another property; the corresponding
10660 attribute is @code{Exec_Dir}, and its value is also a string expression,
10661 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10662 then the default is the object directory (which may also be the project file
10663 directory if attribute @code{Object_Dir} is not specified). Thus the executable
10664 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10665 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10666 and in @file{^/common^[COMMON]^} for the @code{Release} project.
10668 @node Project File Packages
10669 @unnumberedsubsubsec Project File Packages
10671 @noindent
10672 A GNAT tool that is integrated with the Project Manager is modeled by a
10673 corresponding package in the project file. In the example above,
10674 The @code{Debug} project defines the packages @code{Builder}
10675 (for @command{gnatmake}) and @code{Compiler};
10676 the @code{Release} project defines only the @code{Compiler} package.
10678 The Ada-like package syntax is not to be taken literally.  Although packages in
10679 project files bear a surface resemblance to packages in Ada source code, the
10680 notation is simply a way to convey a grouping of properties for a named
10681 entity.  Indeed, the package names permitted in project files are restricted
10682 to a predefined set, corresponding to the project-aware tools, and the contents
10683 of packages are limited to a small set of constructs.
10684 The packages in the example above contain attribute definitions.
10686 @node Specifying ^Switch^Switch^ Settings
10687 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10689 @noindent
10690 ^Switch^Switch^ settings for a project-aware tool can be specified through
10691 attributes in the package that corresponds to the tool.
10692 The example above illustrates one of the relevant attributes,
10693 @code{^Default_Switches^Default_Switches^}, which is defined in packages
10694 in both project files.
10695 Unlike simple attributes like @code{Source_Dirs},
10696 @code{^Default_Switches^Default_Switches^} is
10697 known as an @emph{associative array}.  When you define this attribute, you must
10698 supply an ``index'' (a literal string), and the effect of the attribute
10699 definition is to set the value of the array at the specified index.
10700 For the @code{^Default_Switches^Default_Switches^} attribute,
10701 the index is a programming language (in our case, Ada),
10702 and the value specified (after @code{use}) must be a list
10703 of string expressions.
10705 The attributes permitted in project files are restricted to a predefined set.
10706 Some may appear at project level, others in packages.
10707 For any attribute that is an associative array, the index must always be a
10708 literal string, but the restrictions on this string (e.g., a file name or a
10709 language name) depend on the individual attribute.
10710 Also depending on the attribute, its specified value will need to be either a
10711 string or a string list.
10713 In the @code{Debug} project, we set the switches for two tools,
10714 @command{gnatmake} and the compiler, and thus we include the two corresponding
10715 packages; each package defines the @code{^Default_Switches^Default_Switches^}
10716 attribute with index @code{"Ada"}.
10717 Note that the package corresponding to
10718 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
10719 similar, but only includes the @code{Compiler} package.
10721 In project @code{Debug} above, the ^switches^switches^ starting with
10722 @option{-gnat} that are specified in package @code{Compiler}
10723 could have been placed in package @code{Builder}, since @command{gnatmake}
10724 transmits all such ^switches^switches^ to the compiler.
10726 @node Main Subprograms
10727 @unnumberedsubsubsec Main Subprograms
10729 @noindent
10730 One of the specifiable properties of a project is a list of files that contain
10731 main subprograms.  This property is captured in the @code{Main} attribute,
10732 whose value is a list of strings.  If a project defines the @code{Main}
10733 attribute, it is not necessary to identify the main subprogram(s) when
10734 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
10736 @node Executable File Names
10737 @unnumberedsubsubsec Executable File Names
10739 @noindent
10740 By default, the executable file name corresponding to a main source is
10741 deducted from the main source file name. Through the attributes
10742 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10743 it is possible to change this default.
10744 In project @code{Debug} above, the executable file name
10745 for main source @file{^proc.adb^PROC.ADB^} is
10746 @file{^proc1^PROC1.EXE^}.
10747 Attribute @code{Executable_Suffix}, when specified, may change the suffix
10748 of the the executable files, when no attribute @code{Executable} applies:
10749 its value replace the platform-specific executable suffix.
10750 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10751 specify a non default executable file name when several mains are built at once
10752 in a single @command{gnatmake} command.
10754 @node Source File Naming Conventions
10755 @unnumberedsubsubsec Source File Naming Conventions
10757 @noindent
10758 Since the project files above do not specify any source file naming
10759 conventions, the GNAT defaults are used.  The mechanism for defining source
10760 file naming conventions -- a package named @code{Naming} --
10761 is described below (@pxref{Naming Schemes}).
10763 @node Source Language(s)
10764 @unnumberedsubsubsec Source Language(s)
10766 @noindent
10767 Since the project files do not specify a @code{Languages} attribute, by
10768 default the GNAT tools assume that the language of the project file is Ada.
10769 More generally, a project can comprise source files
10770 in Ada, C, and/or other languages.
10772 @node Using External Variables
10773 @subsection Using External Variables
10775 @noindent
10776 Instead of supplying different project files for debug and release, we can
10777 define a single project file that queries an external variable (set either
10778 on the command line or via an ^environment variable^logical name^) in order to
10779 conditionally define the appropriate settings.  Again, assume that the
10780 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
10781 located in directory @file{^/common^[COMMON]^}.  The following project file,
10782 @file{build.gpr}, queries the external variable named @code{STYLE} and
10783 defines an object directory and ^switch^switch^ settings based on whether
10784 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
10785 the default is @code{"deb"}.
10787 @smallexample @c projectfile
10788 @group
10789 project Build is
10790   for Main use ("proc");
10792   type Style_Type is ("deb", "rel");
10793   Style : Style_Type := external ("STYLE", "deb");
10795   case Style is
10796     when "deb" =>
10797       for Object_Dir use "debug";
10799     when "rel" =>
10800       for Object_Dir use "release";
10801       for Exec_Dir use ".";
10802   end case;
10803 @end group
10805 @group
10806   package Builder is
10808     case Style is
10809       when "deb" =>
10810         for ^Default_Switches^Default_Switches^ ("Ada")
10811             use ("^-g^-g^");
10812         for Executable ("proc") use "proc1";
10813       when others =>
10814         null;
10815     end case;
10817   end Builder;
10818 @end group
10820 @group
10821   package Compiler is
10823     case Style is
10824       when "deb" =>
10825         for ^Default_Switches^Default_Switches^ ("Ada")
10826             use ("^-gnata^-gnata^",
10827                  "^-gnato^-gnato^",
10828                  "^-gnatE^-gnatE^");
10830       when "rel" =>
10831         for ^Default_Switches^Default_Switches^ ("Ada")
10832             use ("^-O2^-O2^");
10833     end case;
10835   end Compiler;
10837 end Build;
10838 @end group
10839 @end smallexample
10841 @noindent
10842 @code{Style_Type} is an example of a @emph{string type}, which is the project
10843 file analog of an Ada enumeration type but whose components are string literals
10844 rather than identifiers.  @code{Style} is declared as a variable of this type.
10846 The form @code{external("STYLE", "deb")} is known as an
10847 @emph{external reference}; its first argument is the name of an
10848 @emph{external variable}, and the second argument is a default value to be
10849 used if the external variable doesn't exist.  You can define an external
10850 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
10851 or you can use ^an environment variable^a logical name^
10852 as an external variable.
10854 Each @code{case} construct is expanded by the Project Manager based on the
10855 value of @code{Style}. Thus the command
10856 @ifclear vms
10857 @smallexample
10858 gnatmake -P/common/build.gpr -XSTYLE=deb
10859 @end smallexample
10860 @end ifclear
10862 @ifset vms
10863 @smallexample
10864 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
10865 @end smallexample
10866 @end ifset
10868 @noindent
10869 is equivalent to the @command{gnatmake} invocation using the project file
10870 @file{debug.gpr} in the earlier example.  So is the command
10871 @smallexample
10872 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
10873 @end smallexample
10875 @noindent
10876 since @code{"deb"} is the default for @code{STYLE}.
10878 Analogously,
10880 @ifclear vms
10881 @smallexample
10882 gnatmake -P/common/build.gpr -XSTYLE=rel
10883 @end smallexample
10884 @end ifclear
10886 @ifset vms
10887 @smallexample
10888 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
10889 @end smallexample
10890 @end ifset
10892 @noindent
10893 is equivalent to the @command{gnatmake} invocation using the project file
10894 @file{release.gpr} in the earlier example.
10896 @node Importing Other Projects
10897 @subsection Importing Other Projects
10899 @noindent
10900 A compilation unit in a source file in one project may depend on compilation
10901 units in source files in other projects.  To compile this unit under
10902 control of a project file, the
10903 dependent project must @emph{import} the projects containing the needed source
10904 files.
10905 This effect is obtained using syntax similar to an Ada @code{with} clause,
10906 but where @code{with}ed entities are strings that denote project files.
10908 As an example, suppose that the two projects @code{GUI_Proj} and
10909 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
10910 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
10911 and @file{^/comm^[COMM]^}, respectively.
10912 Suppose that the source files for @code{GUI_Proj} are
10913 @file{gui.ads} and @file{gui.adb}, and that the source files for
10914 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
10915 files is located in its respective project file directory.  Schematically:
10917 @smallexample
10918 @group
10919 ^/gui^[GUI]^
10920   gui_proj.gpr
10921   gui.ads
10922   gui.adb
10923 @end group
10925 @group
10926 ^/comm^[COMM]^
10927   comm_proj.gpr
10928   comm.ads
10929   comm.adb
10930 @end group
10931 @end smallexample
10933 @noindent
10934 We want to develop an application in directory @file{^/app^[APP]^} that
10935 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
10936 the corresponding project files (e.g. the ^switch^switch^ settings
10937 and object directory).
10938 Skeletal code for a main procedure might be something like the following:
10940 @smallexample @c ada
10941 @group
10942 with GUI, Comm;
10943 procedure App_Main is
10944    ...
10945 begin
10946    ...
10947 end App_Main;
10948 @end group
10949 @end smallexample
10951 @noindent
10952 Here is a project file, @file{app_proj.gpr}, that achieves the desired
10953 effect:
10955 @smallexample @c projectfile
10956 @group
10957 with "/gui/gui_proj", "/comm/comm_proj";
10958 project App_Proj is
10959    for Main use ("app_main");
10960 end App_Proj;
10961 @end group
10962 @end smallexample
10964 @noindent
10965 Building an executable is achieved through the command:
10966 @smallexample
10967 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
10968 @end smallexample
10969 @noindent
10970 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
10971 in the directory where @file{app_proj.gpr} resides.
10973 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
10974 (as illustrated above) the @code{with} clause can omit the extension.
10976 Our example specified an absolute path for each imported project file.
10977 Alternatively, the directory name of an imported object can be omitted
10978 if either
10979 @itemize @bullet
10980 @item
10981 The imported project file is in the same directory as the importing project
10982 file, or
10983 @item
10984 You have defined ^an environment variable^a logical name^
10985 that includes the directory containing
10986 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
10987 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
10988 directory names separated by colons (semicolons on Windows).
10989 @end itemize
10991 @noindent
10992 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
10993 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
10994 as follows:
10996 @smallexample @c projectfile
10997 @group
10998 with "gui_proj", "comm_proj";
10999 project App_Proj is
11000    for Main use ("app_main");
11001 end App_Proj;
11002 @end group
11003 @end smallexample
11005 @noindent
11006 Importing other projects can create ambiguities.
11007 For example, the same unit might be present in different imported projects, or
11008 it might be present in both the importing project and in an imported project.
11009 Both of these conditions are errors.  Note that in the current version of
11010 the Project Manager, it is illegal to have an ambiguous unit even if the
11011 unit is never referenced by the importing project.  This restriction may be
11012 relaxed in a future release.
11014 @node Extending a Project
11015 @subsection Extending a Project
11017 @noindent
11018 In large software systems it is common to have multiple
11019 implementations of a common interface; in Ada terms, multiple versions of a
11020 package body for the same specification.  For example, one implementation
11021 might be safe for use in tasking programs, while another might only be used
11022 in sequential applications.  This can be modeled in GNAT using the concept
11023 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
11024 another project (the ``parent'') then by default all source files of the
11025 parent project are inherited by the child, but the child project can
11026 override any of the parent's source files with new versions, and can also
11027 add new files.  This facility is the project analog of a type extension in
11028 Object-Oriented Programming.  Project hierarchies are permitted (a child
11029 project may be the parent of yet another project), and a project that
11030 inherits one project can also import other projects.
11032 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11033 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11034 @file{pack.adb}, and @file{proc.adb}:
11036 @smallexample
11037 @group
11038 ^/seq^[SEQ]^
11039   pack.ads
11040   pack.adb
11041   proc.adb
11042   seq_proj.gpr
11043 @end group
11044 @end smallexample
11046 @noindent
11047 Note that the project file can simply be empty (that is, no attribute or
11048 package is defined):
11050 @smallexample @c projectfile
11051 @group
11052 project Seq_Proj is
11053 end Seq_Proj;
11054 @end group
11055 @end smallexample
11057 @noindent
11058 implying that its source files are all the Ada source files in the project
11059 directory.
11061 Suppose we want to supply an alternate version of @file{pack.adb}, in
11062 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11063 @file{pack.ads} and @file{proc.adb}.  We can define a project
11064 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11066 @smallexample
11067 @group
11068 ^/tasking^[TASKING]^
11069   pack.adb
11070   tasking_proj.gpr
11071 @end group
11073 @group
11074 project Tasking_Proj extends "/seq/seq_proj" is
11075 end Tasking_Proj;
11076 @end group
11077 @end smallexample
11079 @noindent
11080 The version of @file{pack.adb} used in a build depends on which project file
11081 is specified.
11083 Note that we could have obtained the desired behavior using project import
11084 rather than project inheritance; a @code{base} project would contain the
11085 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11086 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11087 would import @code{base} and add a different version of @file{pack.adb}.  The
11088 choice depends on whether other sources in the original project need to be
11089 overridden.  If they do, then project extension is necessary, otherwise,
11090 importing is sufficient.
11092 @noindent
11093 In a project file that extends another project file, it is possible to
11094 indicate that an inherited source is not part of the sources of the extending
11095 project. This is necessary sometimes when a package spec has been overloaded
11096 and no longer requires a body: in this case, it is necessary to indicate that
11097 the inherited body is not part of the sources of the project, otherwise there
11098 will be a compilation error when compiling the spec.
11100 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11101 Its value is a string list: a list of file names.
11103 @smallexample @c @projectfile
11104 project B extends "a" is
11105    for Source_Files use ("pkg.ads");
11106    --  New spec of Pkg does not need a completion
11107    for Locally_Removed_Files use ("pkg.adb");
11108 end B;
11109 @end smallexample
11111 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11112 is still needed: if it is possible to build using @code{gnatmake} when such
11113 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11114 it is possible to remove the source completely from a system that includes
11115 project P.
11117 @c ***********************
11118 @c * Project File Syntax *
11119 @c ***********************
11121 @node Project File Syntax
11122 @section Project File Syntax
11124 @menu
11125 * Basic Syntax::
11126 * Packages::
11127 * Expressions::
11128 * String Types::
11129 * Variables::
11130 * Attributes::
11131 * Associative Array Attributes::
11132 * case Constructions::
11133 @end menu
11135 @noindent
11136 This section describes the structure of project files.
11138 A project may be an @emph{independent project}, entirely defined by a single
11139 project file. Any Ada source file in an independent project depends only
11140 on the predefined library and other Ada source files in the same project.
11142 @noindent
11143 A project may also @dfn{depend on} other projects, in either or both of
11144 the following ways:
11145 @itemize @bullet
11146 @item It may import any number of projects
11147 @item It may extend at most one other project
11148 @end itemize
11150 @noindent
11151 The dependence relation is a directed acyclic graph (the subgraph reflecting
11152 the ``extends'' relation is a tree).
11154 A project's @dfn{immediate sources} are the source files directly defined by
11155 that project, either implicitly by residing in the project file's directory,
11156 or explicitly through any of the source-related attributes described below.
11157 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11158 of @var{proj} together with the immediate sources (unless overridden) of any
11159 project on which @var{proj} depends (either directly or indirectly).
11161 @node Basic Syntax
11162 @subsection Basic Syntax
11164 @noindent
11165 As seen in the earlier examples, project files have an Ada-like syntax.
11166 The minimal project file is:
11167 @smallexample @c projectfile
11168 @group
11169 project Empty is
11171 end Empty;
11172 @end group
11173 @end smallexample
11175 @noindent
11176 The identifier @code{Empty} is the name of the project.
11177 This project name must be present after the reserved
11178 word @code{end} at the end of the project file, followed by a semi-colon.
11180 Any name in a project file, such as the project name or a variable name,
11181 has the same syntax as an Ada identifier.
11183 The reserved words of project files are the Ada reserved words plus
11184 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11185 reserved words currently used in project file syntax are:
11187 @itemize @bullet
11188 @item
11189 @code{case}
11190 @item
11191 @code{end}
11192 @item
11193 @code{for}
11194 @item
11195 @code{is}
11196 @item
11197 @code{others}
11198 @item
11199 @code{package}
11200 @item
11201 @code{renames}
11202 @item
11203 @code{type}
11204 @item
11205 @code{use}
11206 @item
11207 @code{when}
11208 @item
11209 @code{with}
11210 @end itemize
11212 @noindent
11213 Comments in project files have the same syntax as in Ada, two consecutives
11214 hyphens through the end of the line.
11216 @node Packages
11217 @subsection Packages
11219 @noindent
11220 A project file may contain @emph{packages}. The name of a package must be one
11221 of the identifiers from the following list. A package
11222 with a given name may only appear once in a project file. Package names are
11223 case insensitive. The following package names are legal:
11225 @itemize @bullet
11226 @item
11227 @code{Naming}
11228 @item
11229 @code{Builder}
11230 @item
11231 @code{Compiler}
11232 @item
11233 @code{Binder}
11234 @item
11235 @code{Linker}
11236 @item
11237 @code{Finder}
11238 @item
11239 @code{Cross_Reference}
11240 @item
11241 @code{Eliminate}
11242 @item
11243 @code{gnatls}
11244 @item
11245 @code{gnatstub}
11246 @item
11247 @code{IDE}
11248 @end itemize
11250 @noindent
11251 In its simplest form, a package may be empty:
11253 @smallexample @c projectfile
11254 @group
11255 project Simple is
11256   package Builder is
11257   end Builder;
11258 end Simple;
11259 @end group
11260 @end smallexample
11262 @noindent
11263 A package may contain @emph{attribute declarations},
11264 @emph{variable declarations} and @emph{case constructions}, as will be
11265 described below.
11267 When there is ambiguity between a project name and a package name,
11268 the name always designates the project. To avoid possible confusion, it is
11269 always a good idea to avoid naming a project with one of the
11270 names allowed for packages or any name that starts with @code{gnat}.
11272 @node Expressions
11273 @subsection Expressions
11275 @noindent
11276 An @emph{expression} is either a @emph{string expression} or a
11277 @emph{string list expression}.
11279 A @emph{string expression} is either a @emph{simple string expression} or a
11280 @emph{compound string expression}.
11282 A @emph{simple string expression} is one of the following:
11283 @itemize @bullet
11284 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11285 @item A string-valued variable reference (see @ref{Variables})
11286 @item A string-valued attribute reference (see @ref{Attributes})
11287 @item An external reference (see @ref{External References in Project Files})
11288 @end itemize
11290 @noindent
11291 A @emph{compound string expression} is a concatenation of string expressions,
11292 using the operator @code{"&"}
11293 @smallexample
11294        Path & "/" & File_Name & ".ads"
11295 @end smallexample
11297 @noindent
11298 A @emph{string list expression} is either a
11299 @emph{simple string list expression} or a
11300 @emph{compound string list expression}.
11302 A @emph{simple string list expression} is one of the following:
11303 @itemize @bullet
11304 @item A parenthesized list of zero or more string expressions,
11305 separated by commas
11306 @smallexample
11307    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11308    Empty_List := ();
11309 @end smallexample
11310 @item A string list-valued variable reference
11311 @item A string list-valued attribute reference
11312 @end itemize
11314 @noindent
11315 A @emph{compound string list expression} is the concatenation (using
11316 @code{"&"}) of a simple string list expression and an expression.  Note that
11317 each term in a compound string list expression, except the first, may be
11318 either a string expression or a string list expression.
11320 @smallexample @c projectfile
11321 @group
11322    File_Name_List := () & File_Name; --  One string in this list
11323    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11324    --  Two strings
11325    Big_List := File_Name_List & Extended_File_Name_List;
11326    --  Concatenation of two string lists: three strings
11327    Illegal_List := "gnat.adc" & Extended_File_Name_List;
11328    --  Illegal: must start with a string list
11329 @end group
11330 @end smallexample
11332 @node String Types
11333 @subsection String Types
11335 @noindent
11336 A @emph{string type declaration} introduces a discrete set of string literals.
11337 If a string variable is declared to have this type, its value
11338 is restricted to the given set of literals.
11340 Here is an example of a string type declaration:
11342 @smallexample @c projectfile
11343    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11344 @end smallexample
11346 @noindent
11347 Variables of a string type are called @emph{typed variables}; all other
11348 variables are called @emph{untyped variables}. Typed variables are
11349 particularly useful in @code{case} constructions, to support conditional
11350 attribute declarations.
11351 (see @ref{case Constructions}).
11353 The string literals in the list are case sensitive and must all be different.
11354 They may include any graphic characters allowed in Ada, including spaces.
11356 A string type may only be declared at the project level, not inside a package.
11358 A string type may be referenced by its name if it has been declared in the same
11359 project file, or by an expanded name whose prefix is the name of the project
11360 in which it is declared.
11362 @node Variables
11363 @subsection Variables
11365 @noindent
11366 A variable may be declared at the project file level, or within a package.
11367 Here are some examples of variable declarations:
11369 @smallexample @c projectfile
11370 @group
11371    This_OS : OS := external ("OS"); --  a typed variable declaration
11372    That_OS := "GNU/Linux";          --  an untyped variable declaration
11373 @end group
11374 @end smallexample
11376 @noindent
11377 The syntax of a @emph{typed variable declaration} is identical to the Ada
11378 syntax for an object declaration. By contrast, the syntax of an untyped
11379 variable declaration is identical to an Ada assignment statement. In fact,
11380 variable declarations in project files have some of the characteristics of
11381 an assignment, in that successive declarations for the same variable are
11382 allowed. Untyped variable declarations do establish the expected kind of the
11383 variable (string or string list), and successive declarations for it must
11384 respect the initial kind.
11386 @noindent
11387 A string variable declaration (typed or untyped) declares a variable
11388 whose value is a string. This variable may be used as a string expression.
11389 @smallexample @c projectfile
11390    File_Name       := "readme.txt";
11391    Saved_File_Name := File_Name & ".saved";
11392 @end smallexample
11394 @noindent
11395 A string list variable declaration declares a variable whose value is a list
11396 of strings. The list may contain any number (zero or more) of strings.
11398 @smallexample @c projectfile
11399    Empty_List := ();
11400    List_With_One_Element := ("^-gnaty^-gnaty^");
11401    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11402    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11403                  "pack2.ada", "util_.ada", "util.ada");
11404 @end smallexample
11406 @noindent
11407 The same typed variable may not be declared more than once at project level,
11408 and it may not be declared more than once in any package; it is in effect
11409 a constant.
11411 The same untyped variable may be declared several times. Declarations are
11412 elaborated in the order in which they appear, so  the new value replaces
11413 the old one, and any subsequent reference to the variable uses the new value.
11414 However, as noted above, if a variable has been declared as a string, all
11415 subsequent
11416 declarations must give it a string value. Similarly, if a variable has
11417 been declared as a string list, all subsequent declarations
11418 must give it a string list value.
11420 A @emph{variable reference} may take several forms:
11422 @itemize @bullet
11423 @item The simple variable name, for a variable in the current package (if any)
11424 or in the current project
11425 @item An expanded name, whose prefix is a context name.
11426 @end itemize
11428 @noindent
11429 A @emph{context} may be one of the following:
11431 @itemize @bullet
11432 @item The name of an existing package in the current project
11433 @item The name of an imported project of the current project
11434 @item The name of an ancestor project (i.e., a project extended by the current
11435 project, either directly or indirectly)
11436 @item An expanded name whose prefix is an imported/parent project name, and
11437 whose selector is a package name in that project.
11438 @end itemize
11440 @noindent
11441 A variable reference may be used in an expression.
11443 @node Attributes
11444 @subsection Attributes
11446 @noindent
11447 A project (and its packages) may have @emph{attributes} that define
11448 the project's properties.  Some attributes have values that are strings;
11449 others have values that are string lists.
11451 There are two categories of attributes: @emph{simple attributes}
11452 and @emph{associative arrays} (see @ref{Associative Array Attributes}).
11454 Legal project attribute names, and attribute names for each legal package are
11455 listed below. Attributes names are case-insensitive.
11457 The following attributes are defined on projects (all are simple attributes):
11459 @multitable @columnfractions .4 .3
11460 @item @emph{Attribute Name}
11461 @tab @emph{Value}
11462 @item @code{Source_Files}
11463 @tab string list
11464 @item @code{Source_Dirs}
11465 @tab string list
11466 @item @code{Source_List_File}
11467 @tab string
11468 @item @code{Object_Dir}
11469 @tab string
11470 @item @code{Exec_Dir}
11471 @tab string
11472 @item @code{Locally_Removed_Files}
11473 @tab string list
11474 @item @code{Main}
11475 @tab string list
11476 @item @code{Languages}
11477 @tab string list
11478 @item @code{Main_Language}
11479 @tab string
11480 @item @code{Library_Dir}
11481 @tab string
11482 @item @code{Library_Name}
11483 @tab string
11484 @item @code{Library_Kind}
11485 @tab string
11486 @item @code{Library_Version}
11487 @tab string
11488 @item @code{Library_Interface}
11489 @tab string
11490 @item @code{Library_Auto_Init}
11491 @tab string
11492 @item @code{Library_Options}
11493 @tab string list
11494 @item @code{Library_GCC}
11495 @tab string
11496 @end multitable
11498 @noindent
11499 The following attributes are defined for package  @code{Naming}
11500 (see @ref{Naming Schemes}):
11502 @multitable @columnfractions .4 .2 .2 .2
11503 @item Attribute Name @tab Category @tab Index @tab Value
11504 @item @code{Spec_Suffix}
11505 @tab associative array
11506 @tab language name
11507 @tab string
11508 @item @code{Body_Suffix}
11509 @tab associative array
11510 @tab language name
11511 @tab string
11512 @item @code{Separate_Suffix}
11513 @tab simple attribute
11514 @tab n/a
11515 @tab string
11516 @item @code{Casing}
11517 @tab simple attribute
11518 @tab n/a
11519 @tab string
11520 @item @code{Dot_Replacement}
11521 @tab simple attribute
11522 @tab n/a
11523 @tab string
11524 @item @code{Spec}
11525 @tab associative array
11526 @tab Ada unit name
11527 @tab string
11528 @item @code{Body}
11529 @tab associative array
11530 @tab Ada unit name
11531 @tab string
11532 @item @code{Specification_Exceptions}
11533 @tab associative array
11534 @tab language name
11535 @tab string list
11536 @item @code{Implementation_Exceptions}
11537 @tab associative array
11538 @tab language name
11539 @tab string list
11540 @end multitable
11542 @noindent
11543 The following attributes are defined for packages @code{Builder},
11544 @code{Compiler}, @code{Binder},
11545 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
11546 (see @ref{^Switches^Switches^ and Project Files}).
11548 @multitable @columnfractions .4 .2 .2 .2
11549 @item Attribute Name @tab Category @tab Index @tab Value
11550 @item @code{^Default_Switches^Default_Switches^}
11551 @tab associative array
11552 @tab language name
11553 @tab string list
11554 @item @code{^Switches^Switches^}
11555 @tab associative array
11556 @tab file name
11557 @tab string list
11558 @end multitable
11560 @noindent
11561 In addition, package @code{Compiler} has a single string attribute
11562 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11563 string attribute @code{Global_Configuration_Pragmas}.
11565 @noindent
11566 Each simple attribute has a default value: the empty string (for string-valued
11567 attributes) and the empty list (for string list-valued attributes).
11569 An attribute declaration defines a new value for an attribute.
11571 Examples of simple attribute declarations:
11573 @smallexample @c projectfile
11574    for Object_Dir use "objects";
11575    for Source_Dirs use ("units", "test/drivers");
11576 @end smallexample
11578 @noindent
11579 The syntax of a @dfn{simple attribute declaration} is similar to that of an
11580 attribute definition clause in Ada.
11582 Attributes references may be appear in expressions.
11583 The general form for such a reference is @code{<entity>'<attribute>}:
11584 Associative array attributes are functions. Associative
11585 array attribute references must have an argument that is a string literal.
11587 Examples are:
11589 @smallexample @c projectfile
11590   project'Object_Dir
11591   Naming'Dot_Replacement
11592   Imported_Project'Source_Dirs
11593   Imported_Project.Naming'Casing
11594   Builder'^Default_Switches^Default_Switches^("Ada")
11595 @end smallexample
11597 @noindent
11598 The prefix of an attribute may be:
11599 @itemize @bullet
11600 @item @code{project} for an attribute of the current project
11601 @item The name of an existing package of the current project
11602 @item The name of an imported project
11603 @item The name of a parent project that is extended by the current project
11604 @item An expanded name whose prefix is imported/parent project name,
11605       and whose selector is a package name
11606 @end itemize
11608 @noindent
11609 Example:
11610 @smallexample @c projectfile
11611 @group
11612    project Prj is
11613      for Source_Dirs use project'Source_Dirs & "units";
11614      for Source_Dirs use project'Source_Dirs & "test/drivers"
11615    end Prj;
11616 @end group
11617 @end smallexample
11619 @noindent
11620 In the first attribute declaration, initially the attribute @code{Source_Dirs}
11621 has the default value: an empty string list. After this declaration,
11622 @code{Source_Dirs} is a string list of one element: @code{"units"}.
11623 After the second attribute declaration @code{Source_Dirs} is a string list of
11624 two elements: @code{"units"} and @code{"test/drivers"}.
11626 Note: this example is for illustration only. In practice,
11627 the project file would contain only one attribute declaration:
11629 @smallexample @c projectfile
11630    for Source_Dirs use ("units", "test/drivers");
11631 @end smallexample
11633 @node Associative Array Attributes
11634 @subsection Associative Array Attributes
11636 @noindent
11637 Some attributes are defined as @emph{associative arrays}. An associative
11638 array may be regarded as a function that takes a string as a parameter
11639 and delivers a string or string list value as its result.
11641 Here are some examples of single associative array attribute associations:
11643 @smallexample @c projectfile
11644    for Body ("main") use "Main.ada";
11645    for ^Switches^Switches^ ("main.ada")
11646        use ("^-v^-v^",
11647             "^-gnatv^-gnatv^");
11648    for ^Switches^Switches^ ("main.ada")
11649             use Builder'^Switches^Switches^ ("main.ada")
11650               & "^-g^-g^";
11651 @end smallexample
11653 @noindent
11654 Like untyped variables and simple attributes, associative array attributes
11655 may be declared several times. Each declaration supplies a new value for the
11656 attribute, and replaces the previous setting.
11658 @noindent
11659 An associative array attribute may be declared as a full associative array
11660 declaration, with the value of the same attribute in an imported or extended
11661 project.
11663 @smallexample @c projectfile
11664    package Builder is
11665       for Default_Switches use Default.Builder'Default_Switches;
11666    end Builder;
11667 @end smallexample
11669 @noindent
11670 In this example, @code{Default} must be either an project imported by the
11671 current project, or the project that the current project extends. If the
11672 attribute is in a package (in this case, in package @code{Builder}), the same
11673 package needs to be specified.
11675 @noindent
11676 A full associative array declaration replaces any other declaration for the
11677 attribute, including other full associative array declaration. Single
11678 associative array associations may be declare after a full associative
11679 declaration, modifying the value for a single association of the attribute.
11681 @node case Constructions
11682 @subsection @code{case} Constructions
11684 @noindent
11685 A @code{case} construction is used in a project file to effect conditional
11686 behavior.
11687 Here is a typical example:
11689 @smallexample @c projectfile
11690 @group
11691 project MyProj is
11692    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11694    OS : OS_Type := external ("OS", "GNU/Linux");
11695 @end group
11697 @group
11698    package Compiler is
11699      case OS is
11700        when "GNU/Linux" | "Unix" =>
11701          for ^Default_Switches^Default_Switches^ ("Ada")
11702              use ("^-gnath^-gnath^");
11703        when "NT" =>
11704          for ^Default_Switches^Default_Switches^ ("Ada")
11705              use ("^-gnatP^-gnatP^");
11706        when others =>
11707      end case;
11708    end Compiler;
11709 end MyProj;
11710 @end group
11711 @end smallexample
11713 @noindent
11714 The syntax of a @code{case} construction is based on the Ada case statement
11715 (although there is no @code{null} construction for empty alternatives).
11717 The case expression must a typed string variable.
11718 Each alternative comprises the reserved word @code{when}, either a list of
11719 literal strings separated by the @code{"|"} character or the reserved word
11720 @code{others},  and the @code{"=>"} token.
11721 Each literal string must belong to the string type that is the type of the
11722 case variable.
11723 An @code{others} alternative, if present, must occur last.
11725 After each @code{=>}, there are zero or more constructions.  The only
11726 constructions allowed in a case construction are other case constructions and
11727 attribute declarations. String type declarations, variable declarations and
11728 package declarations are not allowed.
11730 The value of the case variable is often given by an external reference
11731 (see @ref{External References in Project Files}).
11733 @c ****************************************
11734 @c * Objects and Sources in Project Files *
11735 @c ****************************************
11737 @node Objects and Sources in Project Files
11738 @section Objects and Sources in Project Files
11740 @menu
11741 * Object Directory::
11742 * Exec Directory::
11743 * Source Directories::
11744 * Source File Names::
11745 @end menu
11747 @noindent
11748 Each project has exactly one object directory and one or more source
11749 directories. The source directories must contain at least one source file,
11750 unless  the project file explicitly specifies that no source files are present
11751 (see @ref{Source File Names}).
11753 @node Object Directory
11754 @subsection Object Directory
11756 @noindent
11757 The object directory for a project is the directory containing the compiler's
11758 output (such as @file{ALI} files and object files) for the project's immediate
11759 sources.
11761 The object directory is given by the value of the attribute @code{Object_Dir}
11762 in the project file.
11764 @smallexample @c projectfile
11765    for Object_Dir use "objects";
11766 @end smallexample
11768 @noindent
11769 The attribute @var{Object_Dir} has a string value, the path name of the object
11770 directory. The path name may be absolute or relative to the directory of the
11771 project file. This directory must already exist, and be readable and writable.
11773 By default, when the attribute @code{Object_Dir} is not given an explicit value
11774 or when its value is the empty string, the object directory is the same as the
11775 directory containing the project file.
11777 @node Exec Directory
11778 @subsection Exec Directory
11780 @noindent
11781 The exec directory for a project is the directory containing the executables
11782 for the project's main subprograms.
11784 The exec directory is given by the value of the attribute @code{Exec_Dir}
11785 in the project file.
11787 @smallexample @c projectfile
11788    for Exec_Dir use "executables";
11789 @end smallexample
11791 @noindent
11792 The attribute @var{Exec_Dir} has a string value, the path name of the exec
11793 directory. The path name may be absolute or relative to the directory of the
11794 project file. This directory must already exist, and be writable.
11796 By default, when the attribute @code{Exec_Dir} is not given an explicit value
11797 or when its value is the empty string, the exec directory is the same as the
11798 object directory of the project file.
11800 @node Source Directories
11801 @subsection Source Directories
11803 @noindent
11804 The source directories of a project are specified by the project file
11805 attribute @code{Source_Dirs}.
11807 This attribute's value is a string list. If the attribute is not given an
11808 explicit value, then there is only one source directory, the one where the
11809 project file resides.
11811 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
11812 as in
11814 @smallexample @c projectfile
11815     for Source_Dirs use ();
11816 @end smallexample
11818 @noindent
11819 indicates that the project contains no source files.
11821 Otherwise, each string in the string list designates one or more
11822 source directories.
11824 @smallexample @c projectfile
11825    for Source_Dirs use ("sources", "test/drivers");
11826 @end smallexample
11828 @noindent
11829 If a string in the list ends with @code{"/**"},  then the directory whose path
11830 name precedes the two asterisks, as well as all its subdirectories
11831 (recursively), are source directories.
11833 @smallexample @c projectfile
11834    for Source_Dirs use ("/system/sources/**");
11835 @end smallexample
11837 @noindent
11838 Here the directory @code{/system/sources} and all of its subdirectories
11839 (recursively) are source directories.
11841 To specify that the source directories are the directory of the project file
11842 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
11843 @smallexample @c projectfile
11844    for Source_Dirs use ("./**");
11845 @end smallexample
11847 @noindent
11848 Each of the source directories must exist and be readable.
11850 @node Source File Names
11851 @subsection Source File Names
11853 @noindent
11854 In a project that contains source files, their names may be specified by the
11855 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
11856 (a string). Source file names never include any directory information.
11858 If the attribute @code{Source_Files} is given an explicit value, then each
11859 element of the list is a source file name.
11861 @smallexample @c projectfile
11862    for Source_Files use ("main.adb");
11863    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
11864 @end smallexample
11866 @noindent
11867 If the attribute @code{Source_Files} is not given an explicit value,
11868 but the attribute @code{Source_List_File} is given a string value,
11869 then the source file names are contained in the text file whose path name
11870 (absolute or relative to the directory of the project file) is the
11871 value of the attribute @code{Source_List_File}.
11873 Each line in the file that is not empty or is not a comment
11874 contains a source file name.
11876 @smallexample @c projectfile
11877    for Source_List_File use "source_list.txt";
11878 @end smallexample
11880 @noindent
11881 By default, if neither the attribute @code{Source_Files} nor the attribute
11882 @code{Source_List_File} is given an explicit value, then each file in the
11883 source directories that conforms to the project's naming scheme
11884 (see @ref{Naming Schemes}) is an immediate source of the project.
11886 A warning is issued if both attributes @code{Source_Files} and
11887 @code{Source_List_File} are given explicit values. In this case, the attribute
11888 @code{Source_Files} prevails.
11890 Each source file name must be the name of one existing source file
11891 in one of the source directories.
11893 A @code{Source_Files} attribute whose value is an empty list
11894 indicates that there are no source files in the project.
11896 If the order of the source directories is known statically, that is if
11897 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
11898 be several files with the same source file name. In this case, only the file
11899 in the first directory is considered as an immediate source of the project
11900 file. If the order of the source directories is not known statically, it is
11901 an error to have several files with the same source file name.
11903 Projects can be specified to have no Ada source
11904 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
11905 list, or the @code{"Ada"} may be absent from @code{Languages}:
11907 @smallexample @c projectfile
11908    for Source_Dirs use ();
11909    for Source_Files use ();
11910    for Languages use ("C", "C++");
11911 @end smallexample
11913 @noindent
11914 Otherwise, a project must contain at least one immediate source.
11916 Projects with no source files are useful as template packages
11917 (see @ref{Packages in Project Files}) for other projects; in particular to
11918 define a package @code{Naming} (see @ref{Naming Schemes}).
11920 @c ****************************
11921 @c * Importing Projects *
11922 @c ****************************
11924 @node  Importing Projects
11925 @section Importing Projects
11927 @noindent
11928 An immediate source of a project P may depend on source files that
11929 are neither immediate sources of P nor in the predefined library.
11930 To get this effect, P must @emph{import} the projects that contain the needed
11931 source files.
11933 @smallexample @c projectfile
11934 @group
11935   with "project1", "utilities.gpr";
11936   with "/namings/apex.gpr";
11937   project Main is
11938     ...
11939 @end group
11940 @end smallexample
11942 @noindent
11943 As can be seen in this example, the syntax for importing projects is similar
11944 to the syntax for importing compilation units in Ada. However, project files
11945 use literal strings instead of names, and the @code{with} clause identifies
11946 project files rather than packages.
11948 Each literal string is the file name or path name (absolute or relative) of a
11949 project file. If a string is simply a file name, with no path, then its
11950 location is determined by the @emph{project path}:
11952 @itemize @bullet
11953 @item
11954 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} exists,
11955 then the project path includes all the directories in this
11956 ^environment variable^logical name^, plus the directory of the project file.
11958 @item
11959 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} does not
11960 exist, then the project path contains only one directory, namely the one where
11961 the project file is located.
11962 @end itemize
11964 @noindent
11965 If a relative pathname is used, as in
11967 @smallexample @c projectfile
11968   with "tests/proj";
11969 @end smallexample
11971 @noindent
11972 then the path is relative to the directory where the importing project file is
11973 located. Any symbolic link will be fully resolved in the directory
11974 of the importing project file before the imported project file is examined.
11976 If the @code{with}'ed project file name does not have an extension,
11977 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
11978 then the file name as specified in the @code{with} clause (no extension) will
11979 be used. In the above example, if a file @code{project1.gpr} is found, then it
11980 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
11981 then it will be used; if neither file exists, this is an error.
11983 A warning is issued if the name of the project file does not match the
11984 name of the project; this check is case insensitive.
11986 Any source file that is an immediate source of the imported project can be
11987 used by the immediate sources of the importing project, transitively. Thus
11988 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
11989 sources of @code{A} may depend on the immediate sources of @code{C}, even if
11990 @code{A} does not import @code{C} explicitly. However, this is not recommended,
11991 because if and when @code{B} ceases to import @code{C}, some sources in
11992 @code{A} will no longer compile.
11994 A side effect of this capability is that normally cyclic dependencies are not
11995 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
11996 is not allowed to import @code{A}. However, there are cases when cyclic
11997 dependencies would be beneficial. For these cases, another form of import
11998 between projects exists, the @code{limited with}: a project @code{A} that
11999 imports a project @code{B} with a straigh @code{with} may also be imported,
12000 directly or indirectly, by @code{B} on the condition that imports from @code{B}
12001 to @code{A} include at least one @code{limited with}.
12003 @smallexample @c 0projectfile
12004 with "../b/b.gpr";
12005 with "../c/c.gpr";
12006 project A is
12007 end A;
12009 limited with "../a/a.gpr";
12010 project B is
12011 end B;
12013 with "../d/d.gpr";
12014 project C is
12015 end C;
12017 limited with "../a/a.gpr";
12018 project D is
12019 end D;
12020 @end smallexample
12022 @noindent
12023 In the above legal example, there are two project cycles:
12024 @itemize @bullet
12025 @item A-> B-> A
12026 @item A -> C -> D -> A
12027 @end itemize
12029 @noindent
12030 In each of these cycle there is one @code{limited with}: import of @code{A}
12031 from @code{B} and import of @code{A} from @code{D}.
12033 The difference between straight @code{with} and @code{limited with} is that
12034 the name of a project imported with a @code{limited with} cannot be used in the
12035 project that imports it. In particular, its packages cannot be renamed and
12036 its variables cannot be referred to.
12038 An exception to the above rules for @code{limited with} is that for the main
12039 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12040 @code{limited with} is equivalent to a straight @code{with}. For example,
12041 in the example above, projects @code{B} and @code{D} could not be main
12042 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12043 each have a @code{limited with} that is the only one in a cycle of importing
12044 projects.
12046 @c *********************
12047 @c * Project Extension *
12048 @c *********************
12050 @node Project Extension
12051 @section Project Extension
12053 @noindent
12054 During development of a large system, it is sometimes necessary to use
12055 modified versions of some of the source files, without changing the original
12056 sources. This can be achieved through the @emph{project extension} facility.
12058 @smallexample @c projectfile
12059    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12060 @end smallexample
12062 @noindent
12063 A project extension declaration introduces an extending project
12064 (the @emph{child}) and a project being extended (the @emph{parent}).
12066 By default, a child project inherits all the sources of its parent.
12067 However, inherited sources can be overridden: a unit in a parent is hidden
12068 by a unit of the same name in the child.
12070 Inherited sources are considered to be sources (but not immediate sources)
12071 of the child project; see @ref{Project File Syntax}.
12073 An inherited source file retains any switches specified in the parent project.
12075 For example if the project @code{Utilities} contains the specification and the
12076 body of an Ada package @code{Util_IO}, then the project
12077 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12078 The original body of @code{Util_IO} will not be considered in program builds.
12079 However, the package specification will still be found in the project
12080 @code{Utilities}.
12082 A child project can have only one parent but it may import any number of other
12083 projects.
12085 A project is not allowed to import directly or indirectly at the same time a
12086 child project and any of its ancestors.
12088 @c ****************************************
12089 @c * External References in Project Files *
12090 @c ****************************************
12092 @node  External References in Project Files
12093 @section External References in Project Files
12095 @noindent
12096 A project file may contain references to external variables; such references
12097 are called @emph{external references}.
12099 An external variable is either defined as part of the environment (an
12100 environment variable in Unix, for example) or else specified on the command
12101 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12102 If both, then the command line value is used.
12104 The value of an external reference is obtained by means of the built-in
12105 function @code{external}, which returns a string value.
12106 This function has two forms:
12107 @itemize @bullet
12108 @item @code{external (external_variable_name)}
12109 @item @code{external (external_variable_name, default_value)}
12110 @end itemize
12112 @noindent
12113 Each parameter must be a string literal.  For example:
12115 @smallexample @c projectfile
12116    external ("USER")
12117    external ("OS", "GNU/Linux")
12118 @end smallexample
12120 @noindent
12121 In the form with one parameter, the function returns the value of
12122 the external variable given as parameter. If this name is not present in the
12123 environment, the function returns an empty string.
12125 In the form with two string parameters, the second argument is
12126 the value returned when the variable given as the first argument is not
12127 present in the environment. In the example above, if @code{"OS"} is not
12128 the name of ^an environment variable^a logical name^ and is not passed on
12129 the command line, then the returned value is @code{"GNU/Linux"}.
12131 An external reference may be part of a string expression or of a string
12132 list expression, and can therefore appear in a variable declaration or
12133 an attribute declaration.
12135 @smallexample @c projectfile
12136 @group
12137    type Mode_Type is ("Debug", "Release");
12138    Mode : Mode_Type := external ("MODE");
12139    case Mode is
12140      when "Debug" =>
12141         ...
12142 @end group
12143 @end smallexample
12145 @c *****************************
12146 @c * Packages in Project Files *
12147 @c *****************************
12149 @node  Packages in Project Files
12150 @section Packages in Project Files
12152 @noindent
12153 A @emph{package} defines the settings for project-aware tools within a
12154 project.
12155 For each such tool one can declare a package; the names for these
12156 packages are preset (see @ref{Packages}).
12157 A package may contain variable declarations, attribute declarations, and case
12158 constructions.
12160 @smallexample @c projectfile
12161 @group
12162    project Proj is
12163       package Builder is  -- used by gnatmake
12164          for ^Default_Switches^Default_Switches^ ("Ada")
12165              use ("^-v^-v^",
12166                   "^-g^-g^");
12167       end Builder;
12168    end Proj;
12169 @end group
12170 @end smallexample
12172 @noindent
12173 The syntax of package declarations mimics that of package in Ada.
12175 Most of the packages have an attribute
12176 @code{^Default_Switches^Default_Switches^}.
12177 This attribute is an associative array, and its value is a string list.
12178 The index of the associative array is the name of a programming language (case
12179 insensitive). This attribute indicates the ^switch^switch^
12180 or ^switches^switches^ to be used
12181 with the corresponding tool.
12183 Some packages also have another attribute, @code{^Switches^Switches^},
12184 an associative array whose value is a string list.
12185 The index is the name of a source file.
12186 This attribute indicates the ^switch^switch^
12187 or ^switches^switches^ to be used by the corresponding
12188 tool when dealing with this specific file.
12190 Further information on these ^switch^switch^-related attributes is found in
12191 @ref{^Switches^Switches^ and Project Files}.
12193 A package may be declared as a @emph{renaming} of another package; e.g., from
12194 the project file for an imported project.
12196 @smallexample @c projectfile
12197 @group
12198   with "/global/apex.gpr";
12199   project Example is
12200     package Naming renames Apex.Naming;
12201     ...
12202   end Example;
12203 @end group
12204 @end smallexample
12206 @noindent
12207 Packages that are renamed in other project files often come from project files
12208 that have no sources: they are just used as templates. Any modification in the
12209 template will be reflected automatically in all the project files that rename
12210 a package from the template.
12212 In addition to the tool-oriented packages, you can also declare a package
12213 named @code{Naming} to establish specialized source file naming conventions
12214 (see @ref{Naming Schemes}).
12216 @c ************************************
12217 @c * Variables from Imported Projects *
12218 @c ************************************
12220 @node Variables from Imported Projects
12221 @section Variables from Imported Projects
12223 @noindent
12224 An attribute or variable defined in an imported or parent project can
12225 be used in expressions in the importing / extending project.
12226 Such an attribute or variable is denoted by an expanded name whose prefix
12227 is either the name of the project or the expanded name of a package within
12228 a project.
12230 @smallexample @c projectfile
12231 @group
12232   with "imported";
12233   project Main extends "base" is
12234      Var1 := Imported.Var;
12235      Var2 := Base.Var & ".new";
12236 @end group
12238 @group
12239      package Builder is
12240         for ^Default_Switches^Default_Switches^ ("Ada")
12241             use Imported.Builder.Ada_^Switches^Switches^ &
12242                 "^-gnatg^-gnatg^" &
12243                 "^-v^-v^";
12244      end Builder;
12245 @end group
12247 @group
12248      package Compiler is
12249         for ^Default_Switches^Default_Switches^ ("Ada")
12250             use Base.Compiler.Ada_^Switches^Switches^;
12251      end Compiler;
12252   end Main;
12253 @end group
12254 @end smallexample
12256 @noindent
12257 In this example:
12259 @itemize @bullet
12260 @item
12261 The value of @code{Var1} is a copy of the variable @code{Var} defined
12262 in the project file @file{"imported.gpr"}
12263 @item
12264 the value of @code{Var2} is a copy of the value of variable @code{Var}
12265 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12266 @item
12267 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12268 @code{Builder} is a string list that includes in its value a copy of the value
12269 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12270 in project file @file{imported.gpr} plus two new elements:
12271 @option{"^-gnatg^-gnatg^"}
12272 and @option{"^-v^-v^"};
12273 @item
12274 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12275 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12276 defined in the @code{Compiler} package in project file @file{base.gpr},
12277 the project being extended.
12278 @end itemize
12280 @c ******************
12281 @c * Naming Schemes *
12282 @c ******************
12284 @node  Naming Schemes
12285 @section Naming Schemes
12287 @noindent
12288 Sometimes an Ada software system is ported from a foreign compilation
12289 environment to GNAT, and the file names do not use the default GNAT
12290 conventions. Instead of changing all the file names (which for a variety
12291 of reasons might not be possible), you can define the relevant file
12292 naming scheme in the @code{Naming} package in your project file.
12294 @noindent
12295 Note that the use of pragmas described in @ref{Alternative
12296 File Naming Schemes} by mean of a configuration pragmas file is not
12297 supported when using project files. You must use the features described
12298 in this paragraph. You can however use specify other configuration
12299 pragmas (see @ref{Specifying Configuration Pragmas}).
12301 @ifclear vms
12302 For example, the following
12303 package models the Apex file naming rules:
12305 @smallexample @c projectfile
12306 @group
12307   package Naming is
12308     for Casing               use "lowercase";
12309     for Dot_Replacement      use ".";
12310     for Spec_Suffix ("Ada")  use ".1.ada";
12311     for Body_Suffix ("Ada")  use ".2.ada";
12312   end Naming;
12313 @end group
12314 @end smallexample
12315 @end ifclear
12317 @ifset vms
12318 For example, the following package models the DEC Ada file naming rules:
12320 @smallexample @c projectfile
12321 @group
12322   package Naming is
12323     for Casing               use "lowercase";
12324     for Dot_Replacement      use "__";
12325     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12326     for Body_Suffix ("Ada")  use ".^ada^ada^";
12327   end Naming;
12328 @end group
12329 @end smallexample
12331 @noindent
12332 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12333 names in lower case)
12334 @end ifset
12336 @noindent
12337 You can define the following attributes in package @code{Naming}:
12339 @table @code
12341 @item @var{Casing}
12342 This must be a string with one of the three values @code{"lowercase"},
12343 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12345 @noindent
12346 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12348 @item @var{Dot_Replacement}
12349 This must be a string whose value satisfies the following conditions:
12351 @itemize @bullet
12352 @item It must not be empty
12353 @item It cannot start or end with an alphanumeric character
12354 @item It cannot be a single underscore
12355 @item It cannot start with an underscore followed by an alphanumeric
12356 @item It cannot contain a dot @code{'.'} except if the entire string
12357 is @code{"."}
12358 @end itemize
12360 @noindent
12361 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12363 @item @var{Spec_Suffix}
12364 This is an associative array (indexed by the programming language name, case
12365 insensitive) whose value is a string that must satisfy the following
12366 conditions:
12368 @itemize @bullet
12369 @item It must not be empty
12370 @item It must include at least one dot
12371 @end itemize
12372 @noindent
12373 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12374 @code{"^.ads^.ADS^"}.
12376 @item @var{Body_Suffix}
12377 This is an associative array (indexed by the programming language name, case
12378 insensitive) whose value is a string that must satisfy the following
12379 conditions:
12381 @itemize @bullet
12382 @item It must not be empty
12383 @item It must include at least one dot
12384 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12385 @end itemize
12386 @noindent
12387 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12388 @code{"^.adb^.ADB^"}.
12390 @item @var{Separate_Suffix}
12391 This must be a string whose value satisfies the same conditions as
12392 @code{Body_Suffix}.
12394 @noindent
12395 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12396 value as @code{Body_Suffix ("Ada")}.
12398 @item @var{Spec}
12399 @noindent
12400 You can use the associative array attribute @code{Spec}  to define
12401 the source file name for an individual Ada compilation unit's spec. The array
12402 index must be a string literal that identifies the Ada unit (case insensitive).
12403 The value of this attribute must be a string that identifies the file that
12404 contains this unit's spec (case sensitive or insensitive depending on the
12405 operating system).
12407 @smallexample @c projectfile
12408    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12409 @end smallexample
12411 @item @var{Body}
12413 You can use the associative array attribute @code{Body} to
12414 define the source file name for an individual Ada compilation unit's body
12415 (possibly a subunit).  The array index must be a string literal that identifies
12416 the Ada unit (case insensitive).  The value of this attribute must be a string
12417 that identifies the file that contains this unit's body or subunit (case
12418 sensitive or insensitive depending on the operating system).
12420 @smallexample @c projectfile
12421    for Body ("MyPack.MyChild") use "mypack.mychild.body";
12422 @end smallexample
12423 @end table
12425 @c ********************
12426 @c * Library Projects *
12427 @c ********************
12429 @node Library Projects
12430 @section Library Projects
12432 @noindent
12433 @emph{Library projects} are projects whose object code is placed in a library.
12434 (Note that this facility is not yet supported on all platforms)
12436 To create a library project, you need to define in its project file
12437 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12438 Additionally, you may define the library-related attributes
12439 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12440 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12442 The @code{Library_Name} attribute has a string value. There is no restriction
12443 on the name of a library. It is the responsability of the developer to
12444 choose a name that will be accepted by the platform. It is recommanded to
12445 choose names that could be Ada identifiers; such names are almost guaranteed
12446 to be acceptable on all platforms.
12448 The @code{Library_Dir} attribute has a string value that designates the path
12449 (absolute or relative) of the directory where the library will reside.
12450 It must designate an existing directory, and this directory must be
12451 different from the project's object directory. It also needs to be writable.
12452 The directory should only be used for one library; the reason is that all
12453 files contained in this directory may be deleted by the Project Manager.
12455 If both @code{Library_Name} and @code{Library_Dir} are specified and
12456 are legal, then the project file defines a library project.  The optional
12457 library-related attributes are checked only for such project files.
12459 The @code{Library_Kind} attribute has a string value that must be one of the
12460 following (case insensitive): @code{"static"}, @code{"dynamic"} or
12461 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
12462 attribute is not specified, the library is a static library, that is
12463 an archive of object files that can be potentially linked into an
12464 static executable. Otherwise, the library may be dynamic or
12465 relocatable, that is a library that is loaded only at the start of execution.
12467 If you need to build both a static and a dynamic library, you should use two
12468 different object directories, since in some cases some extra code needs to
12469 be generated for the latter. For such cases, it is recommended to either use
12470 two different project files, or a single one which uses external variables
12471 to indicate what kind of library should be build.
12473 The @code{Library_Version} attribute has a string value whose interpretation
12474 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12475 used only for dynamic/relocatable libraries as the internal name of the
12476 library (the @code{"soname"}). If the library file name (built from the
12477 @code{Library_Name}) is different from the @code{Library_Version}, then the
12478 library file will be a symbolic link to the actual file whose name will be
12479 @code{Library_Version}.
12481 Example (on Unix):
12483 @smallexample @c projectfile
12484 @group
12485 project Plib is
12487    Version := "1";
12489    for Library_Dir use "lib_dir";
12490    for Library_Name use "dummy";
12491    for Library_Kind use "relocatable";
12492    for Library_Version use "libdummy.so." & Version;
12494 end Plib;
12495 @end group
12496 @end smallexample
12498 @noindent
12499 Directory @file{lib_dir} will contain the internal library file whose name
12500 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12501 @file{libdummy.so.1}.
12503 When @command{gnatmake} detects that a project file
12504 is a library project file, it will check all immediate sources of the project
12505 and rebuild the library if any of the sources have been recompiled.
12507 Standard project files can import library project files. In such cases,
12508 the libraries will only be rebuild if some of its sources are recompiled
12509 because they are in the closure of some other source in an importing project.
12510 Sources of the library project files that are not in such a closure will
12511 not be checked, unless the full library is checked, because one of its sources
12512 needs to be recompiled.
12514 For instance, assume the project file @code{A} imports the library project file
12515 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
12516 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
12517 @file{l2.ads}, @file{l2.adb}.
12519 If @file{l1.adb} has been modified, then the library associated with @code{L}
12520 will be rebuild when compiling all the immediate sources of @code{A} only
12521 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
12522 @code{"with L1;"}.
12524 To be sure that all the sources in the library associated with @code{L} are
12525 up to date, and that all the sources of parject @code{A} are also up to date,
12526 the following two commands needs to be used:
12528 @smallexample
12529 gnatmake -Pl.gpr
12530 gnatmake -Pa.gpr
12531 @end smallexample
12533 When a library is built or rebuilt, an attempt is made first to delete all
12534 files in the library directory.
12535 All @file{ALI} files will also be copied from the object directory to the
12536 library directory. To build executables, @command{gnatmake} will use the
12537 library rather than the individual object files.
12540 @c **********************************************
12541 @c * Using Third-Party Libraries through Projects
12542 @c **********************************************
12543 @node Using Third-Party Libraries through Projects
12544 @section Using Third-Party Libraries through Projects
12546 Whether you are exporting your own library to make it available to
12547 clients, or you are using a library provided by a third party, it is
12548 convenient to have project files that automatically set the correct
12549 command line switches for the compiler and linker.
12551 Such project files are very similar to the library project files;
12552 @xref{Library Projects}. The only difference is that you set the
12553 @code{Source_Dirs} and @code{Object_Dir} attribute so that they point to the
12554 directories where, respectively, the sources and the read-only ALI files have
12555 been installed.
12557 If you need to interface with a set of libraries, as opposed to a
12558 single one, you need to create one library project for each of the
12559 libraries. In addition, a top-level project that imports all these
12560 library projects should be provided, so that the user of your library
12561 has a single @code{with} clause to add to his own projects.
12563 For instance, let's assume you are providing two static libraries
12564 @file{liba.a} and @file{libb.a}. The user needs to link with
12565 both of these libraries. Each of these is associated with its
12566 own set of header files. Let's assume furthermore that all the
12567 header files for the two libraries have been installed in the same
12568 directory @file{headers}. The @file{ALI} files are found in the same
12569 @file{headers} directory.
12571 In this case, you should provide the following three projects:
12573 @smallexample @c projectfile
12574 @group
12575 with "liba", "libb";
12576 project My_Library is
12577   for Source_Dirs use ("headers");
12578   for Object_Dir  use "headers";
12579 end My_Library;
12580 @end group
12582 @group
12583 project Liba is
12584    for Source_Dirs use ();
12585    for Library_Dir use "lib";
12586    for Library_Name use "a";
12587    for Library_Kind use "static";
12588 end Liba;
12589 @end group
12591 @group
12592 project Libb is
12593    for Source_Dirs use ();
12594    for Library_Dir use "lib";
12595    for Library_Name use "b";
12596    for Library_Kind use "static";
12597 end Libb;
12598 @end group
12599 @end smallexample
12601 @c *******************************
12602 @c * Stand-alone Library Projects *
12603 @c *******************************
12605 @node Stand-alone Library Projects
12606 @section Stand-alone Library Projects
12608 @noindent
12609 A Stand-alone Library is a library that contains the necessary code to
12610 elaborate the Ada units that are included in the library. A Stand-alone
12611 Library is suitable to be used in an executable when the main is not
12612 in Ada. However, Stand-alone Libraries may also be used with an Ada main
12613 subprogram.
12615 A Stand-alone Library Project is a Library Project where the library is
12616 a Stand-alone Library.
12618 To be a Stand-alone Library Project, in addition to the two attributes
12619 that make a project a Library Project (@code{Library_Name} and
12620 @code{Library_Dir}, see @ref{Library Projects}), the attribute
12621 @code{Library_Interface} must be defined.
12623 @smallexample @c projectfile
12624 @group
12625    for Library_Dir use "lib_dir";
12626    for Library_Name use "dummy";
12627    for Library_Interface use ("int1", "int1.child");
12628 @end group
12629 @end smallexample
12631 Attribute @code{Library_Interface} has a non empty string list value,
12632 each string in the list designating a unit contained in an immediate source
12633 of the project file.
12635 When a Stand-alone Library is built, first the binder is invoked to build
12636 a package whose name depends on the library name
12637 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12638 This binder-generated package includes initialization and
12639 finalization procedures whose
12640 names depend on the library name (dummyinit and dummyfinal in the example
12641 above). The object corresponding to this package is included in the library.
12643 A dynamic or relocatable Stand-alone Library is automatically initialized
12644 if automatic initialization of Stand-alone Libraries is supported on the
12645 platform and if attribute @code{Library_Auto_Init} is not specified or
12646 is specified with the value "true". A static Stand-alone Library is never
12647 automatically initialized.
12649 Single string attribute @code{Library_Auto_Init} may be specified with only
12650 two possible values: "false" or "true" (case-insensitive). Specifying
12651 "false" for attribute @code{Library_Auto_Init} will prevent automatic
12652 initialization of dynamic or relocatable libraries.
12654 When a non automatically initialized Stand-alone Library is used
12655 in an executable, its initialization procedure must be called before
12656 any service of the library is used.
12657 When the main subprogram is in Ada, it may mean that the initialization
12658 procedure has to be called during elaboration of another package.
12660 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12661 (those that are listed in attribute @code{Library_Interface}) are copied to
12662 the Library Directory. As a consequence, only the Interface Units may be
12663 imported from Ada units outside of the library. If other units are imported,
12664 the binding phase will fail.
12666 When a Stand-Alone Library is bound, the switches that are specified in
12667 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12668 used in the call to @command{gnatbind}.
12670 The string list attribute @code{Library_Options} may be used to specified
12671 additional switches to the call to @command{gcc} to link the library.
12673 The attribute @code{Library_Src_Dir}, may be specified for a
12674 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12675 single string value. Its value must be the path (absolute or relative to the
12676 project directory) of an existing directory. This directory cannot be the
12677 object directory or one of the source directories, but it can be the same as
12678 the library directory. The sources of the Interface
12679 Units of the library, necessary to an Ada client of the library, will be
12680 copied to the designated directory, called Interface Copy directory.
12681 These sources includes the specs of the Interface Units, but they may also
12682 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12683 are used, or when there is a generic units in the spec. Before the sources
12684 are copied to the Interface Copy directory, an attempt is made to delete all
12685 files in the Interface Copy directory.
12687 @c *************************************
12688 @c * Switches Related to Project Files *
12689 @c *************************************
12690 @node Switches Related to Project Files
12691 @section Switches Related to Project Files
12693 @noindent
12694 The following switches are used by GNAT tools that support project files:
12696 @table @option
12698 @item ^-P^/PROJECT_FILE=^@var{project}
12699 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12700 Indicates the name of a project file. This project file will be parsed with
12701 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12702 if any, and using the external references indicated
12703 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12704 @ifclear vms
12705 There may zero, one or more spaces between @option{-P} and @var{project}.
12706 @end ifclear
12708 @noindent
12709 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12711 @noindent
12712 Since the Project Manager parses the project file only after all the switches
12713 on the command line are checked, the order of the switches
12714 @option{^-P^/PROJECT_FILE^},
12715 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12716 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12718 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12719 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12720 Indicates that external variable @var{name} has the value @var{value}.
12721 The Project Manager will use this value for occurrences of
12722 @code{external(name)} when parsing the project file.
12724 @ifclear vms
12725 @noindent
12726 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12727 put between quotes.
12728 @smallexample
12729   -XOS=NT
12730   -X"user=John Doe"
12731 @end smallexample
12732 @end ifclear
12734 @noindent
12735 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12736 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12737 @var{name}, only the last one is used.
12739 @noindent
12740 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12741 takes precedence over the value of the same name in the environment.
12743 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12744 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
12745 @c Previous line uses code vs option command, to stay less than 80 chars
12746 Indicates the verbosity of the parsing of GNAT project files.
12748 @ifclear vms
12749 @option{-vP0} means Default;
12750 @option{-vP1} means Medium;
12751 @option{-vP2} means High.
12752 @end ifclear
12754 @ifset vms
12755 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12756 HIGH.
12757 @end ifset
12759 @noindent
12760 The default is ^Default^DEFAULT^: no output for syntactically correct
12761 project files.
12762 @noindent
12763 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12764 only the last one is used.
12766 @end table
12768 @c **********************************
12769 @c * Tools Supporting Project Files *
12770 @c **********************************
12772 @node  Tools Supporting Project Files
12773 @section Tools Supporting Project Files
12775 @menu
12776 * gnatmake and Project Files::
12777 * The GNAT Driver and Project Files::
12778 @ifclear vms
12779 * Glide and Project Files::
12780 @end ifclear
12781 @end menu
12783 @node gnatmake and Project Files
12784 @subsection gnatmake and Project Files
12786 @noindent
12787 This section covers several topics related to @command{gnatmake} and
12788 project files: defining ^switches^switches^ for @command{gnatmake}
12789 and for the tools that it invokes; specifying configuration pragmas;
12790 the use of the @code{Main} attribute; building and rebuilding library project
12791 files.
12793 @menu
12794 * ^Switches^Switches^ and Project Files::
12795 * Specifying Configuration Pragmas::
12796 * Project Files and Main Subprograms::
12797 * Library Project Files::
12798 @end menu
12800 @node ^Switches^Switches^ and Project Files
12801 @subsubsection ^Switches^Switches^ and Project Files
12803 @ifset vms
12804 It is not currently possible to specify VMS style qualifiers in the project
12805 files; only Unix style ^switches^switches^ may be specified.
12806 @end ifset
12808 @noindent
12809 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12810 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12811 attribute, a @code{^Switches^Switches^} attribute, or both;
12812 as their names imply, these ^switch^switch^-related
12813 attributes affect the ^switches^switches^ that are used for each of these GNAT
12814 components when
12815 @command{gnatmake} is invoked.  As will be explained below, these
12816 component-specific ^switches^switches^ precede
12817 the ^switches^switches^ provided on the @command{gnatmake} command line.
12819 The @code{^Default_Switches^Default_Switches^} attribute is an associative
12820 array indexed by language name (case insensitive) whose value is a string list.
12821 For example:
12823 @smallexample @c projectfile
12824 @group
12825 package Compiler is
12826   for ^Default_Switches^Default_Switches^ ("Ada")
12827       use ("^-gnaty^-gnaty^",
12828            "^-v^-v^");
12829 end Compiler;
12830 @end group
12831 @end smallexample
12833 @noindent
12834 The @code{^Switches^Switches^} attribute is also an associative array,
12835 indexed by a file name (which may or may not be case sensitive, depending
12836 on the operating system) whose value is a string list.  For example:
12838 @smallexample @c projectfile
12839 @group
12840 package Builder is
12841    for ^Switches^Switches^ ("main1.adb")
12842        use ("^-O2^-O2^");
12843    for ^Switches^Switches^ ("main2.adb")
12844        use ("^-g^-g^");
12845 end Builder;
12846 @end group
12847 @end smallexample
12849 @noindent
12850 For the @code{Builder} package, the file names must designate source files
12851 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12852 file names must designate @file{ALI} or source files for main subprograms.
12853 In each case just the file name without an explicit extension is acceptable.
12855 For each tool used in a program build (@command{gnatmake}, the compiler, the
12856 binder, and the linker), the corresponding package @dfn{contributes} a set of
12857 ^switches^switches^ for each file on which the tool is invoked, based on the
12858 ^switch^switch^-related attributes defined in the package.
12859 In particular, the ^switches^switches^
12860 that each of these packages contributes for a given file @var{f} comprise:
12862 @itemize @bullet
12863 @item
12864 the value of attribute @code{^Switches^Switches^ (@var{f})},
12865 if it is specified in the package for the given file,
12866 @item
12867 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12868 if it is specified in the package.
12869 @end itemize
12871 @noindent
12872 If neither of these attributes is defined in the package, then the package does
12873 not contribute any ^switches^switches^ for the given file.
12875 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12876 two sets, in the following order: those contributed for the file
12877 by the @code{Builder} package;
12878 and the switches passed on the command line.
12880 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12881 the ^switches^switches^ passed to the tool comprise three sets,
12882 in the following order:
12884 @enumerate
12885 @item
12886 the applicable ^switches^switches^ contributed for the file
12887 by the @code{Builder} package in the project file supplied on the command line;
12889 @item
12890 those contributed for the file by the package (in the relevant project file --
12891 see below) corresponding to the tool; and
12893 @item
12894 the applicable switches passed on the command line.
12895 @end enumerate
12897 @noindent
12898 The term @emph{applicable ^switches^switches^} reflects the fact that
12899 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12900 tools, depending on the individual ^switch^switch^.
12902 @command{gnatmake} may invoke the compiler on source files from different
12903 projects. The Project Manager will use the appropriate project file to
12904 determine the @code{Compiler} package for each source file being compiled.
12905 Likewise for the @code{Binder} and @code{Linker} packages.
12907 As an example, consider the following package in a project file:
12909 @smallexample @c projectfile
12910 @group
12911 project Proj1 is
12912    package Compiler is
12913       for ^Default_Switches^Default_Switches^ ("Ada")
12914           use ("^-g^-g^");
12915       for ^Switches^Switches^ ("a.adb")
12916           use ("^-O1^-O1^");
12917       for ^Switches^Switches^ ("b.adb")
12918           use ("^-O2^-O2^",
12919                "^-gnaty^-gnaty^");
12920    end Compiler;
12921 end Proj1;
12922 @end group
12923 @end smallexample
12925 @noindent
12926 If @command{gnatmake} is invoked with this project file, and it needs to
12927 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12928 @file{a.adb} will be compiled with the ^switch^switch^
12929 @option{^-O1^-O1^},
12930 @file{b.adb} with ^switches^switches^
12931 @option{^-O2^-O2^}
12932 and @option{^-gnaty^-gnaty^},
12933 and @file{c.adb} with @option{^-g^-g^}.
12935 The following example illustrates the ordering of the ^switches^switches^
12936 contributed by different packages:
12938 @smallexample @c projectfile
12939 @group
12940 project Proj2 is
12941    package Builder is
12942       for ^Switches^Switches^ ("main.adb")
12943           use ("^-g^-g^",
12944                "^-O1^-)1^",
12945                "^-f^-f^");
12946    end Builder;
12947 @end group
12949 @group
12950    package Compiler is
12951       for ^Switches^Switches^ ("main.adb")
12952           use ("^-O2^-O2^");
12953    end Compiler;
12954 end Proj2;
12955 @end group
12956 @end smallexample
12958 @noindent
12959 If you issue the command:
12961 @smallexample
12962     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12963 @end smallexample
12965 @noindent
12966 then the compiler will be invoked on @file{main.adb} with the following
12967 sequence of ^switches^switches^
12969 @smallexample
12970    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12971 @end smallexample
12973 with the last @option{^-O^-O^}
12974 ^switch^switch^ having precedence over the earlier ones;
12975 several other ^switches^switches^
12976 (such as @option{^-c^-c^}) are added implicitly.
12978 The ^switches^switches^
12979 @option{^-g^-g^}
12980 and @option{^-O1^-O1^} are contributed by package
12981 @code{Builder},  @option{^-O2^-O2^} is contributed
12982 by the package @code{Compiler}
12983 and @option{^-O0^-O0^} comes from the command line.
12985 The @option{^-g^-g^}
12986 ^switch^switch^ will also be passed in the invocation of
12987 @command{Gnatlink.}
12989 A final example illustrates switch contributions from packages in different
12990 project files:
12992 @smallexample @c projectfile
12993 @group
12994 project Proj3 is
12995    for Source_Files use ("pack.ads", "pack.adb");
12996    package Compiler is
12997       for ^Default_Switches^Default_Switches^ ("Ada")
12998           use ("^-gnata^-gnata^");
12999    end Compiler;
13000 end Proj3;
13001 @end group
13003 @group
13004 with "Proj3";
13005 project Proj4 is
13006    for Source_Files use ("foo_main.adb", "bar_main.adb");
13007    package Builder is
13008       for ^Switches^Switches^ ("foo_main.adb")
13009           use ("^-s^-s^",
13010                "^-g^-g^");
13011    end Builder;
13012 end Proj4;
13013 @end group
13015 @group
13016 -- Ada source file:
13017 with Pack;
13018 procedure Foo_Main is
13019    ...
13020 end Foo_Main;
13021 @end group
13022 @end smallexample
13024 If the command is
13025 @smallexample
13026 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13027 @end smallexample
13029 @noindent
13030 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13031 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13032 @option{^-gnato^-gnato^} (passed on the command line).
13033 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13034 are @option{^-g^-g^} from @code{Proj4.Builder},
13035 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13036 and @option{^-gnato^-gnato^} from the command line.
13038 @noindent
13039 When using @command{gnatmake} with project files, some ^switches^switches^ or
13040 arguments may be expressed as relative paths. As the working directory where
13041 compilation occurs may change, these relative paths are converted to absolute
13042 paths. For the ^switches^switches^ found in a project file, the relative paths
13043 are relative to the project file directory, for the switches on the command
13044 line, they are relative to the directory where @command{gnatmake} is invoked.
13045 The ^switches^switches^ for which this occurs are:
13046 ^-I^-I^,
13047 ^-A^-A^,
13048 ^-L^-L^,
13049 ^-aO^-aO^,
13050 ^-aL^-aL^,
13051 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13052 ^switch^switch^
13053 ^-o^-o^, object files specified in package @code{Linker} or after
13054 -largs on the command line). The exception to this rule is the ^switch^switch^
13055 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13057 @node Specifying Configuration Pragmas
13058 @subsubsection Specifying Configuration Pragmas
13060 When using @command{gnatmake} with project files, if there exists a file
13061 @file{gnat.adc} that contains configuration pragmas, this file will be
13062 ignored.
13064 Configuration pragmas can be defined by means of the following attributes in
13065 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13066 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13068 Both these attributes are single string attributes. Their values is the path
13069 name of a file containing configuration pragmas. If a path name is relative,
13070 then it is relative to the project directory of the project file where the
13071 attribute is defined.
13073 When compiling a source, the configuration pragmas used are, in order,
13074 those listed in the file designated by attribute
13075 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13076 project file, if it is specified, and those listed in the file designated by
13077 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13078 the project file of the source, if it exists.
13080 @node Project Files and Main Subprograms
13081 @subsubsection Project Files and Main Subprograms
13083 @noindent
13084 When using a project file, you can invoke @command{gnatmake}
13085 with one or several main subprograms, by specifying their source files on the
13086 command line.
13088 @smallexample
13089     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13090 @end smallexample
13092 @noindent
13093 Each of these needs to be a source file of the same project, except
13094 when the switch ^-u^/UNIQUE^ is used.
13096 @noindent
13097 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13098 same project, one of the project in the tree rooted at the project specified
13099 on the command line. The package @code{Builder} of this common project, the
13100 "main project" is the one that is considered by @command{gnatmake}.
13102 @noindent
13103 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13104 imported directly or indirectly by the project specified on the command line.
13105 Note that if such a source file is not part of the project specified on the
13106 command line, the ^switches^switches^ found in package @code{Builder} of the
13107 project specified on the command line, if any, that are transmitted
13108 to the compiler will still be used, not those found in the project file of
13109 the source file.
13111 @noindent
13112 When using a project file, you can also invoke @command{gnatmake} without
13113 explicitly specifying any main, and the effect depends on whether you have
13114 defined the @code{Main} attribute.  This attribute has a string list value,
13115 where each element in the list is the name of a source file (the file
13116 extension is optional) that contains a unit that can be a main subprogram.
13118 If the @code{Main} attribute is defined in a project file as a non-empty
13119 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13120 line, then invoking @command{gnatmake} with this project file but without any
13121 main on the command line is equivalent to invoking @command{gnatmake} with all
13122 the file names in the @code{Main} attribute on the command line.
13124 Example:
13125 @smallexample @c projectfile
13126 @group
13127    project Prj is
13128       for Main use ("main1", "main2", "main3");
13129    end Prj;
13130 @end group
13131 @end smallexample
13133 @noindent
13134 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13135 is equivalent to
13136 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13138 When the project attribute @code{Main} is not specified, or is specified
13139 as an empty string list, or when the switch @option{-u} is used on the command
13140 line, then invoking @command{gnatmake} with no main on the command line will
13141 result in all immediate sources of the project file being checked, and
13142 potentially recompiled. Depending on the presence of the switch @option{-u},
13143 sources from other project files on which the immediate sources of the main
13144 project file depend are also checked and potentially recompiled. In other
13145 words, the @option{-u} switch is applied to all of the immediate sources of the
13146 main project file.
13148 When no main is specified on the command line and attribute @code{Main} exists
13149 and includes several mains, or when several mains are specified on the
13150 command line, the default ^switches^switches^ in package @code{Builder} will
13151 be used for all mains, even if there are specific ^switches^switches^
13152 specified for one or several mains.
13154 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13155 the specific ^switches^switches^ for each main, if they are specified.
13157 @node Library Project Files
13158 @subsubsection Library Project Files
13160 @noindent
13161 When @command{gnatmake} is invoked with a main project file that is a library
13162 project file, it is not allowed to specify one or more mains on the command
13163 line.
13165 @noindent
13166 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13167 ^-l^/ACTION=LINK^ have special meanings.
13169 @itemize @bullet
13170 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13171 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13172 library.
13174 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13175 to @command{gnatmake} that the binder generated file should be compiled
13176 (in the case of a stand-alone library) and that the library should be built.
13178 @end itemize
13180 @node The GNAT Driver and Project Files
13181 @subsection The GNAT Driver and Project Files
13183 @noindent
13184 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13185 are project-aware:
13186 @command{^gnatbind^gnatbind^},
13187 @command{^gnatfind^gnatfind^},
13188 @command{^gnatlink^gnatlink^},
13189 @command{^gnatls^gnatls^},
13190 @command{^gnatelim^gnatelim^},
13191 @command{^gnatpp^gnatpp^},
13192 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13193 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13194 They must be invoked through the @command{gnat} driver.
13196 The @command{gnat} driver is a front-end that accepts a number of commands and
13197 call the corresponding tool. It has been designed initially for VMS to convert
13198 VMS style qualifiers to Unix style switches, but it is now available to all
13199 the GNAT supported platforms.
13201 On non VMS platforms, the @command{gnat} driver accepts the following commands
13202 (case insensitive):
13204 @itemize @bullet
13205 @item
13206 BIND to invoke @command{^gnatbind^gnatbind^}
13207 @item
13208 CHOP to invoke @command{^gnatchop^gnatchop^}
13209 @item
13210 CLEAN to invoke @command{^gnatclean^gnatclean^}
13211 @item
13212 COMP or COMPILE to invoke the compiler
13213 @item
13214 ELIM to invoke @command{^gnatelim^gnatelim^}
13215 @item
13216 FIND to invoke @command{^gnatfind^gnatfind^}
13217 @item
13218 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13219 @item
13220 LINK to invoke @command{^gnatlink^gnatlink^}
13221 @item
13222 LS or LIST to invoke @command{^gnatls^gnatls^}
13223 @item
13224 MAKE to invoke @command{^gnatmake^gnatmake^}
13225 @item
13226 NAME to invoke @command{^gnatname^gnatname^}
13227 @item
13228 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13229 @item
13230 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13231 @item
13232 STUB to invoke @command{^gnatstub^gnatstub^}
13233 @item
13234 XREF to invoke @command{^gnatxref^gnatxref^}
13235 @end itemize
13237 @noindent
13238 (note that the compiler is invoked using the command
13239 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13241 @noindent
13242 On non VMS platforms, between @command{gnat} and the command, two
13243 special switches may be used:
13245 @itemize @bullet
13246 @item
13247 @command{-v} to display the invocation of the tool.
13248 @item
13249 @command{-dn} to prevent the @command{gnat} driver from removing
13250 the temporary files it has created. These temporary files are
13251 configuration files and temporary file list files.
13252 @end itemize
13254 @noindent
13255 The command may be followed by switches and arguments for the invoked
13256 tool.
13258 @smallexample
13259   gnat bind -C main.ali
13260   gnat ls -a main
13261   gnat chop foo.txt
13262 @end smallexample
13264 @noindent
13265 Switches may also be put in text files, one switch per line, and the text
13266 files may be specified with their path name preceded by '@@'.
13268 @smallexample
13269    gnat bind @@args.txt main.ali
13270 @end smallexample
13272 @noindent
13273 In addition, for command BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13274 PP or PRETTY and XREF, the project file related switches
13275 (@option{^-P^/PROJECT_FILE^},
13276 @option{^-X^/EXTERNAL_REFERENCE^} and
13277 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13278 the switches of the invoking tool.
13280 @noindent
13281 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13282 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13283 the immediate sources of the specified project file.
13285 @noindent
13286 For each of these commands, there is optionally a corresponding  package
13287 in the main project.
13289 @itemize @bullet
13290 @item
13291 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13293 @item
13294 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13296 @item
13297 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13299 @item
13300 package @code{Eliminate} for command ELIM (invoking
13301 @code{^gnatelim^gnatelim^})
13303 @item
13304 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13306 @item
13307 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13309 @item
13310 package @code{Pretty_Printer} for command PP or PRETTY
13311 (invoking @code{^gnatpp^gnatpp^})
13313 @item
13314 package @code{Cross_Reference} for command XREF (invoking
13315 @code{^gnatxref^gnatxref^})
13317 @end itemize
13319 @noindent
13320 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13321 a simple variable with a string list value. It contains ^switches^switches^
13322 for the invocation of @code{^gnatls^gnatls^}.
13324 @smallexample @c projectfile
13325 @group
13326 project Proj1 is
13327    package gnatls is
13328       for ^Switches^Switches^
13329           use ("^-a^-a^",
13330                "^-v^-v^");
13331    end gnatls;
13332 end Proj1;
13333 @end group
13334 @end smallexample
13336 @noindent
13337 All other packages have two attribute @code{^Switches^Switches^} and
13338 @code{^Default_Switches^Default_Switches^}.
13340 @noindent
13341 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13342 source file name, that has a string list value: the ^switches^switches^ to be
13343 used when the tool corresponding to the package is invoked for the specific
13344 source file.
13346 @noindent
13347 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13348 indexed by  the programming language that has a string list value.
13349 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13350 ^switches^switches^ for the invocation of the tool corresponding
13351 to the package, except if a specific @code{^Switches^Switches^} attribute
13352 is specified for the source file.
13354 @smallexample @c projectfile
13355 @group
13356 project Proj is
13358    for Source_Dirs use ("./**");
13360    package gnatls is
13361       for ^Switches^Switches^ use
13362           ("^-a^-a^",
13363            "^-v^-v^");
13364    end gnatls;
13365 @end group
13366 @group
13368    package Compiler is
13369       for ^Default_Switches^Default_Switches^ ("Ada")
13370           use ("^-gnatv^-gnatv^",
13371                "^-gnatwa^-gnatwa^");
13372    end Binder;
13373 @end group
13374 @group
13376    package Binder is
13377       for ^Default_Switches^Default_Switches^ ("Ada")
13378           use ("^-C^-C^",
13379                "^-e^-e^");
13380    end Binder;
13381 @end group
13382 @group
13384    package Linker is
13385       for ^Default_Switches^Default_Switches^ ("Ada")
13386           use ("^-C^-C^");
13387       for ^Switches^Switches^ ("main.adb")
13388           use ("^-C^-C^",
13389                "^-v^-v^",
13390                "^-v^-v^");
13391    end Linker;
13392 @end group
13393 @group
13395    package Finder is
13396       for ^Default_Switches^Default_Switches^ ("Ada")
13397            use ("^-a^-a^",
13398                 "^-f^-f^");
13399    end Finder;
13400 @end group
13401 @group
13403    package Cross_Reference is
13404       for ^Default_Switches^Default_Switches^ ("Ada")
13405           use ("^-a^-a^",
13406                "^-f^-f^",
13407                "^-d^-d^",
13408                "^-u^-u^");
13409    end Cross_Reference;
13410 end Proj;
13411 @end group
13412 @end smallexample
13414 @noindent
13415 With the above project file, commands such as
13417 @smallexample
13418    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13419    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13420    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13421    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13422    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13423 @end smallexample
13425 @noindent
13426 will set up the environment properly and invoke the tool with the switches
13427 found in the package corresponding to the tool:
13428 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13429 except @code{^Switches^Switches^ ("main.adb")}
13430 for @code{^gnatlink^gnatlink^}.
13432 @ifclear vms
13433 @node Glide and Project Files
13434 @subsection Glide and Project Files
13436 @noindent
13437 Glide will automatically recognize the @file{.gpr} extension for
13438 project files, and will
13439 convert them to its own internal format automatically. However, it
13440 doesn't provide a syntax-oriented editor for modifying these
13441 files.
13442 The project file will be loaded as text when you select the menu item
13443 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13444 You can edit this text and save the @file{gpr} file;
13445 when you next select this project file in Glide it
13446 will be automatically reloaded.
13447 @end ifclear
13449 @c **********************
13450 @node An Extended Example
13451 @section An Extended Example
13453 @noindent
13454 Suppose that we have two programs, @var{prog1} and @var{prog2},
13455 whose sources are in corresponding directories. We would like
13456 to build them with a single @command{gnatmake} command, and we want to place
13457 their object files into @file{build} subdirectories of the source directories.
13458 Furthermore, we want to have to have two separate subdirectories
13459 in @file{build}  -- @file{release} and @file{debug} -- which will contain
13460 the object files compiled with different set of compilation flags.
13462 In other words, we have the following structure:
13464 @smallexample
13465 @group
13466    main
13467      |- prog1
13468      |    |- build
13469      |         | debug
13470      |         | release
13471      |- prog2
13472           |- build
13473                | debug
13474                | release
13475 @end group
13476 @end smallexample
13478 @noindent
13479 Here are the project files that we must place in a directory @file{main}
13480 to maintain this structure:
13482 @enumerate
13484 @item We create a @code{Common} project with a package @code{Compiler} that
13485 specifies the compilation ^switches^switches^:
13487 @smallexample
13488 File "common.gpr":
13489 @group
13490 @b{project} Common @b{is}
13492    @b{for} Source_Dirs @b{use} (); -- No source files
13493 @end group
13495 @group
13496    @b{type} Build_Type @b{is} ("release", "debug");
13497    Build : Build_Type := External ("BUILD", "debug");
13498 @end group
13499 @group
13500    @b{package} Compiler @b{is}
13501       @b{case} Build @b{is}
13502          @b{when} "release" =>
13503            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13504                    @b{use} ("^-O2^-O2^");
13505          @b{when} "debug"   =>
13506            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13507                    @b{use} ("^-g^-g^");
13508       @b{end case};
13509    @b{end} Compiler;
13511 @b{end} Common;
13512 @end group
13513 @end smallexample
13515 @item We create separate projects for the two programs:
13517 @smallexample
13518 @group
13519 File "prog1.gpr":
13521 @b{with} "common";
13522 @b{project} Prog1 @b{is}
13524     @b{for} Source_Dirs @b{use} ("prog1");
13525     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
13527     @b{package} Compiler @b{renames} Common.Compiler;
13529 @b{end} Prog1;
13530 @end group
13531 @end smallexample
13533 @smallexample
13534 @group
13535 File "prog2.gpr":
13537 @b{with} "common";
13538 @b{project} Prog2 @b{is}
13540     @b{for} Source_Dirs @b{use} ("prog2");
13541     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
13543     @b{package} Compiler @b{renames} Common.Compiler;
13545 @end group
13546 @b{end} Prog2;
13547 @end smallexample
13549 @item We create a wrapping project @code{Main}:
13551 @smallexample
13552 @group
13553 File "main.gpr":
13555 @b{with} "common";
13556 @b{with} "prog1";
13557 @b{with} "prog2";
13558 @b{project} Main @b{is}
13560    @b{package} Compiler @b{renames} Common.Compiler;
13562 @b{end} Main;
13563 @end group
13564 @end smallexample
13566 @item Finally we need to create a dummy procedure that @code{with}s (either
13567 explicitly or implicitly) all the sources of our two programs.
13569 @end enumerate
13571 @noindent
13572 Now we can build the programs using the command
13574 @smallexample
13575    gnatmake ^-P^/PROJECT_FILE=^main dummy
13576 @end smallexample
13578 @noindent
13579 for the Debug mode, or
13581 @ifclear vms
13582 @smallexample
13583    gnatmake -Pmain -XBUILD=release
13584 @end smallexample
13585 @end ifclear
13587 @ifset vms
13588 @smallexample
13589    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13590 @end smallexample
13591 @end ifset
13593 @noindent
13594 for the Release mode.
13596 @c ********************************
13597 @c * Project File Complete Syntax *
13598 @c ********************************
13600 @node Project File Complete Syntax
13601 @section Project File Complete Syntax
13603 @smallexample
13604 project ::=
13605   context_clause project_declaration
13607 context_clause ::=
13608   @{with_clause@}
13610 with_clause ::=
13611   @b{with} path_name @{ , path_name @} ;
13613 path_name ::=
13614    string_literal
13616 project_declaration ::=
13617   simple_project_declaration | project_extension
13619 simple_project_declaration ::=
13620   @b{project} <project_>simple_name @b{is}
13621     @{declarative_item@}
13622   @b{end} <project_>simple_name;
13624 project_extension ::=
13625   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
13626     @{declarative_item@}
13627   @b{end} <project_>simple_name;
13629 declarative_item ::=
13630   package_declaration |
13631   typed_string_declaration |
13632   other_declarative_item
13634 package_declaration ::=
13635   package_specification | package_renaming
13637 package_specification ::=
13638   @b{package} package_identifier @b{is}
13639     @{simple_declarative_item@}
13640   @b{end} package_identifier ;
13642 package_identifier ::=
13643   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13644   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
13645   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
13647 package_renaming ::==
13648   @b{package} package_identifier @b{renames}
13649        <project_>simple_name.package_identifier ;
13651 typed_string_declaration ::=
13652   @b{type} <typed_string_>_simple_name @b{is}
13653    ( string_literal @{, string_literal@} );
13655 other_declarative_item ::=
13656   attribute_declaration |
13657   typed_variable_declaration |
13658   variable_declaration |
13659   case_construction
13661 attribute_declaration ::=
13662   full_associative_array_declaration |
13663   @b{for} attribute_designator @b{use} expression ;
13665 full_associative_array_declaration ::=
13666   @b{for} <associative_array_attribute_>simple_name @b{use}
13667   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13669 attribute_designator ::=
13670   <simple_attribute_>simple_name |
13671   <associative_array_attribute_>simple_name ( string_literal )
13673 typed_variable_declaration ::=
13674   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
13676 variable_declaration ::=
13677   <variable_>simple_name := expression;
13679 expression ::=
13680   term @{& term@}
13682 term ::=
13683   literal_string |
13684   string_list |
13685   <variable_>name |
13686   external_value |
13687   attribute_reference
13689 string_literal ::=
13690   (same as Ada)
13692 string_list ::=
13693   ( <string_>expression @{ , <string_>expression @} )
13695 external_value ::=
13696   @b{external} ( string_literal [, string_literal] )
13698 attribute_reference ::=
13699   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
13701 attribute_prefix ::=
13702   @b{project} |
13703   <project_>simple_name | package_identifier |
13704   <project_>simple_name . package_identifier
13706 case_construction ::=
13707   @b{case} <typed_variable_>name @b{is}
13708     @{case_item@}
13709   @b{end case} ;
13711 case_item ::=
13712   @b{when} discrete_choice_list =>
13713       @{case_construction | attribute_declaration@}
13715 discrete_choice_list ::=
13716   string_literal @{| string_literal@} |
13717   @b{others}
13719 name ::=
13720   simple_name @{. simple_name@}
13722 simple_name ::=
13723   identifier (same as Ada)
13725 @end smallexample
13728 @node The Cross-Referencing Tools gnatxref and gnatfind
13729 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13730 @findex gnatxref
13731 @findex gnatfind
13733 @noindent
13734 The compiler generates cross-referencing information (unless
13735 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13736 This information indicates where in the source each entity is declared and
13737 referenced. Note that entities in package Standard are not included, but
13738 entities in all other predefined units are included in the output.
13740 Before using any of these two tools, you need to compile successfully your
13741 application, so that GNAT gets a chance to generate the cross-referencing
13742 information.
13744 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13745 information to provide the user with the capability to easily locate the
13746 declaration and references to an entity. These tools are quite similar,
13747 the difference being that @code{gnatfind} is intended for locating
13748 definitions and/or references to a specified entity or entities, whereas
13749 @code{gnatxref} is oriented to generating a full report of all
13750 cross-references.
13752 To use these tools, you must not compile your application using the
13753 @option{-gnatx} switch on the @file{gnatmake} command line
13754 (see @ref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13755 information will not be generated.
13757 @menu
13758 * gnatxref Switches::
13759 * gnatfind Switches::
13760 * Project Files for gnatxref and gnatfind::
13761 * Regular Expressions in gnatfind and gnatxref::
13762 * Examples of gnatxref Usage::
13763 * Examples of gnatfind Usage::
13764 @end menu
13766 @node gnatxref Switches
13767 @section @code{gnatxref} Switches
13769 @noindent
13770 The command invocation for @code{gnatxref} is:
13771 @smallexample
13772 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13773 @end smallexample
13775 @noindent
13776 where
13778 @table @code
13779 @item sourcefile1, sourcefile2
13780 identifies the source files for which a report is to be generated. The
13781 ``with''ed units will be processed too. You must provide at least one file.
13783 These file names are considered to be regular expressions, so for instance
13784 specifying @file{source*.adb} is the same as giving every file in the current
13785 directory whose name starts with @file{source} and whose extension is
13786 @file{adb}.
13788 You shouldn't specify any directory name, just base names. @command{gnatxref}
13789 and @command{gnatfind} will be able to locate these files by themselves using
13790 the source path. If you specify directories, no result is produced.
13792 @end table
13794 @noindent
13795 The switches can be :
13796 @table @option
13797 @c !sort!
13798 @item ^-a^/ALL_FILES^
13799 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13800 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13801 the read-only files found in the library search path. Otherwise, these files
13802 will be ignored. This option can be used to protect Gnat sources or your own
13803 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13804 much faster, and their output much smaller. Read-only here refers to access
13805 or permissions status in the file system for the current user.
13807 @item -aIDIR
13808 @cindex @option{-aIDIR} (@command{gnatxref})
13809 When looking for source files also look in directory DIR. The order in which
13810 source file search is undertaken is the same as for @file{gnatmake}.
13812 @item -aODIR
13813 @cindex @option{-aODIR} (@command{gnatxref})
13814 When searching for library and object files, look in directory
13815 DIR. The order in which library files are searched is the same as for
13816 @file{gnatmake}.
13818 @item -nostdinc
13819 @cindex @option{-nostdinc} (@command{gnatxref})
13820 Do not look for sources in the system default directory.
13822 @item -nostdlib
13823 @cindex @option{-nostdlib} (@command{gnatxref})
13824 Do not look for library files in the system default directory.
13826 @item --RTS=@var{rts-path}
13827 @cindex @option{--RTS} (@command{gnatxref})
13828 Specifies the default location of the runtime library. Same meaning as the
13829 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13831 @item ^-d^/DERIVED_TYPES^
13832 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13833 If this switch is set @code{gnatxref} will output the parent type
13834 reference for each matching derived types.
13836 @item ^-f^/FULL_PATHNAME^
13837 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13838 If this switch is set, the output file names will be preceded by their
13839 directory (if the file was found in the search path). If this switch is
13840 not set, the directory will not be printed.
13842 @item ^-g^/IGNORE_LOCALS^
13843 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13844 If this switch is set, information is output only for library-level
13845 entities, ignoring local entities. The use of this switch may accelerate
13846 @code{gnatfind} and @code{gnatxref}.
13848 @item -IDIR
13849 @cindex @option{-IDIR} (@command{gnatxref})
13850 Equivalent to @samp{-aODIR -aIDIR}.
13852 @item -pFILE
13853 @cindex @option{-pFILE} (@command{gnatxref})
13854 Specify a project file to use @xref{Project Files}. These project files are
13855 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
13856 project files, you should use gnatxref through the GNAT driver
13857 (@command{gnat xref -Pproject}).
13859 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13860 project file in the current directory.
13862 If a project file is either specified or found by the tools, then the content
13863 of the source directory and object directory lines are added as if they
13864 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13865 and @samp{^-aO^OBJECT_SEARCH^}.
13866 @item ^-u^/UNUSED^
13867 Output only unused symbols. This may be really useful if you give your
13868 main compilation unit on the command line, as @code{gnatxref} will then
13869 display every unused entity and 'with'ed package.
13871 @ifclear vms
13872 @item -v
13873 Instead of producing the default output, @code{gnatxref} will generate a
13874 @file{tags} file that can be used by vi. For examples how to use this
13875 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
13876 to the standard output, thus you will have to redirect it to a file.
13877 @end ifclear
13879 @end table
13881 @noindent
13882 All these switches may be in any order on the command line, and may even
13883 appear after the file names. They need not be separated by spaces, thus
13884 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13885 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13887 @node gnatfind Switches
13888 @section @code{gnatfind} Switches
13890 @noindent
13891 The command line for @code{gnatfind} is:
13893 @smallexample
13894 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
13895       [file1 file2 ...]
13896 @end smallexample
13898 @noindent
13899 where
13901 @table @code
13902 @item pattern
13903 An entity will be output only if it matches the regular expression found
13904 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
13906 Omitting the pattern is equivalent to specifying @samp{*}, which
13907 will match any entity. Note that if you do not provide a pattern, you
13908 have to provide both a sourcefile and a line.
13910 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13911 for matching purposes. At the current time there is no support for
13912 8-bit codes other than Latin-1, or for wide characters in identifiers.
13914 @item sourcefile
13915 @code{gnatfind} will look for references, bodies or declarations
13916 of symbols referenced in @file{sourcefile}, at line @samp{line}
13917 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
13918 for syntax examples.
13920 @item line
13921 is a decimal integer identifying the line number containing
13922 the reference to the entity (or entities) to be located.
13924 @item column
13925 is a decimal integer identifying the exact location on the
13926 line of the first character of the identifier for the
13927 entity reference. Columns are numbered from 1.
13929 @item file1 file2 ...
13930 The search will be restricted to these source files. If none are given, then
13931 the search will be done for every library file in the search path.
13932 These file must appear only after the pattern or sourcefile.
13934 These file names are considered to be regular expressions, so for instance
13935 specifying 'source*.adb' is the same as giving every file in the current
13936 directory whose name starts with 'source' and whose extension is 'adb'.
13938 The location of the spec of the entity will always be displayed, even if it
13939 isn't in one of file1, file2,... The occurrences of the entity in the
13940 separate units of the ones given on the command line will also be displayed.
13942 Note that if you specify at least one file in this part, @code{gnatfind} may
13943 sometimes not be able to find the body of the subprograms...
13945 @end table
13947 @noindent
13948 At least one of 'sourcefile' or 'pattern' has to be present on
13949 the command line.
13951 The following switches are available:
13952 @table @option
13953 @c !sort!
13955 @item ^-a^/ALL_FILES^
13956 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13957 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13958 the read-only files found in the library search path. Otherwise, these files
13959 will be ignored. This option can be used to protect Gnat sources or your own
13960 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13961 much faster, and their output much smaller. Read-only here refers to access
13962 or permission status in the file system for the current user.
13964 @item -aIDIR
13965 @cindex @option{-aIDIR} (@command{gnatfind})
13966 When looking for source files also look in directory DIR. The order in which
13967 source file search is undertaken is the same as for @file{gnatmake}.
13969 @item -aODIR
13970 @cindex @option{-aODIR} (@command{gnatfind})
13971 When searching for library and object files, look in directory
13972 DIR. The order in which library files are searched is the same as for
13973 @file{gnatmake}.
13975 @item -nostdinc
13976 @cindex @option{-nostdinc} (@command{gnatfind})
13977 Do not look for sources in the system default directory.
13979 @item -nostdlib
13980 @cindex @option{-nostdlib} (@command{gnatfind})
13981 Do not look for library files in the system default directory.
13983 @item --RTS=@var{rts-path}
13984 @cindex @option{--RTS} (@command{gnatfind})
13985 Specifies the default location of the runtime library. Same meaning as the
13986 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13988 @item ^-d^/DERIVED_TYPE_INFORMATION^
13989 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13990 If this switch is set, then @code{gnatfind} will output the parent type
13991 reference for each matching derived types.
13993 @item ^-e^/EXPRESSIONS^
13994 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13995 By default, @code{gnatfind} accept the simple regular expression set for
13996 @samp{pattern}. If this switch is set, then the pattern will be
13997 considered as full Unix-style regular expression.
13999 @item ^-f^/FULL_PATHNAME^
14000 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14001 If this switch is set, the output file names will be preceded by their
14002 directory (if the file was found in the search path). If this switch is
14003 not set, the directory will not be printed.
14005 @item ^-g^/IGNORE_LOCALS^
14006 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14007 If this switch is set, information is output only for library-level
14008 entities, ignoring local entities. The use of this switch may accelerate
14009 @code{gnatfind} and @code{gnatxref}.
14011 @item -IDIR
14012 @cindex @option{-IDIR} (@command{gnatfind})
14013 Equivalent to @samp{-aODIR -aIDIR}.
14015 @item -pFILE
14016 @cindex @option{-pFILE} (@command{gnatfind})
14017 Specify a project file (@pxref{Project Files}) to use.
14018 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14019 project file in the current directory.
14021 If a project file is either specified or found by the tools, then the content
14022 of the source directory and object directory lines are added as if they
14023 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14024 @samp{^-aO^/OBJECT_SEARCH^}.
14026 @item ^-r^/REFERENCES^
14027 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14028 By default, @code{gnatfind} will output only the information about the
14029 declaration, body or type completion of the entities. If this switch is
14030 set, the @code{gnatfind} will locate every reference to the entities in
14031 the files specified on the command line (or in every file in the search
14032 path if no file is given on the command line).
14034 @item ^-s^/PRINT_LINES^
14035 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14036 If this switch is set, then @code{gnatfind} will output the content
14037 of the Ada source file lines were the entity was found.
14039 @item ^-t^/TYPE_HIERARCHY^
14040 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14041 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14042 the specified type. It act like -d option but recursively from parent
14043 type to parent type. When this switch is set it is not possible to
14044 specify more than one file.
14046 @end table
14048 @noindent
14049 All these switches may be in any order on the command line, and may even
14050 appear after the file names. They need not be separated by spaces, thus
14051 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14052 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14054 As stated previously, gnatfind will search in every directory in the
14055 search path. You can force it to look only in the current directory if
14056 you specify @code{*} at the end of the command line.
14058 @node Project Files for gnatxref and gnatfind
14059 @section Project Files for @command{gnatxref} and @command{gnatfind}
14061 @noindent
14062 Project files allow a programmer to specify how to compile its
14063 application, where to find sources, etc.  These files are used
14064 @ifclear vms
14065 primarily by the Glide Ada mode, but they can also be used
14066 @end ifclear
14067 by the two tools
14068 @code{gnatxref} and @code{gnatfind}.
14070 A project file name must end with @file{.gpr}. If a single one is
14071 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14072 extract the information from it. If multiple project files are found, none of
14073 them is read, and you have to use the @samp{-p} switch to specify the one
14074 you want to use.
14076 The following lines can be included, even though most of them have default
14077 values which can be used in most cases.
14078 The lines can be entered in any order in the file.
14079 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14080 each line. If you have multiple instances, only the last one is taken into
14081 account.
14083 @table @code
14084 @item src_dir=DIR
14085 [default: @code{"^./^[]^"}]
14086 specifies a directory where to look for source files. Multiple @code{src_dir}
14087 lines can be specified and they will be searched in the order they
14088 are specified.
14090 @item obj_dir=DIR
14091 [default: @code{"^./^[]^"}]
14092 specifies a directory where to look for object and library files. Multiple
14093 @code{obj_dir} lines can be specified, and they will be searched in the order
14094 they are specified
14096 @item comp_opt=SWITCHES
14097 [default: @code{""}]
14098 creates a variable which can be referred to subsequently by using
14099 the @code{$@{comp_opt@}} notation. This is intended to store the default
14100 switches given to @command{gnatmake} and @command{gcc}.
14102 @item bind_opt=SWITCHES
14103 [default: @code{""}]
14104 creates a variable which can be referred to subsequently by using
14105 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14106 switches given to @command{gnatbind}.
14108 @item link_opt=SWITCHES
14109 [default: @code{""}]
14110 creates a variable which can be referred to subsequently by using
14111 the @samp{$@{link_opt@}} notation. This is intended to store the default
14112 switches given to @command{gnatlink}.
14114 @item main=EXECUTABLE
14115 [default: @code{""}]
14116 specifies the name of the executable for the application. This variable can
14117 be referred to in the following lines by using the @samp{$@{main@}} notation.
14119 @ifset vms
14120 @item comp_cmd=COMMAND
14121 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14122 @end ifset
14123 @ifclear vms
14124 @item comp_cmd=COMMAND
14125 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14126 @end ifclear
14127 specifies the command used to compile a single file in the application.
14129 @ifset vms
14130 @item make_cmd=COMMAND
14131 [default: @code{"GNAT MAKE $@{main@}
14132 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14133 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14134 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14135 @end ifset
14136 @ifclear vms
14137 @item make_cmd=COMMAND
14138 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14139  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14140  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14141 @end ifclear
14142 specifies the command used to recompile the whole application.
14144 @item run_cmd=COMMAND
14145 [default: @code{"$@{main@}"}]
14146 specifies the command used to run the application.
14148 @item debug_cmd=COMMAND
14149 [default: @code{"gdb $@{main@}"}]
14150 specifies the command used to debug the application
14152 @end table
14154 @noindent
14155 @command{gnatxref} and @command{gnatfind} only take into account the
14156 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14158 @node Regular Expressions in gnatfind and gnatxref
14159 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
14161 @noindent
14162 As specified in the section about @command{gnatfind}, the pattern can be a
14163 regular expression. Actually, there are to set of regular expressions
14164 which are recognized by the program :
14166 @table @code
14167 @item globbing patterns
14168 These are the most usual regular expression. They are the same that you
14169 generally used in a Unix shell command line, or in a DOS session.
14171 Here is a more formal grammar :
14172 @smallexample
14173 @group
14174 @iftex
14175 @leftskip=.5cm
14176 @end iftex
14177 regexp ::= term
14178 term   ::= elmt            -- matches elmt
14179 term   ::= elmt elmt       -- concatenation (elmt then elmt)
14180 term   ::= *               -- any string of 0 or more characters
14181 term   ::= ?               -- matches any character
14182 term   ::= [char @{char@}] -- matches any character listed
14183 term   ::= [char - char]   -- matches any character in range
14184 @end group
14185 @end smallexample
14187 @item full regular expression
14188 The second set of regular expressions is much more powerful. This is the
14189 type of regular expressions recognized by utilities such a @file{grep}.
14191 The following is the form of a regular expression, expressed in Ada
14192 reference manual style BNF is as follows
14194 @smallexample
14195 @iftex
14196 @leftskip=.5cm
14197 @end iftex
14198 @group
14199 regexp ::= term @{| term@} -- alternation (term or term ...)
14201 term ::= item @{item@}     -- concatenation (item then item)
14203 item ::= elmt              -- match elmt
14204 item ::= elmt *            -- zero or more elmt's
14205 item ::= elmt +            -- one or more elmt's
14206 item ::= elmt ?            -- matches elmt or nothing
14207 @end group
14208 @group
14209 elmt ::= nschar            -- matches given character
14210 elmt ::= [nschar @{nschar@}]   -- matches any character listed
14211 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14212 elmt ::= [char - char]     -- matches chars in given range
14213 elmt ::= \ char            -- matches given character
14214 elmt ::= .                 -- matches any single character
14215 elmt ::= ( regexp )        -- parens used for grouping
14217 char ::= any character, including special characters
14218 nschar ::= any character except ()[].*+?^^^
14219 @end group
14220 @end smallexample
14222 Following are a few examples :
14224 @table @samp
14225 @item abcde|fghi
14226 will match any of the two strings 'abcde' and 'fghi'.
14228 @item abc*d
14229 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14231 @item [a-z]+
14232 will match any string which has only lowercase characters in it (and at
14233 least one character
14235 @end table
14236 @end table
14238 @node Examples of gnatxref Usage
14239 @section Examples of @code{gnatxref} Usage
14241 @subsection General Usage
14243 @noindent
14244 For the following examples, we will consider the following units :
14246 @smallexample @c ada
14247 @group
14248 @cartouche
14249 main.ads:
14250 1: with Bar;
14251 2: package Main is
14252 3:     procedure Foo (B : in Integer);
14253 4:     C : Integer;
14254 5: private
14255 6:     D : Integer;
14256 7: end Main;
14258 main.adb:
14259 1: package body Main is
14260 2:     procedure Foo (B : in Integer) is
14261 3:     begin
14262 4:        C := B;
14263 5:        D := B;
14264 6:        Bar.Print (B);
14265 7:        Bar.Print (C);
14266 8:     end Foo;
14267 9: end Main;
14269 bar.ads:
14270 1: package Bar is
14271 2:     procedure Print (B : Integer);
14272 3: end bar;
14273 @end cartouche
14274 @end group
14275 @end smallexample
14277 @table @code
14279 @noindent
14280 The first thing to do is to recompile your application (for instance, in
14281 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14282 the cross-referencing information.
14283 You can then issue any of the following commands:
14285 @item gnatxref main.adb
14286 @code{gnatxref} generates cross-reference information for main.adb
14287 and every unit 'with'ed by main.adb.
14289 The output would be:
14290 @smallexample
14291 @iftex
14292 @leftskip=0cm
14293 @end iftex
14294 B                                                      Type: Integer
14295   Decl: bar.ads           2:22
14296 B                                                      Type: Integer
14297   Decl: main.ads          3:20
14298   Body: main.adb          2:20
14299   Ref:  main.adb          4:13     5:13     6:19
14300 Bar                                                    Type: Unit
14301   Decl: bar.ads           1:9
14302   Ref:  main.adb          6:8      7:8
14303        main.ads           1:6
14304 C                                                      Type: Integer
14305   Decl: main.ads          4:5
14306   Modi: main.adb          4:8
14307   Ref:  main.adb          7:19
14308 D                                                      Type: Integer
14309   Decl: main.ads          6:5
14310   Modi: main.adb          5:8
14311 Foo                                                    Type: Unit
14312   Decl: main.ads          3:15
14313   Body: main.adb          2:15
14314 Main                                                    Type: Unit
14315   Decl: main.ads          2:9
14316   Body: main.adb          1:14
14317 Print                                                   Type: Unit
14318   Decl: bar.ads           2:15
14319   Ref:  main.adb          6:12     7:12
14320 @end smallexample
14322 @noindent
14323 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14324 its body is in main.adb, line 1, column 14 and is not referenced any where.
14326 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14327 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14329 @item gnatxref package1.adb package2.ads
14330 @code{gnatxref} will generates cross-reference information for
14331 package1.adb, package2.ads and any other package 'with'ed by any
14332 of these.
14334 @end table
14336 @ifclear vms
14337 @subsection Using gnatxref with vi
14339 @code{gnatxref} can generate a tags file output, which can be used
14340 directly from @file{vi}. Note that the standard version of @file{vi}
14341 will not work properly with overloaded symbols. Consider using another
14342 free implementation of @file{vi}, such as @file{vim}.
14344 @smallexample
14345 $ gnatxref -v gnatfind.adb > tags
14346 @end smallexample
14348 @noindent
14349 will generate the tags file for @code{gnatfind} itself (if the sources
14350 are in the search path!).
14352 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14353 (replacing @i{entity} by whatever you are looking for), and vi will
14354 display a new file with the corresponding declaration of entity.
14355 @end ifclear
14357 @node Examples of gnatfind Usage
14358 @section Examples of @code{gnatfind} Usage
14360 @table @code
14362 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14363 Find declarations for all entities xyz referenced at least once in
14364 main.adb. The references are search in every library file in the search
14365 path.
14367 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14368 switch is set)
14370 The output will look like:
14371 @smallexample
14372 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14373 ^directory/^[directory]^main.adb:24:10: xyz <= body
14374 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14375 @end smallexample
14377 @noindent
14378 that is to say, one of the entities xyz found in main.adb is declared at
14379 line 12 of main.ads (and its body is in main.adb), and another one is
14380 declared at line 45 of foo.ads
14382 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14383 This is the same command as the previous one, instead @code{gnatfind} will
14384 display the content of the Ada source file lines.
14386 The output will look like:
14388 @smallexample
14389 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14390    procedure xyz;
14391 ^directory/^[directory]^main.adb:24:10: xyz <= body
14392    procedure xyz is
14393 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14394    xyz : Integer;
14395 @end smallexample
14397 @noindent
14398 This can make it easier to find exactly the location your are looking
14399 for.
14401 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14402 Find references to all entities containing an x that are
14403 referenced on line 123 of main.ads.
14404 The references will be searched only in main.ads and foo.adb.
14406 @item gnatfind main.ads:123
14407 Find declarations and bodies for all entities that are referenced on
14408 line 123 of main.ads.
14410 This is the same as @code{gnatfind "*":main.adb:123}.
14412 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14413 Find the declaration for the entity referenced at column 45 in
14414 line 123 of file main.adb in directory mydir. Note that it
14415 is usual to omit the identifier name when the column is given,
14416 since the column position identifies a unique reference.
14418 The column has to be the beginning of the identifier, and should not
14419 point to any character in the middle of the identifier.
14421 @end table
14424 @c *********************************
14425 @node The GNAT Pretty-Printer gnatpp
14426 @chapter The GNAT Pretty-Printer @command{gnatpp}
14427 @findex gnatpp
14428 @cindex Pretty-Printer
14430 @noindent
14431 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14432 for source reformatting / pretty-printing.
14433 It takes an Ada source file as input and generates a reformatted
14434 version as output.
14435 You can specify various style directives via switches; e.g.,
14436 identifier case conventions, rules of indentation, and comment layout.
14438 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14439 tree for the input source and thus requires the input to be syntactically and
14440 semantically legal.
14441 If this condition is not met, @command{gnatpp} will terminate with an
14442 error message; no output file will be generated.
14444 If the compilation unit
14445 contained in the input source depends semantically upon units located
14446 outside the current directory, you have to provide the source search path
14447 when invoking @command{gnatpp}, if these units are contained in files with
14448 names that do not follow the GNAT file naming rules, you have to provide
14449 the configuration file describing the corresponding naming scheme;
14450 see the description of the @command{gnatpp}
14451 switches below. Another possibility is to use a project file and to
14452 call @command{gnatpp} through the @command{gnat} driver
14454 The @command{gnatpp} command has the form
14456 @smallexample
14457 $ gnatpp [@var{switches}] @var{filename}
14458 @end smallexample
14460 @noindent
14461 where
14462 @itemize @bullet
14463 @item
14464 @var{switches} is an optional sequence of switches defining such properties as
14465 the formatting rules, the source search path, and the destination for the
14466 output source file
14468 @item
14469 @var{filename} is the name (including the extension) of the source file to
14470 reformat; ``wildcards'' or several file names on the same gnatpp command are
14471 allowed.  The file name may contain path information; it does not have to
14472 follow the GNAT file naming rules
14473 @end itemize
14476 @menu
14477 * Switches for gnatpp::
14478 * Formatting Rules::
14479 @end menu
14481 @node Switches for gnatpp
14482 @section Switches for @command{gnatpp}
14484 @noindent
14485 The following subsections describe the various switches accepted by
14486 @command{gnatpp}, organized by category.
14488 @ifclear vms
14489 You specify a switch by supplying a name and generally also a value.
14490 In many cases the values for a switch with a given name are incompatible with
14491 each other
14492 (for example the switch that controls the casing of a reserved word may have
14493 exactly one value: upper case, lower case, or
14494 mixed case) and thus exactly one such switch can be in effect for an
14495 invocation of @command{gnatpp}.
14496 If more than one is supplied, the last one is used.
14497 However, some values for the same switch are mutually compatible.
14498 You may supply several such switches to @command{gnatpp}, but then
14499 each must be specified in full, with both the name and the value.
14500 Abbreviated forms (the name appearing once, followed by each value) are
14501 not permitted.
14502 For example, to set
14503 the alignment of the assignment delimiter both in declarations and in
14504 assignment statements, you must write @option{-A2A3}
14505 (or @option{-A2 -A3}), but not @option{-A23}.
14506 @end ifclear
14508 @ifset vms
14509 In many cases the set of options for a given qualifier are incompatible with
14510 each other (for example the qualifier that controls the casing of a reserved
14511 word may have exactly one option, which specifies either upper case, lower
14512 case, or mixed case), and thus exactly one such option can be in effect for
14513 an invocation of @command{gnatpp}.
14514 If more than one is supplied, the last one is used.
14515 However, some qualifiers have options that are mutually compatible,
14516 and then you may then supply several such options when invoking
14517 @command{gnatpp}.
14518 @end ifset
14520 In most cases, it is obvious whether or not the
14521 ^values for a switch with a given name^options for a given qualifier^
14522 are compatible with each other.
14523 When the semantics might not be evident, the summaries below explicitly
14524 indicate the effect.
14526 @menu
14527 * Alignment Control::
14528 * Casing Control::
14529 * Construct Layout Control::
14530 * General Text Layout Control::
14531 * Other Formatting Options::
14532 * Setting the Source Search Path::
14533 * Output File Control::
14534 * Other gnatpp Switches::
14535 @end menu
14538 @node Alignment Control
14539 @subsection Alignment Control
14540 @cindex Alignment control in @command{gnatpp}
14542 @noindent
14543 Programs can be easier to read if certain constructs are vertically aligned.
14544 By default all alignments are set ON.
14545 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14546 OFF, and then use one or more of the other
14547 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14548 to activate alignment for specific constructs.
14550 @table @option
14551 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14553 @ifset vms
14554 @item /ALIGN=ON
14555 Set all alignments to ON
14556 @end ifset
14558 @item ^-A0^/ALIGN=OFF^
14559 Set all alignments to OFF
14561 @item ^-A1^/ALIGN=COLONS^
14562 Align @code{:} in declarations
14564 @item ^-A2^/ALIGN=DECLARATIONS^
14565 Align @code{:=} in initializations in declarations
14567 @item ^-A3^/ALIGN=STATEMENTS^
14568 Align @code{:=} in assignment statements
14570 @item ^-A4^/ALIGN=ARROWS^
14571 Align @code{=>} in associations
14572 @end table
14574 @noindent
14575 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14576 is allowed.
14579 @node Casing Control
14580 @subsection Casing Control
14581 @cindex Casing control in @command{gnatpp}
14583 @noindent
14584 @command{gnatpp} allows you to specify the casing for reserved words,
14585 pragma names, attribute designators and identifiers.
14586 For identifiers you may define a
14587 general rule for name casing but also override this rule
14588 via a set of dictionary files.
14590 Three types of casing are supported: lower case, upper case, and mixed case.
14591 Lower and upper case are self-explanatory (but since some letters in
14592 Latin1 and other GNAT-supported character sets
14593 exist only in lower-case form, an upper case conversion will have no
14594 effect on them.)
14595 ``Mixed case'' means that the first letter, and also each letter immediately
14596 following an underscore, are converted to their uppercase forms;
14597 all the other letters are converted to their lowercase forms.
14599 @table @option
14600 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14601 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14602 Attribute designators are lower case
14604 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14605 Attribute designators are upper case
14607 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14608 Attribute designators are mixed case (this is the default)
14610 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14611 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14612 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14613 lower case (this is the default)
14615 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14616 Keywords are upper case
14618 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14619 @item ^-nD^/NAME_CASING=AS_DECLARED^
14620 Name casing for defining occurrences are as they appear in the source file
14621 (this is the default)
14623 @item ^-nU^/NAME_CASING=UPPER_CASE^
14624 Names are in upper case
14626 @item ^-nL^/NAME_CASING=LOWER_CASE^
14627 Names are in lower case
14629 @item ^-nM^/NAME_CASING=MIXED_CASE^
14630 Names are in mixed case
14632 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14633 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14634 Pragma names are lower case
14636 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14637 Pragma names are upper case
14639 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14640 Pragma names are mixed case (this is the default)
14642 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14643 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14644 Use @var{file} as a @emph{dictionary file} that defines
14645 the casing for a set of specified names,
14646 thereby overriding the effect on these names by
14647 any explicit or implicit
14648 ^-n^/NAME_CASING^ switch.
14649 To supply more than one dictionary file,
14650 use ^several @option{-D} switches^a list of files as options^.
14652 @noindent
14653 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14654 to define the casing for the Ada predefined names and
14655 the names declared in the GNAT libraries.
14657 @item ^-D-^/SPECIFIC_CASING^
14658 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14659 Do not use the default dictionary file;
14660 instead, use the casing
14661 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14662 dictionary file(s)
14663 @end table
14665 @noindent
14666 The structure of a dictionary file, and details on the conventions
14667 used in the default dictionary file, are defined in @ref{Name Casing}.
14669 The @option{^-D-^/SPECIFIC_CASING^} and
14670 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14671 compatible.
14674 @node Construct Layout Control
14675 @subsection Construct Layout Control
14676 @cindex Layout control in @command{gnatpp}
14678 @noindent
14679 This group of @command{gnatpp} switches controls the layout of comments and
14680 complex syntactic constructs.  See @ref{Formatting Comments}, for details
14681 on their effect.
14683 @table @option
14684 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14685 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14686 All the comments remain unchanged
14688 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14689 GNAT-style comment line indentation (this is the default).
14691 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14692 Reference-manual comment line indentation.
14694 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14695 GNAT-style comment beginning
14697 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14698 Reformat comment blocks
14700 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14701 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14702 GNAT-style layout (this is the default)
14704 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14705 Compact layout
14707 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14708 Uncompact layout
14710 @item ^-notab^/NOTABS^
14711 All the VT characters are removed from the comment text. All the HT characters
14712 are expanded with the sequences of space characters to get to the next tab
14713 stops.
14715 @end table
14717 @ifclear vms
14718 @noindent
14719 The @option{-c1} and @option{-c2} switches are incompatible.
14720 The @option{-c3} and @option{-c4} switches are compatible with each other and
14721 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14722 the other comment formatting switches.
14724 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14725 @end ifclear
14727 @ifset vms
14728 @noindent
14729 For the @option{/COMMENTS_LAYOUT} qualifier:
14730 @itemize @bullet
14731 @item
14732 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14733 @item
14734 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14735 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14736 @end itemize
14738 @noindent
14739 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14740 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14741 @end ifset
14743 @node General Text Layout Control
14744 @subsection General Text Layout Control
14746 @noindent
14747 These switches allow control over line length and indentation.
14749 @table @option
14750 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
14751 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14752 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
14754 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
14755 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14756 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
14758 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
14759 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14760 Indentation level for continuation lines (relative to the line being
14761 continued), @i{nnn} from 1 .. 9.
14762 The default
14763 value is one less then the (normal) indentation level, unless the
14764 indentation is set to 1 (in which case the default value for continuation
14765 line indentation is also 1)
14766 @end table
14769 @node Other Formatting Options
14770 @subsection Other Formatting Options
14772 @noindent
14773 These switches control the inclusion of missing end/exit labels, and
14774 the indentation level in @b{case} statements.
14776 @table @option
14777 @item ^-e^/NO_MISSED_LABELS^
14778 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14779 Do not insert missing end/exit labels. An end label is the name of
14780 a construct that may optionally be repeated at the end of the
14781 construct's declaration;
14782 e.g., the names of packages, subprograms, and tasks.
14783 An exit label is the name of a loop that may appear as target
14784 of an exit statement within the loop.
14785 By default, @command{gnatpp} inserts these end/exit labels when
14786 they are absent from the original source. This option suppresses such
14787 insertion, so that the formatted source reflects the original.
14789 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14790 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14791 Insert a Form Feed character after a pragma Page.
14793 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
14794 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14795 Do not use an additional indentation level for @b{case} alternatives
14796 and variants if there are @i{nnn} or more (the default
14797 value is 10).
14798 If @i{nnn} is 0, an additional indentation level is
14799 used for @b{case} alternatives and variants regardless of their number.
14800 @end table
14802 @node Setting the Source Search Path
14803 @subsection Setting the Source Search Path
14805 @noindent
14806 To define the search path for the input source file, @command{gnatpp}
14807 uses the same switches as the GNAT compiler, with the same effects.
14809 @table @option
14810 @item ^-I^/SEARCH=^@var{dir}
14811 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14812 The same as the corresponding gcc switch
14814 @item ^-I-^/NOCURRENT_DIRECTORY^
14815 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14816 The same as the corresponding gcc switch
14818 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14819 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14820 The same as the corresponding gcc switch
14822 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14823 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14824 The same as the corresponding gcc switch
14826 @end table
14829 @node Output File Control
14830 @subsection Output File Control
14832 @noindent
14833 By default the output is sent to the file whose name is obtained by appending
14834 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14835 (if the file with this name already exists, it is unconditionally overwritten).
14836 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14837 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14838 as output file.
14839 The output may be redirected by the following switches:
14841 @table @option
14842 @item ^-pipe^/STANDARD_OUTPUT^
14843 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14844 Send the output to @code{Standard_Output}
14846 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14847 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14848 Write the output into @var{output_file}.
14849 If @var{output_file} already exists, @command{gnatpp} terminates without
14850 reading or processing the input file.
14852 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14853 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14854 Write the output into @var{output_file}, overwriting the existing file
14855 (if one is present).
14857 @item ^-r^/REPLACE^
14858 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14859 Replace the input source file with the reformatted output, and copy the
14860 original input source into the file whose name is obtained by appending the
14861 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14862 If a file with this name already exists, @command{gnatpp} terminates without
14863 reading or processing the input file.
14865 @item ^-rf^/OVERRIDING_REPLACE^
14866 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14867 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14868 already exists, it is overwritten.
14870 @item ^-rnb^/NO_BACKUP^
14871 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
14872 Replace the input source file with the reformatted output without
14873 creating any backup copy of the input source.
14874 @end table
14876 @noindent
14877 Options @option{^-pipe^/STANDARD_OUTPUT^},
14878 @option{^-o^/OUTPUT^} and
14879 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14880 contains only one file to reformat
14882 @node Other gnatpp Switches
14883 @subsection Other @code{gnatpp} Switches
14885 @noindent
14886 The additional @command{gnatpp} switches are defined in this subsection.
14888 @table @option
14889 @item ^-files @var{filename}^/FILES=@var{output_file}^
14890 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14891 Take the argument source files from the specified file. This file should be an
14892 ordinary textual file containing file names separated by spaces or
14893 line breaks. You can use this switch more then once in the same call to
14894 @command{gnatpp}. You also can combine this switch with explicit list of
14895 files.
14897 @item ^-v^/VERBOSE^
14898 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14899 Verbose mode;
14900 @command{gnatpp} generates version information and then
14901 a trace of the actions it takes to produce or obtain the ASIS tree.
14903 @item ^-w^/WARNINGS^
14904 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14905 Warning mode;
14906 @command{gnatpp} generates a warning whenever it can not provide
14907 a required layout in the result source.
14908 @end table
14911 @node Formatting Rules
14912 @section Formatting Rules
14914 @noindent
14915 The following subsections show how @command{gnatpp} treats ``white space'',
14916 comments, program layout, and name casing.
14917 They provide the detailed descriptions of the switches shown above.
14919 @menu
14920 * White Space and Empty Lines::
14921 * Formatting Comments::
14922 * Construct Layout::
14923 * Name Casing::
14924 @end menu
14927 @node White Space and Empty Lines
14928 @subsection White Space and Empty Lines
14930 @noindent
14931 @command{gnatpp} does not have an option to control space characters.
14932 It will add or remove spaces according to the style illustrated by the
14933 examples in the @cite{Ada Reference Manual}.
14935 The only format effectors
14936 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
14937 that will appear in the output file are platform-specific line breaks,
14938 and also format effectors within (but not at the end of) comments.
14939 In particular, each horizontal tab character that is not inside
14940 a comment will be treated as a space and thus will appear in the
14941 output file as zero or more spaces depending on
14942 the reformatting of the line in which it appears.
14943 The only exception is a Form Feed character, which is inserted after a
14944 pragma @code{Page} when @option{-ff} is set.
14946 The output file will contain no lines with trailing ``white space'' (spaces,
14947 format effectors).
14949 Empty lines in the original source are preserved
14950 only if they separate declarations or statements.
14951 In such contexts, a
14952 sequence of two or more empty lines is replaced by exactly one empty line.
14953 Note that a blank line will be removed if it separates two ``comment blocks''
14954 (a comment block is a sequence of whole-line comments).
14955 In order to preserve a visual separation between comment blocks, use an
14956 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
14957 Likewise, if for some reason you wish to have a sequence of empty lines,
14958 use a sequence of empty comments instead.
14961 @node Formatting Comments
14962 @subsection Formatting Comments
14964 @noindent
14965 Comments in Ada code are of two kinds:
14966 @itemize @bullet
14967 @item
14968 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14969 ``white space'') on a line
14971 @item
14972 an @emph{end-of-line comment}, which follows some other Ada lexical element
14973 on the same line.
14974 @end itemize
14976 @noindent
14977 The indentation of a whole-line comment is that of either
14978 the preceding or following line in
14979 the formatted source, depending on switch settings as will be described below.
14981 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
14982 between the end of the preceding Ada lexical element and the beginning
14983 of the comment as appear in the original source,
14984 unless either the comment has to be split to
14985 satisfy the line length limitation, or else the next line contains a
14986 whole line comment that is considered a continuation of this end-of-line
14987 comment (because it starts at the same position).
14988 In the latter two
14989 cases, the start of the end-of-line comment is moved right to the nearest
14990 multiple of the indentation level.
14991 This may result in a ``line overflow'' (the right-shifted comment extending
14992 beyond the maximum line length), in which case the comment is split as
14993 described below.
14995 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
14996 (GNAT-style comment line indentation)
14997 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
14998 (reference-manual comment line indentation).
14999 With reference-manual style, a whole-line comment is indented as if it
15000 were a declaration or statement at the same place
15001 (i.e., according to the indentation of the preceding line(s)).
15002 With GNAT style, a whole-line comment that is immediately followed by an
15003 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15004 word @b{begin}, is indented based on the construct that follows it.
15006 For example:
15007 @smallexample @c ada
15008 @cartouche
15009 if A then
15010     null;
15011        -- some comment
15012 else
15013    null;
15014 end if;
15015 @end cartouche
15016 @end smallexample
15018 @noindent
15019 Reference-manual indentation produces:
15021 @smallexample @c ada
15022 @cartouche
15023 if A then
15024    null;
15025    --  some comment
15026 else
15027    null;
15028 end if;
15029 @end cartouche
15030 @end smallexample
15032 @noindent
15033 while GNAT-style indentation produces:
15035 @smallexample @c ada
15036 @cartouche
15037 if A then
15038    null;
15039 --  some comment
15040 else
15041    null;
15042 end if;
15043 @end cartouche
15044 @end smallexample
15046 @noindent
15047 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15048 (GNAT style comment beginning) has the following
15049 effect:
15051 @itemize @bullet
15052 @item
15053 For each whole-line comment that does not end with two hyphens,
15054 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15055 to ensure that there are at least two spaces between these hyphens and the
15056 first non-blank character of the comment.
15057 @end itemize
15059 @noindent
15060 For an end-of-line comment, if in the original source the next line is a
15061 whole-line comment that starts at the same position
15062 as the end-of-line comment,
15063 then the whole-line comment (and all whole-line comments
15064 that follow it and that start at the same position)
15065 will start at this position in the output file.
15067 @noindent
15068 That is, if in the original source we have:
15070 @smallexample @c ada
15071 @cartouche
15072 begin
15073 A := B + C;            --  B must be in the range Low1..High1
15074                        --  C must be in the range Low2..High2
15075              --B+C will be in the range Low1+Low2..High1+High2
15076 X := X + 1;
15077 @end cartouche
15078 @end smallexample
15080 @noindent
15081 Then in the formatted source we get
15083 @smallexample @c ada
15084 @cartouche
15085 begin
15086    A := B + C;            --  B must be in the range Low1..High1
15087                           --  C must be in the range Low2..High2
15088    --  B+C will be in the range Low1+Low2..High1+High2
15089    X := X + 1;
15090 @end cartouche
15091 @end smallexample
15093 @noindent
15094 A comment that exceeds the line length limit will be split.
15095 Unless switch
15096 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15097 the line belongs to a reformattable block, splitting the line generates a
15098 @command{gnatpp} warning.
15099 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15100 comments may be reformatted in typical
15101 word processor style (that is, moving words between lines and putting as
15102 many words in a line as possible).
15105 @node Construct Layout
15106 @subsection Construct Layout
15108 @noindent
15109 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15110 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15111 layout on the one hand, and uncompact layout
15112 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15113 can be illustrated by the following examples:
15115 @iftex
15116 @cartouche
15117 @multitable @columnfractions .5 .5
15118 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15120 @item
15121 @smallexample @c ada
15122 type q is record
15123    a : integer;
15124    b : integer;
15125 end record;
15126 @end smallexample
15127 @tab
15128 @smallexample @c ada
15129 type q is
15130    record
15131       a : integer;
15132       b : integer;
15133    end record;
15134 @end smallexample
15136 @item
15137 @smallexample @c ada
15138 Block : declare
15139    A : Integer := 3;
15140 begin
15141    Proc (A, A);
15142 end Block;
15143 @end smallexample
15144 @tab
15145 @smallexample @c ada
15146 Block :
15147    declare
15148       A : Integer := 3;
15149    begin
15150       Proc (A, A);
15151    end Block;
15152 @end smallexample
15154 @item
15155 @smallexample @c ada
15156 Clear : for J in 1 .. 10 loop
15157    A (J) := 0;
15158 end loop Clear;
15159 @end smallexample
15160 @tab
15161 @smallexample @c ada
15162 Clear :
15163    for J in 1 .. 10 loop
15164       A (J) := 0;
15165    end loop Clear;
15166 @end smallexample
15167 @end multitable
15168 @end cartouche
15169 @end iftex
15171 @ifnottex
15172 @smallexample
15173 @cartouche
15174 GNAT style, compact layout              Uncompact layout
15176 type q is record                        type q is
15177    a : integer;                            record
15178    b : integer;                               a : integer;
15179 end record;                                   b : integer;
15180                                            end record;
15183 Block : declare                         Block :
15184    A : Integer := 3;                       declare
15185 begin                                         A : Integer := 3;
15186    Proc (A, A);                            begin
15187 end Block;                                    Proc (A, A);
15188                                            end Block;
15190 Clear : for J in 1 .. 10 loop           Clear :
15191    A (J) := 0;                             for J in 1 .. 10 loop
15192 end loop Clear;                               A (J) := 0;
15193                                            end loop Clear;
15194 @end cartouche
15195 @end smallexample
15196 @end ifnottex
15198 @noindent
15199 A further difference between GNAT style layout and compact layout is that
15200 GNAT style layout inserts empty lines as separation for
15201 compound statements, return statements and bodies.
15204 @node Name Casing
15205 @subsection Name Casing
15207 @noindent
15208 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15209 the same casing as the corresponding defining identifier.
15211 You control the casing for defining occurrences via the
15212 @option{^-n^/NAME_CASING^} switch.
15213 @ifclear vms
15214 With @option{-nD} (``as declared'', which is the default),
15215 @end ifclear
15216 @ifset vms
15217 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15218 @end ifset
15219 defining occurrences appear exactly as in the source file
15220 where they are declared.
15221 The other ^values for this switch^options for this qualifier^ ---
15222 @option{^-nU^UPPER_CASE^},
15223 @option{^-nL^LOWER_CASE^},
15224 @option{^-nM^MIXED_CASE^} ---
15225 result in
15226 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15227 If @command{gnatpp} changes the casing of a defining
15228 occurrence, it analogously changes the casing of all the
15229 usage occurrences of this name.
15231 If the defining occurrence of a name is not in the source compilation unit
15232 currently being processed by @command{gnatpp}, the casing of each reference to
15233 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15234 switch (subject to the dictionary file mechanism described below).
15235 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15236 had affected the
15237 casing for the defining occurrence of the name.
15239 Some names may need to be spelled with casing conventions that are not
15240 covered by the upper-, lower-, and mixed-case transformations.
15241 You can arrange correct casing by placing such names in a
15242 @emph{dictionary file},
15243 and then supplying a @option{^-D^/DICTIONARY^} switch.
15244 The casing of names from dictionary files overrides
15245 any @option{^-n^/NAME_CASING^} switch.
15247 To handle the casing of Ada predefined names and the names from GNAT libraries,
15248 @command{gnatpp} assumes a default dictionary file.
15249 The name of each predefined entity is spelled with the same casing as is used
15250 for the entity in the @cite{Ada Reference Manual}.
15251 The name of each entity in the GNAT libraries is spelled with the same casing
15252 as is used in the declaration of that entity.
15254 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15255 default dictionary file.
15256 Instead, the casing for predefined and GNAT-defined names will be established
15257 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15258 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15259 will appear as just shown,
15260 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15261 To ensure that even such names are rendered in uppercase,
15262 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15263 (or else, less conveniently, place these names in upper case in a dictionary
15264 file).
15266 A dictionary file is
15267 a plain text file; each line in this file can be either a blank line
15268 (containing only space characters and ASCII.HT characters), an Ada comment
15269 line, or the specification of exactly one @emph{casing schema}.
15271 A casing schema is a string that has the following syntax:
15273 @smallexample
15274 @cartouche
15275   @var{casing_schema} ::= @var{identifier} | [*]@var{simple_identifier}[*]
15277   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15278 @end cartouche
15279 @end smallexample
15281 @noindent
15282 (The @code{[]} metanotation stands for an optional part;
15283 see @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15284 @var{identifier} lexical element and the @var{letter_or_digit} category).
15286 The casing schema string can be followed by white space and/or an Ada-style
15287 comment; any amount of white space is allowed before the string.
15289 If a dictionary file is passed as
15290 @ifclear vms
15291 the value of a @option{-D@var{file}} switch
15292 @end ifclear
15293 @ifset vms
15294 an option to the @option{/DICTIONARY} qualifier
15295 @end ifset
15296 then for every
15297 simple name and every identifier, @command{gnatpp} checks if the dictionary
15298 defines the casing for the name or for some of its parts (the term ``subword''
15299 is used below to denote the part of a name which is delimited by ``_'' or by
15300 the beginning or end of the word and which does not contain any ``_'' inside):
15302 @itemize @bullet
15303 @item
15304 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15305 the casing defined by the dictionary; no subwords are checked for this word
15307 @item
15308 for the first subword (that is, for the subword preceding the leftmost
15309 ``_''), @command{gnatpp} checks if the dictionary contains the corresponding
15310 string of the form @code{@var{simple_identifier}*}, and if it does, the
15311 casing of this @var{simple_identifier} is used for this subword
15313 @item
15314 for the last subword (following the rightmost ``_'') @command{gnatpp}
15315 checks if the dictionary contains the corresponding string of the form
15316 @code{*@var{simple_identifier}}, and if it does, the casing of this
15317 @var{simple_identifier} is used for this subword
15319 @item
15320 for every intermediate subword (surrounded by two'_') @command{gnatpp} checks
15321 if the dictionary contains the corresponding string of the form
15322 @code{*@var{simple_identifier}*}, and if it does, the casing of this
15323 simple_identifier is used for this subword
15325 @item
15326 if more than one dictionary file is passed as @command{gnatpp} switches, each
15327 dictionary adds new casing exceptions and overrides all the existing casing
15328 exceptions set by the previous dictionaries
15330 @item
15331 when @command{gnatpp} checks if the word or subword is in the dictionary,
15332 this check is not case sensitive
15333 @end itemize
15335 @noindent
15336 For example, suppose we have the following source to reformat:
15338 @smallexample @c ada
15339 @cartouche
15340 procedure test is
15341    name1 : integer := 1;
15342    name4_name3_name2 : integer := 2;
15343    name2_name3_name4 : Boolean;
15344    name1_var : Float;
15345 begin
15346    name2_name3_name4 := name4_name3_name2 > name1;
15347 end;
15348 @end cartouche
15349 @end smallexample
15351 @noindent
15352 And suppose we have two dictionaries:
15354 @smallexample
15355 @cartouche
15356 @i{dict1:}
15357    NAME1
15358    *NaMe3*
15359    *NAME2
15360 @end cartouche
15362 @cartouche
15363 @i{dict2:}
15364   *NAME3*
15365 @end cartouche
15366 @end smallexample
15368 @noindent
15369 If @command{gnatpp} is called with the following switches:
15371 @smallexample
15372 @ifclear vms
15373 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15374 @end ifclear
15375 @ifset vms
15376 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15377 @end ifset
15378 @end smallexample
15380 @noindent
15381 then we will get the following name casing in the @command{gnatpp} output:
15383 @smallexample @c ada
15384 @cartouche
15385 procedure Test is
15386    NAME1             : Integer := 1;
15387    Name4_NAME3_NAME2 : integer := 2;
15388    Name2_NAME3_Name4 : Boolean;
15389    Name1_Var         : Float;
15390 begin
15391    Name2_NAME3_Name4 := Name4_NAME3_NAME2 > NAME1;
15392 end Test;
15393 @end cartouche
15394 @end smallexample
15398 @c ***********************************
15399 @node File Name Krunching Using gnatkr
15400 @chapter File Name Krunching Using @code{gnatkr}
15401 @findex gnatkr
15403 @noindent
15404 This chapter discusses the method used by the compiler to shorten
15405 the default file names chosen for Ada units so that they do not
15406 exceed the maximum length permitted. It also describes the
15407 @code{gnatkr} utility that can be used to determine the result of
15408 applying this shortening.
15409 @menu
15410 * About gnatkr::
15411 * Using gnatkr::
15412 * Krunching Method::
15413 * Examples of gnatkr Usage::
15414 @end menu
15416 @node About gnatkr
15417 @section About @code{gnatkr}
15419 @noindent
15420 The default file naming rule in GNAT
15421 is that the file name must be derived from
15422 the unit name. The exact default rule is as follows:
15423 @itemize @bullet
15424 @item
15425 Take the unit name and replace all dots by hyphens.
15426 @item
15427 If such a replacement occurs in the
15428 second character position of a name, and the first character is
15429 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
15430 ^~ (tilde)^$ (dollar sign)^
15431 instead of a minus.
15432 @end itemize
15433 The reason for this exception is to avoid clashes
15434 with the standard names for children of System, Ada, Interfaces,
15435 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
15436 respectively.
15438 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15439 switch of the compiler activates a ``krunching''
15440 circuit that limits file names to nn characters (where nn is a decimal
15441 integer). For example, using OpenVMS,
15442 where the maximum file name length is
15443 39, the value of nn is usually set to 39, but if you want to generate
15444 a set of files that would be usable if ported to a system with some
15445 different maximum file length, then a different value can be specified.
15446 The default value of 39 for OpenVMS need not be specified.
15448 The @code{gnatkr} utility can be used to determine the krunched name for
15449 a given file, when krunched to a specified maximum length.
15451 @node Using gnatkr
15452 @section Using @code{gnatkr}
15454 @noindent
15455 The @code{gnatkr} command has the form
15457 @ifclear vms
15458 @smallexample
15459 $ gnatkr @var{name} [@var{length}]
15460 @end smallexample
15461 @end ifclear
15463 @ifset vms
15464 @smallexample
15465 $ gnatkr @var{name} /COUNT=nn
15466 @end smallexample
15467 @end ifset
15469 @noindent
15470 @var{name} is the uncrunched file name, derived from the name of the unit
15471 in the standard manner described in the previous section (i.e. in particular
15472 all dots are replaced by hyphens). The file name may or may not have an
15473 extension (defined as a suffix of the form period followed by arbitrary
15474 characters other than period). If an extension is present then it will
15475 be preserved in the output. For example, when krunching @file{hellofile.ads}
15476 to eight characters, the result will be hellofil.ads.
15478 Note: for compatibility with previous versions of @code{gnatkr} dots may
15479 appear in the name instead of hyphens, but the last dot will always be
15480 taken as the start of an extension. So if @code{gnatkr} is given an argument
15481 such as @file{Hello.World.adb} it will be treated exactly as if the first
15482 period had been a hyphen, and for example krunching to eight characters
15483 gives the result @file{hellworl.adb}.
15485 Note that the result is always all lower case (except on OpenVMS where it is
15486 all upper case). Characters of the other case are folded as required.
15488 @var{length} represents the length of the krunched name. The default
15489 when no argument is given is ^8^39^ characters. A length of zero stands for
15490 unlimited, in other words do not chop except for system files where the
15491 impled crunching length is always eight characters.
15493 @noindent
15494 The output is the krunched name. The output has an extension only if the
15495 original argument was a file name with an extension.
15497 @node Krunching Method
15498 @section Krunching Method
15500 @noindent
15501 The initial file name is determined by the name of the unit that the file
15502 contains. The name is formed by taking the full expanded name of the
15503 unit and replacing the separating dots with hyphens and
15504 using ^lowercase^uppercase^
15505 for all letters, except that a hyphen in the second character position is
15506 replaced by a ^tilde^dollar sign^ if the first character is
15507 ^a, i, g, or s^A, I, G, or S^.
15508 The extension is @code{.ads} for a
15509 specification and @code{.adb} for a body.
15510 Krunching does not affect the extension, but the file name is shortened to
15511 the specified length by following these rules:
15513 @itemize @bullet
15514 @item
15515 The name is divided into segments separated by hyphens, tildes or
15516 underscores and all hyphens, tildes, and underscores are
15517 eliminated. If this leaves the name short enough, we are done.
15519 @item
15520 If the name is too long, the longest segment is located (left-most
15521 if there are two of equal length), and shortened by dropping
15522 its last character. This is repeated until the name is short enough.
15524 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15525 to fit the name into 8 characters as required by some operating systems.
15527 @smallexample
15528 our-strings-wide_fixed 22
15529 our strings wide fixed 19
15530 our string  wide fixed 18
15531 our strin   wide fixed 17
15532 our stri    wide fixed 16
15533 our stri    wide fixe  15
15534 our str     wide fixe  14
15535 our str     wid  fixe  13
15536 our str     wid  fix   12
15537 ou  str     wid  fix   11
15538 ou  st      wid  fix   10
15539 ou  st      wi   fix   9
15540 ou  st      wi   fi    8
15541 Final file name: oustwifi.adb
15542 @end smallexample
15544 @item
15545 The file names for all predefined units are always krunched to eight
15546 characters. The krunching of these predefined units uses the following
15547 special prefix replacements:
15549 @table @file
15550 @item ada-
15551 replaced by @file{^a^A^-}
15553 @item gnat-
15554 replaced by @file{^g^G^-}
15556 @item interfaces-
15557 replaced by @file{^i^I^-}
15559 @item system-
15560 replaced by @file{^s^S^-}
15561 @end table
15563 These system files have a hyphen in the second character position. That
15564 is why normal user files replace such a character with a
15565 ^tilde^dollar sign^, to
15566 avoid confusion with system file names.
15568 As an example of this special rule, consider
15569 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15571 @smallexample
15572 ada-strings-wide_fixed 22
15573 a-  strings wide fixed 18
15574 a-  string  wide fixed 17
15575 a-  strin   wide fixed 16
15576 a-  stri    wide fixed 15
15577 a-  stri    wide fixe  14
15578 a-  str     wide fixe  13
15579 a-  str     wid  fixe  12
15580 a-  str     wid  fix   11
15581 a-  st      wid  fix   10
15582 a-  st      wi   fix   9
15583 a-  st      wi   fi    8
15584 Final file name: a-stwifi.adb
15585 @end smallexample
15586 @end itemize
15588 Of course no file shortening algorithm can guarantee uniqueness over all
15589 possible unit names, and if file name krunching is used then it is your
15590 responsibility to ensure that no name clashes occur. The utility
15591 program @code{gnatkr} is supplied for conveniently determining the
15592 krunched name of a file.
15594 @node Examples of gnatkr Usage
15595 @section Examples of @code{gnatkr} Usage
15597 @smallexample
15598 @iftex
15599 @leftskip=0cm
15600 @end iftex
15601 @ifclear vms
15602 $ gnatkr very_long_unit_name.ads      --> velounna.ads
15603 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15604 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15605 $ gnatkr grandparent-parent-child     --> grparchi
15606 @end ifclear
15607 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15608 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15609 @end smallexample
15611 @node Preprocessing Using gnatprep
15612 @chapter Preprocessing Using @code{gnatprep}
15613 @findex gnatprep
15615 @noindent
15616 The @code{gnatprep} utility provides
15617 a simple preprocessing capability for Ada programs.
15618 It is designed for use with GNAT, but is not dependent on any special
15619 features of GNAT.
15621 @menu
15622 * Using gnatprep::
15623 * Switches for gnatprep::
15624 * Form of Definitions File::
15625 * Form of Input Text for gnatprep::
15626 @end menu
15628 @node Using gnatprep
15629 @section Using @code{gnatprep}
15631 @noindent
15632 To call @code{gnatprep} use
15634 @smallexample
15635 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
15636 @end smallexample
15638 @noindent
15639 where
15640 @table @code
15641 @item infile
15642 is the full name of the input file, which is an Ada source
15643 file containing preprocessor directives.
15645 @item outfile
15646 is the full name of the output file, which is an Ada source
15647 in standard Ada form. When used with GNAT, this file name will
15648 normally have an ads or adb suffix.
15650 @item deffile
15651 is the full name of a text file containing definitions of
15652 symbols to be referenced by the preprocessor. This argument is
15653 optional, and can be replaced by the use of the @option{-D} switch.
15655 @item switches
15656 is an optional sequence of switches as described in the next section.
15657 @end table
15659 @node Switches for gnatprep
15660 @section Switches for @code{gnatprep}
15662 @table @option
15663 @c !sort!
15665 @item ^-b^/BLANK_LINES^
15666 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15667 Causes both preprocessor lines and the lines deleted by
15668 preprocessing to be replaced by blank lines in the output source file,
15669 preserving line numbers in the output file.
15671 @item ^-c^/COMMENTS^
15672 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15673 Causes both preprocessor lines and the lines deleted
15674 by preprocessing to be retained in the output source as comments marked
15675 with the special string @code{"--! "}. This option will result in line numbers
15676 being preserved in the output file.
15678 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15679 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15680 Defines a new symbol, associated with value. If no value is given on the
15681 command line, then symbol is considered to be @code{True}. This switch
15682 can be used in place of a definition file.
15684 @ifset vms
15685 @item /REMOVE
15686 @cindex @option{/REMOVE} (@command{gnatprep})
15687 This is the default setting which causes lines deleted by preprocessing
15688 to be entirely removed from the output file.
15689 @end ifset
15691 @item ^-r^/REFERENCE^
15692 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15693 Causes a @code{Source_Reference} pragma to be generated that
15694 references the original input file, so that error messages will use
15695 the file name of this original file. The use of this switch implies
15696 that preprocessor lines are not to be removed from the file, so its
15697 use will force @option{^-b^/BLANK_LINES^} mode if
15698 @option{^-c^/COMMENTS^}
15699 has not been specified explicitly.
15701 Note that if the file to be preprocessed contains multiple units, then
15702 it will be necessary to @code{gnatchop} the output file from
15703 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15704 in the preprocessed file, it will be respected by
15705 @code{gnatchop ^-r^/REFERENCE^}
15706 so that the final chopped files will correctly refer to the original
15707 input source file for @code{gnatprep}.
15709 @item ^-s^/SYMBOLS^
15710 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15711 Causes a sorted list of symbol names and values to be
15712 listed on the standard output file.
15714 @item ^-u^/UNDEFINED^
15715 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15716 Causes undefined symbols to be treated as having the value FALSE in the context
15717 of a preprocessor test. In the absence of this option, an undefined symbol in
15718 a @code{#if} or @code{#elsif} test will be treated as an error.
15720 @end table
15722 @ifclear vms
15723 @noindent
15724 Note: if neither @option{-b} nor @option{-c} is present,
15725 then preprocessor lines and
15726 deleted lines are completely removed from the output, unless -r is
15727 specified, in which case -b is assumed.
15728 @end ifclear
15730 @node Form of Definitions File
15731 @section Form of Definitions File
15733 @noindent
15734 The definitions file contains lines of the form
15736 @smallexample
15737 symbol := value
15738 @end smallexample
15740 @noindent
15741 where symbol is an identifier, following normal Ada (case-insensitive)
15742 rules for its syntax, and value is one of the following:
15744 @itemize @bullet
15745 @item
15746 Empty, corresponding to a null substitution
15747 @item
15748 A string literal using normal Ada syntax
15749 @item
15750 Any sequence of characters from the set
15751 (letters, digits, period, underline).
15752 @end itemize
15754 @noindent
15755 Comment lines may also appear in the definitions file, starting with
15756 the usual @code{--},
15757 and comments may be added to the definitions lines.
15759 @node Form of Input Text for gnatprep
15760 @section Form of Input Text for @code{gnatprep}
15762 @noindent
15763 The input text may contain preprocessor conditional inclusion lines,
15764 as well as general symbol substitution sequences.
15766 The preprocessor conditional inclusion commands have the form
15768 @smallexample
15769 @group
15770 @cartouche
15771 #if @i{expression} [then]
15772    lines
15773 #elsif @i{expression} [then]
15774    lines
15775 #elsif @i{expression} [then]
15776    lines
15778 #else
15779    lines
15780 #end if;
15781 @end cartouche
15782 @end group
15783 @end smallexample
15785 @noindent
15786 In this example, @i{expression} is defined by the following grammar:
15787 @smallexample
15788 @i{expression} ::=  <symbol>
15789 @i{expression} ::=  <symbol> = "<value>"
15790 @i{expression} ::=  <symbol> = <symbol>
15791 @i{expression} ::=  <symbol> 'Defined
15792 @i{expression} ::=  not @i{expression}
15793 @i{expression} ::=  @i{expression} and @i{expression}
15794 @i{expression} ::=  @i{expression} or @i{expression}
15795 @i{expression} ::=  @i{expression} and then @i{expression}
15796 @i{expression} ::=  @i{expression} or else @i{expression}
15797 @i{expression} ::=  ( @i{expression} )
15798 @end smallexample
15800 @noindent
15801 For the first test (@i{expression} ::= <symbol>) the symbol must have
15802 either the value true or false, that is to say the right-hand of the
15803 symbol definition must be one of the (case-insensitive) literals
15804 @code{True} or @code{False}. If the value is true, then the
15805 corresponding lines are included, and if the value is false, they are
15806 excluded.
15808 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15809 the symbol has been defined in the definition file or by a @option{-D}
15810 switch on the command line. Otherwise, the test is false.
15812 The equality tests are case insensitive, as are all the preprocessor lines.
15814 If the symbol referenced is not defined in the symbol definitions file,
15815 then the effect depends on whether or not switch @option{-u}
15816 is specified. If so, then the symbol is treated as if it had the value
15817 false and the test fails. If this switch is not specified, then
15818 it is an error to reference an undefined symbol. It is also an error to
15819 reference a symbol that is defined with a value other than @code{True}
15820 or @code{False}.
15822 The use of the @code{not} operator inverts the sense of this logical test, so
15823 that the lines are included only if the symbol is not defined.
15824 The @code{then} keyword is optional as shown
15826 The @code{#} must be the first non-blank character on a line, but
15827 otherwise the format is free form. Spaces or tabs may appear between
15828 the @code{#} and the keyword. The keywords and the symbols are case
15829 insensitive as in normal Ada code. Comments may be used on a
15830 preprocessor line, but other than that, no other tokens may appear on a
15831 preprocessor line. Any number of @code{elsif} clauses can be present,
15832 including none at all. The @code{else} is optional, as in Ada.
15834 The @code{#} marking the start of a preprocessor line must be the first
15835 non-blank character on the line, i.e. it must be preceded only by
15836 spaces or horizontal tabs.
15838 Symbol substitution outside of preprocessor lines is obtained by using
15839 the sequence
15841 @smallexample
15842 $symbol
15843 @end smallexample
15845 @noindent
15846 anywhere within a source line, except in a comment or within a
15847 string literal. The identifier
15848 following the @code{$} must match one of the symbols defined in the symbol
15849 definition file, and the result is to substitute the value of the
15850 symbol in place of @code{$symbol} in the output file.
15852 Note that although the substitution of strings within a string literal
15853 is not possible, it is possible to have a symbol whose defined value is
15854 a string literal. So instead of setting XYZ to @code{hello} and writing:
15856 @smallexample
15857 Header : String := "$XYZ";
15858 @end smallexample
15860 @noindent
15861 you should set XYZ to @code{"hello"} and write:
15863 @smallexample
15864 Header : String := $XYZ;
15865 @end smallexample
15867 @noindent
15868 and then the substitution will occur as desired.
15870 @ifset vms
15871 @node The GNAT Run-Time Library Builder gnatlbr
15872 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
15873 @findex gnatlbr
15874 @cindex Library builder
15876 @noindent
15877 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
15878 supplied configuration pragmas.
15880 @menu
15881 * Running gnatlbr::
15882 * Switches for gnatlbr::
15883 * Examples of gnatlbr Usage::
15884 @end menu
15886 @node Running gnatlbr
15887 @section Running @code{gnatlbr}
15889 @noindent
15890 The @code{gnatlbr} command has the form
15892 @smallexample
15893 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
15894 @end smallexample
15896 @node Switches for gnatlbr
15897 @section Switches for @code{gnatlbr}
15899 @noindent
15900 @code{gnatlbr} recognizes the following switches:
15902 @table @option
15903 @c !sort!
15904 @item /CREATE=directory
15905 @cindex @code{/CREATE} (@code{gnatlbr})
15906      Create the new run-time library in the specified directory.
15908 @item /SET=directory
15909 @cindex @code{/SET} (@code{gnatlbr})
15910      Make the library in the specified directory the current run-time
15911      library.
15913 @item /DELETE=directory
15914 @cindex @code{/DELETE} (@code{gnatlbr})
15915      Delete the run-time library in the specified directory.
15917 @item /CONFIG=file
15918 @cindex @code{/CONFIG} (@code{gnatlbr})
15919      With /CREATE:
15920      Use the configuration pragmas in the specified file when building
15921      the library.
15923      With /SET:
15924      Use the configuration pragmas in the specified file when compiling.
15926 @end table
15928 @node Examples of gnatlbr Usage
15929 @section Example of @code{gnatlbr} Usage
15931 @smallexample
15932 Contents of VAXFLOAT.ADC:
15933 pragma Float_Representation (VAX_Float);
15935 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
15937 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
15939 @end smallexample
15940 @end ifset
15942 @node The GNAT Library Browser gnatls
15943 @chapter The GNAT Library Browser @code{gnatls}
15944 @findex gnatls
15945 @cindex Library browser
15947 @noindent
15948 @code{gnatls} is a tool that outputs information about compiled
15949 units. It gives the relationship between objects, unit names and source
15950 files. It can also be used to check the source dependencies of a unit
15951 as well as various characteristics.
15953 @menu
15954 * Running gnatls::
15955 * Switches for gnatls::
15956 * Examples of gnatls Usage::
15957 @end menu
15959 @node Running gnatls
15960 @section Running @code{gnatls}
15962 @noindent
15963 The @code{gnatls} command has the form
15965 @smallexample
15966 $ gnatls switches @var{object_or_ali_file}
15967 @end smallexample
15969 @noindent
15970 The main argument is the list of object or @file{ali} files
15971 (@pxref{The Ada Library Information Files})
15972 for which information is requested.
15974 In normal mode, without additional option, @code{gnatls} produces a
15975 four-column listing. Each line represents information for a specific
15976 object. The first column gives the full path of the object, the second
15977 column gives the name of the principal unit in this object, the third
15978 column gives the status of the source and the fourth column gives the
15979 full path of the source representing this unit.
15980 Here is a simple example of use:
15982 @smallexample
15983 $ gnatls *.o
15984 ^./^[]^demo1.o            demo1            DIF demo1.adb
15985 ^./^[]^demo2.o            demo2             OK demo2.adb
15986 ^./^[]^hello.o            h1                OK hello.adb
15987 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15988 ^./^[]^instr.o            instr             OK instr.adb
15989 ^./^[]^tef.o              tef              DIF tef.adb
15990 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15991 ^./^[]^tgef.o             tgef             DIF tgef.adb
15992 @end smallexample
15994 @noindent
15995 The first line can be interpreted as follows: the main unit which is
15996 contained in
15997 object file @file{demo1.o} is demo1, whose main source is in
15998 @file{demo1.adb}. Furthermore, the version of the source used for the
15999 compilation of demo1 has been modified (DIF). Each source file has a status
16000 qualifier which can be:
16002 @table @code
16003 @item OK (unchanged)
16004 The version of the source file used for the compilation of the
16005 specified unit corresponds exactly to the actual source file.
16007 @item MOK (slightly modified)
16008 The version of the source file used for the compilation of the
16009 specified unit differs from the actual source file but not enough to
16010 require recompilation. If you use gnatmake with the qualifier
16011 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16012 MOK will not be recompiled.
16014 @item DIF (modified)
16015 No version of the source found on the path corresponds to the source
16016 used to build this object.
16018 @item ??? (file not found)
16019 No source file was found for this unit.
16021 @item HID (hidden,  unchanged version not first on PATH)
16022 The version of the source that corresponds exactly to the source used
16023 for compilation has been found on the path but it is hidden by another
16024 version of the same source that has been modified.
16026 @end table
16028 @node Switches for gnatls
16029 @section Switches for @code{gnatls}
16031 @noindent
16032 @code{gnatls} recognizes the following switches:
16034 @table @option
16035 @c !sort!
16036 @item ^-a^/ALL_UNITS^
16037 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
16038 Consider all units, including those of the predefined Ada library.
16039 Especially useful with @option{^-d^/DEPENDENCIES^}.
16041 @item ^-d^/DEPENDENCIES^
16042 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16043 List sources from which specified units depend on.
16045 @item ^-h^/OUTPUT=OPTIONS^
16046 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16047 Output the list of options.
16049 @item ^-o^/OUTPUT=OBJECTS^
16050 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16051 Only output information about object files.
16053 @item ^-s^/OUTPUT=SOURCES^
16054 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16055 Only output information about source files.
16057 @item ^-u^/OUTPUT=UNITS^
16058 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16059 Only output information about compilation units.
16061 @item ^-files^/FILES^=@var{file}
16062 @cindex @option{^-files^/FILES^} (@code{gnatls})
16063 Take as arguments the files listed in text file @var{file}.
16064 Text file @var{file} may contain empty lines that are ignored.
16065 Each non empty line should contain the name of an existing file.
16066 Several such switches may be specified simultaneously.
16068 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16069 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16070 @itemx ^-I^/SEARCH=^@var{dir}
16071 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
16072 @itemx -nostdinc
16073 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16074 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16075 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16076 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16077 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
16078 (see @ref{Switches for gnatmake}).
16080 @item --RTS=@var{rts-path}
16081 @cindex @option{--RTS} (@code{gnatls})
16082 Specifies the default location of the runtime library. Same meaning as the
16083 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
16085 @item ^-v^/OUTPUT=VERBOSE^
16086 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16087 Verbose mode. Output the complete source and object paths. Do not use
16088 the default column layout but instead use long format giving as much as
16089 information possible on each requested units, including special
16090 characteristics such as:
16092 @table @code
16093 @item  Preelaborable
16094 The unit is preelaborable in the Ada 95 sense.
16096 @item No_Elab_Code
16097 No elaboration code has been produced by the compiler for this unit.
16099 @item Pure
16100 The unit is pure in the Ada 95 sense.
16102 @item Elaborate_Body
16103 The unit contains a pragma Elaborate_Body.
16105 @item Remote_Types
16106 The unit contains a pragma Remote_Types.
16108 @item Shared_Passive
16109 The unit contains a pragma Shared_Passive.
16111 @item Predefined
16112 This unit is part of the predefined environment and cannot be modified
16113 by the user.
16115 @item Remote_Call_Interface
16116 The unit contains a pragma Remote_Call_Interface.
16118 @end table
16120 @end table
16122 @node Examples of gnatls Usage
16123 @section Example of @code{gnatls} Usage
16124 @ifclear vms
16126 @noindent
16127 Example of using the verbose switch. Note how the source and
16128 object paths are affected by the -I switch.
16130 @smallexample
16131 $ gnatls -v -I.. demo1.o
16133 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
16135 Source Search Path:
16136    <Current_Directory>
16137    ../
16138    /home/comar/local/adainclude/
16140 Object Search Path:
16141    <Current_Directory>
16142    ../
16143    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
16145 ./demo1.o
16146    Unit =>
16147      Name   => demo1
16148      Kind   => subprogram body
16149      Flags  => No_Elab_Code
16150      Source => demo1.adb    modified
16151 @end smallexample
16153 @noindent
16154 The following is an example of use of the dependency list.
16155 Note the use of the -s switch
16156 which gives a straight list of source files. This can be useful for
16157 building specialized scripts.
16159 @smallexample
16160 $ gnatls -d demo2.o
16161 ./demo2.o   demo2        OK demo2.adb
16162                          OK gen_list.ads
16163                          OK gen_list.adb
16164                          OK instr.ads
16165                          OK instr-child.ads
16167 $ gnatls -d -s -a demo1.o
16168 demo1.adb
16169 /home/comar/local/adainclude/ada.ads
16170 /home/comar/local/adainclude/a-finali.ads
16171 /home/comar/local/adainclude/a-filico.ads
16172 /home/comar/local/adainclude/a-stream.ads
16173 /home/comar/local/adainclude/a-tags.ads
16174 gen_list.ads
16175 gen_list.adb
16176 /home/comar/local/adainclude/gnat.ads
16177 /home/comar/local/adainclude/g-io.ads
16178 instr.ads
16179 /home/comar/local/adainclude/system.ads
16180 /home/comar/local/adainclude/s-exctab.ads
16181 /home/comar/local/adainclude/s-finimp.ads
16182 /home/comar/local/adainclude/s-finroo.ads
16183 /home/comar/local/adainclude/s-secsta.ads
16184 /home/comar/local/adainclude/s-stalib.ads
16185 /home/comar/local/adainclude/s-stoele.ads
16186 /home/comar/local/adainclude/s-stratt.ads
16187 /home/comar/local/adainclude/s-tasoli.ads
16188 /home/comar/local/adainclude/s-unstyp.ads
16189 /home/comar/local/adainclude/unchconv.ads
16190 @end smallexample
16191 @end ifclear
16193 @ifset vms
16194 @smallexample
16195 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16197 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16198 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16199 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16200 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16201 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16202 demo1.adb
16203 gen_list.ads
16204 gen_list.adb
16205 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16206 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16207 instr.ads
16208 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16209 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16210 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16211 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16212 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16213 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16214 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16215 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16216 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16217 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16218 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16219 @end smallexample
16220 @end ifset
16222 @node Cleaning Up Using gnatclean
16223 @chapter Cleaning Up Using @code{gnatclean}
16224 @findex gnatclean
16225 @cindex Cleaning tool
16227 @noindent
16228 @code{gnatclean} is a tool that allows the deletion of files produced by the
16229 compiler, binder and linker, including ALI files, object files, tree files,
16230 expanded source files, library files, interface copy source files, binder
16231 generated files and executable files.
16233 @menu
16234 * Running gnatclean::
16235 * Switches for gnatclean::
16236 * Examples of gnatclean Usage::
16237 @end menu
16239 @node Running gnatclean
16240 @section Running @code{gnatclean}
16242 @noindent
16243 The @code{gnatclean} command has the form:
16245 @smallexample
16246 $ gnatclean switches @var{names}
16247 @end smallexample
16249 @noindent
16250 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16251 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16252 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16254 @noindent
16255 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16256 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16257 the linker. In informative-only mode, specified by switch
16258 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16259 normal mode is listed, but no file is actually deleted.
16261 @node Switches for gnatclean
16262 @section Switches for @code{gnatclean}
16264 @noindent
16265 @code{gnatclean} recognizes the following switches:
16267 @table @option
16268 @c !sort!
16269 @item ^-c^/COMPILER_FILES_ONLY^
16270 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16271 Only attempt to delete the files produced by the compiler, not those produced
16272 by the binder or the linker. The files that are not to be deleted are library
16273 files, interface copy files, binder generated files and executable files.
16275 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16276 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16277 Indicate that ALI and object files should normally be found in directory
16278 @var{dir}.
16280 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16281 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16282 When using project files, if some errors or warnings are detected during
16283 parsing and verbose mode is not in effect (no use of switch
16284 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16285 file, rather than its simple file name.
16287 @item ^-h^/HELP^
16288 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16289 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16291 @item ^-n^/NODELETE^
16292 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16293 Informative-only mode. Do not delete any files. Output the list of the files
16294 that would have been deleted if this switch was not specified.
16296 @item ^-P^/PROJECT_FILE=^@var{project}
16297 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16298 Use project file @var{project}. Only one such switch can be used.
16299 When cleaning a project file, the files produced by the compilation of the
16300 immediate sources or inherited sources of the project files are to be
16301 deleted. This is not depending on the presence or not of executable names
16302 on the command line.
16304 @item ^-q^/QUIET^
16305 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16306 Quiet output. If there are no error, do not ouuput anything, except in
16307 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16308 (switch ^-n^/NODELETE^).
16310 @item ^-r^/RECURSIVE^
16311 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16312 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16313 clean all imported and extended project files, recursively. If this switch
16314 is not specified, only the files related to the main project file are to be
16315 deleted. This switch has no effect if no project file is specified.
16317 @item ^-v^/VERBOSE^
16318 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16319 Verbose mode.
16321 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16322 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16323 Indicates the verbosity of the parsing of GNAT project files.
16324 See @ref{Switches Related to Project Files}.
16326 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16327 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16328 Indicates that external variable @var{name} has the value @var{value}.
16329 The Project Manager will use this value for occurrences of
16330 @code{external(name)} when parsing the project file.
16331 See @ref{Switches Related to Project Files}.
16333 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16334 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16335 When searching for ALI and object files, look in directory
16336 @var{dir}.
16338 @item ^-I^/SEARCH=^@var{dir}
16339 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16340 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16342 @item ^-I-^/NOCURRENT_DIRECTORY^
16343 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16344 @cindex Source files, suppressing search
16345 Do not look for ALI or object files in the directory
16346 where @code{gnatclean} was invoked.
16348 @end table
16350 @node Examples of gnatclean Usage
16351 @section Examples of @code{gnatclean} Usage
16353 @ifclear vms
16354 @node GNAT and Libraries
16355 @chapter GNAT and Libraries
16356 @cindex Library, building, installing, using
16358 @noindent
16359 This chapter describes how to build and use
16360 libraries with GNAT, and also shows how to recompile the GNAT run-time library.
16361 You should be familiar with the
16362 Project Manager facility (see @ref{GNAT Project Manager}) before reading this
16363 chapter.
16365 @menu
16366 * Introduction to Libraries in GNAT::
16367 * General Ada Libraries::
16368 * Stand-alone Ada Libraries::
16369 * Rebuilding the GNAT Run-Time Library::
16370 @end menu
16372 @node Introduction to Libraries in GNAT
16373 @section Introduction to Libraries in GNAT
16375 @noindent
16376 A library is, conceptually, a collection of objects which does not have its
16377 own main thread of execution, but rather provides certain services to the
16378 applications that use it. A library can be either statically linked with the
16379 application, in which case its code is directly included in the application,
16380 or, on platforms that support it, be dynamically linked, in which case
16381 its code is shared by all applications making use of this library.
16383 GNAT supports both types of libraries.
16384 In the static case, the compiled code can be provided in different ways.
16385 The simplest approach is to provide directly the
16386 set of objects resulting from compilation of the library source files.
16387 Alternatively, you can group the objects into an archive using whatever
16388 commands are provided by the operating system. For the latter case,
16389 the objects are grouped into a shared library.
16391 In the GNAT environment, a library has two types of components:
16392 @itemize @bullet
16393 @item
16394 Source files.
16395 @item
16396 Compiled code and @file{ALI} files.
16397 See @ref{The Ada Library Information Files}.
16398 @end itemize
16400 @noindent
16401 A GNAT library may either completely expose its source files to the
16402 compilation context of the user's application.
16403 Alternatively, it may expose
16404 a limited subset of its source files, called @emph{interface units},
16405 in which case the library is referred to as a @emph{stand-alone library}
16406 (see @ref{Stand-alone Ada Libraries}). In addition, GNAT fully supports
16407 foreign libraries, which are only available in the object format.
16409 All compilation units comprising
16410 an application are elaborated, in an order partially defined by Ada language
16411 semantics.
16412 Where possible, GNAT provides facilities
16413 to ensure that compilation units of a library are automatically elaborated;
16414 however, there are cases where this must be responsibility of a user. This will
16415 be addressed in greater detail below.
16417 @node General Ada Libraries
16418 @section General Ada Libraries
16420 @menu
16421 * Building the library::
16422 * Installing the library::
16423 * Using the library::
16424 @end menu
16426 @node Building the library
16427 @subsection Building the library
16429 @noindent
16430 The easiest way to build a library is to use the Project Manager,
16431 which supports a special type of projects called Library Projects
16432 (see @ref{Library Projects}).
16434 A project is considered a library project, when two project-level attributes
16435 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
16436 control different aspects of library configuration, additional optional
16437 project-level attributes can be specified:
16438 @table @code
16439 @item Library_Kind
16440 This attribute controls whether the library is to be static or shared
16442 @item Library_Version
16443 This attribute specifies what is the library version; this value is used
16444 during dynamic linking of shared libraries to determine if the currently
16445 installed versions of the binaries are compatible.
16447 @item Library_Options
16448 @item Library_GCC
16449 These attributes specify additional low-level options to be used during
16450 library generation, and redefine the actual application used to generate
16451 library.
16452 @end table
16454 @noindent
16455 The GNAT Project Manager takes full care of the library maintenance task,
16456 including recompilation of the source files for which objects do not exist
16457 or are not up to date, assembly of the library archive, and installation of
16458 the library, i.e. copying associated source, object and @file{ALI} files
16459 to the specified location.
16461 It is not entirely trivial to correctly perform all the steps required to
16462 produce a library. We recommend that you use the GNAT Project Manager
16463 for this task. In special cases where this is not desired, the necessary
16464 steps are discussed below.
16466 There are various possibilities for compiling the units that make up the
16467 library: for example with a Makefile (see @ref{Using the GNU make Utility})
16468 or with a conventional script.
16469 For simple libraries, it is also possible to create a
16470 dummy main program which depends upon all the packages that comprise the
16471 interface of the library. This dummy main program can then be given to
16472 @command{gnatmake}, which will ensure that all necessary objects are built.
16474 After this task is accomplished, you should follow the standard procedure
16475 of the underlying operating system to produce the static or shared library.
16477 Here is an example of such a dummy program:
16478 @smallexample @c ada
16479 @group
16480 with My_Lib.Service1;
16481 with My_Lib.Service2;
16482 with My_Lib.Service3;
16483 procedure My_Lib_Dummy is
16484 begin
16485    null;
16486 end;
16487 @end group
16488 @end smallexample
16490 @noindent
16491 Here are the generic commands that will build an archive or a shared library.
16493 @smallexample
16494 # compiling the library
16495 $ gnatmake -c my_lib_dummy.adb
16497 # we don't need the dummy object itself
16498 $ rm my_lib_dummy.o my_lib_dummy.ali
16500 # create an archive with the remaining objects
16501 $ ar rc libmy_lib.a *.o
16502 # some systems may require "ranlib" to be run as well
16504 # or create a shared library
16505 $ gcc -shared -o libmy_lib.so *.o
16506 # some systems may require the code to have been compiled with -fPIC
16508 # remove the object files that are now in the library
16509 $ rm *.o
16511 # Make the ALI files read-only so that gnatmake will not try to
16512 # regenerate the objects that are in the library
16513 $ chmod -w *.ali
16514 @end smallexample
16516 @noindent
16517 Please note that the library must have a name of the form @file{libxxx.a} or
16518 @file{libxxx.so} in order to be accessed by the directive @option{-lxxx}
16519 at link time.
16521 @node Installing the library
16522 @subsection Installing the library
16524 @noindent
16525 In the GNAT model, installing a library consists in copying into a specific
16526 location the files that make up this library. When the library is built using
16527 projects, it is automatically installed in the location specified in the
16528 project by means of the attribute @code{Library_Dir},
16529 otherwise the user must specify the destination.
16530 GNAT also supports installing the sources in a
16531 different directory from the other files (@file{ALI}, objects, archives)
16532 since the source path and the object path can be specified separately.
16534 The system administrator can place general purpose libraries in the default
16535 compiler paths, by specifying the libraries' location in the configuration
16536 files @file{ada_source_path} and @file{ada_object_path}.
16537 These configuration files must be located in the GNAT
16538 installation tree at the same place as the gcc spec file. The location of
16539 the gcc spec file can be determined as follows:
16540 @smallexample
16541 $ gcc -v
16542 @end smallexample
16544 @noindent
16545 The configuration files mentioned above have a simple format: each line
16546 must contain one unique directory name.
16547 Those names are added to the corresponding path
16548 in their order of appearance in the file. The names can be either absolute
16549 or relative; in the latter case, they are relative to where theses files
16550 are located.
16552 The files @file{ada_source_path} and @file{ada_object_path} might not be
16553 present in a
16554 GNAT installation, in which case, GNAT will look for its run-time library in
16555 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
16556 objects and @file{ALI} files). When the files exist, the compiler does not
16557 look in @file{adainclude} and @file{adalib}, and thus the
16558 @file{ada_source_path} file
16559 must contain the location for the GNAT run-time sources (which can simply
16560 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16561 contain the location for the GNAT run-time objects (which can simply
16562 be @file{adalib}).
16564 You can also specify a new default path to the run-time library at compilation
16565 time with the switch @option{--RTS=rts-path}. You can thus choose / change
16566 the run-time library you want your program to be compiled with. This switch is
16567 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
16568 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
16570 It is possible to install a library before or after the standard GNAT
16571 library, by reordering the lines in the configuration files. In general, a
16572 library must be installed before the GNAT library if it redefines
16573 any part of it.
16576 @node Using the library
16577 @subsection Using the library
16579 @noindent
16580 Once again, the project facility greatly simplifies the addition of libraries
16581 to the compilation. If the project file for an application lists a library
16582 project in its @code{with} clause, the Project Manager will ensure that the
16583 library files are consistent, and that they are considered during the
16584 compilation and linking of the application.
16586 Even if you have a third-party, non-Ada library, you can still use GNAT's
16587 Project Manager facility to provide a wrapper for it. The following project for
16588 example, when @code{with}ed in your main project, will link with the
16589 third-party library @file{liba.a}:
16591 @smallexample @c projectfile
16592 @group
16593 project Liba is
16594    for Source_Dirs use ();
16595    for Library_Dir use "lib";
16596    for Library_Name use "a";
16597    for Library_Kind use "static";
16598 end Liba;
16599 @end group
16600 @end smallexample
16602 @noindent
16603 In order to use an Ada library manually, you need to make sure that this
16604 library is on both your source and object path
16605 (see @ref{Search Paths and the Run-Time Library (RTL)},
16606 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
16607 in an archive or a shared library, you need to specify the desired
16608 library at link time.
16610 For example, you can use the library @file{mylib} installed in
16611 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16613 @smallexample
16614 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16615   -largs -lmy_lib
16616 @end smallexample
16618 @noindent
16619 This can be expressed more simply:
16620 @smallexample
16621 $ gnatmake my_appl
16622 @end smallexample
16623 @noindent
16624 when the following conditions are met:
16625 @itemize @bullet
16626 @item
16627 @file{/dir/my_lib_src} has been added by the user to the environment
16628 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
16629 @file{ada_source_path}
16630 @item
16631 @file{/dir/my_lib_obj} has been added by the user to the environment
16632 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
16633 @file{ada_object_path}
16634 @item
16635 a pragma @code{Linker_Options} has been added to one of the sources.
16636 For example:
16638 @smallexample @c ada
16639 pragma Linker_Options ("-lmy_lib");
16640 @end smallexample
16641 @end itemize
16644 @node Stand-alone Ada Libraries
16645 @section Stand-alone Ada Libraries
16646 @cindex Stand-alone library, building, using
16648 @menu
16649 * Introduction to Stand-alone Libraries::
16650 * Building a Stand-alone Library::
16651 * Creating a Stand-alone Library to be used in a non-Ada context::
16652 * Restrictions in Stand-alone Libraries::
16653 @end menu
16655 @node Introduction to Stand-alone Libraries
16656 @subsection Introduction to Stand-alone Libraries
16658 @noindent
16659 A Stand-alone Library (SAL) is a library that contains the necessary code to
16660 elaborate the Ada units that are included in the library. In contrast with
16661 an ordinary library, which consists of all sources, objects and @file{ALI}
16662 files of the
16663 library, a SAL may specify a restricted subset of compilation units
16664 to serve as a library interface. In this case, the fully
16665 self-sufficient set of files will normally consist of an objects
16666 archive, the sources of interface units' specs, and the @file{ALI}
16667 files of interface units.
16668 If an interface spec contains a generic unit or an inlined subprogram,
16669 the body's
16670 source must also be provided; if the units that must be provided in the source
16671 form depend on other units, the source and @file{ALI} files of those must
16672 also be provided.
16674 The main purpose of a SAL is to minimize the recompilation overhead of client
16675 applications when a new version of the library is installed. Specifically,
16676 if the interface sources have not changed, client applications do not need to
16677 be recompiled. If, furthermore, a SAL is provided in the shared form and its
16678 version, controlled by @code{Library_Version} attribute, is not changed,
16679 then the clients do not need to be relinked.
16681 SALs also allow the library providers to minimize the amount of library source
16682 text exposed to the clients.  Such ``information hiding'' might be useful or
16683 necessary for various reasons.
16685 Stand-alone libraries are also well suited to be used in an executable whose
16686 main routine is not written in Ada.
16688 @node Building a Stand-alone Library
16689 @subsection Building a Stand-alone Library
16691 @noindent
16692 GNAT's Project facility provides a simple way of building and installing
16693 stand-alone libraries; see @ref{Stand-alone Library Projects}.
16694 To be a Stand-alone Library Project, in addition to the two attributes
16695 that make a project a Library Project (@code{Library_Name} and
16696 @code{Library_Dir}; see @ref{Library Projects}), the attribute
16697 @code{Library_Interface} must be defined.  For example:
16699 @smallexample @c projectfile
16700 @group
16701    for Library_Dir use "lib_dir";
16702    for Library_Name use "dummy";
16703    for Library_Interface use ("int1", "int1.child");
16704 @end group
16705 @end smallexample
16707 @noindent
16708 Attribute @code{Library_Interface} has a non empty string list value,
16709 each string in the list designating a unit contained in an immediate source
16710 of the project file.
16712 When a Stand-alone Library is built, first the binder is invoked to build
16713 a package whose name depends on the library name
16714 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16715 This binder-generated package includes initialization and
16716 finalization procedures whose
16717 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16718 in the example
16719 above). The object corresponding to this package is included in the library.
16721 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16722 calling of these procedures if a static SAL is built, or if a shared SAL
16723 is built
16724 with the project-level attribute @code{Library_Auto_Init} set to
16725 @code{"false"}.
16727 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16728 (those that are listed in attribute @code{Library_Interface}) are copied to
16729 the Library Directory. As a consequence, only the Interface Units may be
16730 imported from Ada units outside of the library. If other units are imported,
16731 the binding phase will fail.
16733 The attribute @code{Library_Src_Dir} may be specified for a
16734 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16735 single string value. Its value must be the path (absolute or relative to the
16736 project directory) of an existing directory. This directory cannot be the
16737 object directory or one of the source directories, but it can be the same as
16738 the library directory. The sources of the Interface
16739 Units of the library that are needed by an Ada client of the library will be
16740 copied to the designated directory, called the Interface Copy directory.
16741 These sources includes the specs of the Interface Units, but they may also
16742 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16743 are used, or when there is a generic unit in the spec. Before the sources
16744 are copied to the Interface Copy directory, an attempt is made to delete all
16745 files in the Interface Copy directory.
16747 Building stand-alone libraries by hand is somewhat tedious, but for those
16748 occasions when it is necessary here are the steps that you need to perform:
16749 @itemize @bullet
16750 @item
16751 Compile all library sources.
16753 @item
16754 Invoke the binder with the switch @option{-n} (No Ada main program),
16755 with all the @file{ALI} files of the interfaces, and
16756 with the switch @option{-L} to give specific names to the @code{init}
16757 and @code{final} procedures.  For example:
16758 @smallexample
16759   gnatbind -n int1.ali int2.ali -Lsal1
16760 @end smallexample
16762 @item
16763 Compile the binder generated file:
16764 @smallexample
16765   gcc -c b~int2.adb
16766 @end smallexample
16768 @item
16769 Link the dynamic library with all the necessary object files,
16770 indicating to the linker the names of the @code{init} (and possibly
16771 @code{final}) procedures for automatic initialization (and finalization).
16772 The built library should be placed in a directory different from
16773 the object directory.
16775 @item
16776 Copy the @code{ALI} files of the interface to the library directory,
16777 add in this copy an indication that it is an interface to a SAL
16778 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
16779 with letter ``P'') and make the modified copy of the @file{ALI} file
16780 read-only.
16781 @end itemize
16783 @noindent
16784 Using SALs is not different from using other libraries
16785 (see @ref{Using the library}).
16787 @node Creating a Stand-alone Library to be used in a non-Ada context
16788 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16790 @noindent
16791 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16792 a non-Ada context.
16794 The only extra step required is to ensure that library interface subprograms
16795 are compatible with the main program, by means of @code{pragma Export}
16796 or @code{pragma Convention}.
16798 Here is an example of simple library interface for use with C main program:
16800 @smallexample @c ada
16801 package Interface is
16803    procedure Do_Something;
16804    pragma Export (C, Do_Something, "do_something");
16806    procedure Do_Something_Else;
16807    pragma Export (C, Do_Something_Else, "do_something_else");
16809 end Interface;
16810 @end smallexample
16812 @noindent
16813 On the foreign language side, you must provide a ``foreign'' view of the
16814 library interface; remember that it should contain elaboration routines in
16815 addition to interface subprograms.
16817 The example below shows the content of @code{mylib_interface.h} (note
16818 that there is no rule for the naming of this file, any name can be used)
16819 @smallexample
16820 /* the library elaboration procedure */
16821 extern void mylibinit (void);
16823 /* the library finalization procedure */
16824 extern void mylibfinal (void);
16826 /* the interface exported by the library */
16827 extern void do_something (void);
16828 extern void do_something_else (void);
16829 @end smallexample
16831 @noindent
16832 Libraries built as explained above can be used from any program, provided
16833 that the elaboration procedures (named @code{mylibinit} in the previous
16834 example) are called before the library services are used. Any number of
16835 libraries can be used simultaneously, as long as the elaboration
16836 procedure of each library is called.
16838 Below is an example of C program that uses the @code{mylib} library.
16840 @smallexample
16841 #include "mylib_interface.h"
16844 main (void)
16846    /* First, elaborate the library before using it */
16847    mylibinit ();
16849    /* Main program, using the library exported entities */
16850    do_something ();
16851    do_something_else ();
16853    /* Library finalization at the end of the program */
16854    mylibfinal ();
16855    return 0;
16857 @end smallexample
16859 @noindent
16860 Note that invoking any library finalization procedure generated by
16861 @code{gnatbind} shuts down the Ada run-time environment.
16862 Consequently, the
16863 finalization of all Ada libraries must be performed at the end of the program.
16864 No call to these libraries nor to the Ada run-time library should be made
16865 after the finalization phase.
16867 @node Restrictions in Stand-alone Libraries
16868 @subsection Restrictions in Stand-alone Libraries
16870 @noindent
16871 The pragmas listed below should be used with caution inside libraries,
16872 as they can create incompatibilities with other Ada libraries:
16873 @itemize @bullet
16874 @item pragma @code{Locking_Policy}
16875 @item pragma @code{Queuing_Policy}
16876 @item pragma @code{Task_Dispatching_Policy}
16877 @item pragma @code{Unreserve_All_Interrupts}
16878 @end itemize
16880 @noindent
16881 When using a library that contains such pragmas, the user must make sure
16882 that all libraries use the same pragmas with the same values. Otherwise,
16883 @code{Program_Error} will
16884 be raised during the elaboration of the conflicting
16885 libraries. The usage of these pragmas and its consequences for the user
16886 should therefore be well documented.
16888 Similarly, the traceback in the exception occurrence mechanism should be
16889 enabled or disabled in a consistent manner across all libraries.
16890 Otherwise, Program_Error will be raised during the elaboration of the
16891 conflicting libraries.
16893 If the @code{Version} or @code{Body_Version}
16894 attributes are used inside a library, then you need to
16895 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16896 libraries, so that version identifiers can be properly computed.
16897 In practice these attributes are rarely used, so this is unlikely
16898 to be a consideration.
16900 @node  Rebuilding the GNAT Run-Time Library
16901 @section Rebuilding the GNAT Run-Time Library
16902 @cindex GNAT Run-Time Library, rebuilding
16904 @noindent
16905 It may be useful to recompile the GNAT library in various contexts, the
16906 most important one being the use of partition-wide configuration pragmas
16907 such as @code{Normalize_Scalars}. A special Makefile called
16908 @code{Makefile.adalib} is provided to that effect and can be found in
16909 the directory containing the GNAT library. The location of this
16910 directory depends on the way the GNAT environment has been installed and can
16911 be determined by means of the command:
16913 @smallexample
16914 $ gnatls -v
16915 @end smallexample
16917 @noindent
16918 The last entry in the object search path usually contains the
16919 gnat library. This Makefile contains its own documentation and in
16920 particular the set of instructions needed to rebuild a new library and
16921 to use it.
16924 @node Using the GNU make Utility
16925 @chapter Using the GNU @code{make} Utility
16926 @findex make
16928 @noindent
16929 This chapter offers some examples of makefiles that solve specific
16930 problems. It does not explain how to write a makefile (see the GNU make
16931 documentation), nor does it try to replace the @code{gnatmake} utility
16932 (@pxref{The GNAT Make Program gnatmake}).
16934 All the examples in this section are specific to the GNU version of
16935 make. Although @code{make} is a standard utility, and the basic language
16936 is the same, these examples use some advanced features found only in
16937 @code{GNU make}.
16939 @menu
16940 * Using gnatmake in a Makefile::
16941 * Automatically Creating a List of Directories::
16942 * Generating the Command Line Switches::
16943 * Overcoming Command Line Length Limits::
16944 @end menu
16946 @node Using gnatmake in a Makefile
16947 @section Using gnatmake in a Makefile
16948 @findex makefile
16949 @cindex GNU make
16951 @noindent
16952 Complex project organizations can be handled in a very powerful way by
16953 using GNU make combined with gnatmake. For instance, here is a Makefile
16954 which allows you to build each subsystem of a big project into a separate
16955 shared library. Such a makefile allows you to significantly reduce the link
16956 time of very big applications while maintaining full coherence at
16957 each step of the build process.
16959 The list of dependencies are handled automatically by
16960 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
16961 the appropriate directories.
16963 Note that you should also read the example on how to automatically
16964 create the list of directories
16965 (@pxref{Automatically Creating a List of Directories})
16966 which might help you in case your project has a lot of subdirectories.
16968 @smallexample
16969 @iftex
16970 @leftskip=0cm
16971 @font@heightrm=cmr8
16972 @heightrm
16973 @end iftex
16974 ## This Makefile is intended to be used with the following directory
16975 ## configuration:
16976 ##  - The sources are split into a series of csc (computer software components)
16977 ##    Each of these csc is put in its own directory.
16978 ##    Their name are referenced by the directory names.
16979 ##    They will be compiled into shared library (although this would also work
16980 ##    with static libraries
16981 ##  - The main program (and possibly other packages that do not belong to any
16982 ##    csc is put in the top level directory (where the Makefile is).
16983 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16984 ##                    \_ second_csc (sources) __ lib (will contain the library)
16985 ##                    \_ ...
16986 ## Although this Makefile is build for shared library, it is easy to modify
16987 ## to build partial link objects instead (modify the lines with -shared and
16988 ## gnatlink below)
16990 ## With this makefile, you can change any file in the system or add any new
16991 ## file, and everything will be recompiled correctly (only the relevant shared
16992 ## objects will be recompiled, and the main program will be re-linked).
16994 # The list of computer software component for your project. This might be
16995 # generated automatically.
16996 CSC_LIST=aa bb cc
16998 # Name of the main program (no extension)
16999 MAIN=main
17001 # If we need to build objects with -fPIC, uncomment the following line
17002 #NEED_FPIC=-fPIC
17004 # The following variable should give the directory containing libgnat.so
17005 # You can get this directory through 'gnatls -v'. This is usually the last
17006 # directory in the Object_Path.
17007 GLIB=...
17009 # The directories for the libraries
17010 # (This macro expands the list of CSC to the list of shared libraries, you
17011 # could simply use the expanded form :
17012 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17013 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17015 $@{MAIN@}: objects $@{LIB_DIR@}
17016     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17017     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17019 objects::
17020     # recompile the sources
17021     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17023 # Note: In a future version of GNAT, the following commands will be simplified
17024 # by a new tool, gnatmlib
17025 $@{LIB_DIR@}:
17026     mkdir -p $@{dir $@@ @}
17027     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17028     cd $@{dir $@@ @}; cp -f ../*.ali .
17030 # The dependencies for the modules
17031 # Note that we have to force the expansion of *.o, since in some cases
17032 # make won't be able to do it itself.
17033 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17034 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17035 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17037 # Make sure all of the shared libraries are in the path before starting the
17038 # program
17039 run::
17040     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17042 clean::
17043     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17044     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17045     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17046     $@{RM@} *.o *.ali $@{MAIN@}
17047 @end smallexample
17049 @node Automatically Creating a List of Directories
17050 @section Automatically Creating a List of Directories
17052 @noindent
17053 In most makefiles, you will have to specify a list of directories, and
17054 store it in a variable. For small projects, it is often easier to
17055 specify each of them by hand, since you then have full control over what
17056 is the proper order for these directories, which ones should be
17057 included...
17059 However, in larger projects, which might involve hundreds of
17060 subdirectories, it might be more convenient to generate this list
17061 automatically.
17063 The example below presents two methods. The first one, although less
17064 general, gives you more control over the list. It involves wildcard
17065 characters, that are automatically expanded by @code{make}. Its
17066 shortcoming is that you need to explicitly specify some of the
17067 organization of your project, such as for instance the directory tree
17068 depth, whether some directories are found in a separate tree,...
17070 The second method is the most general one. It requires an external
17071 program, called @code{find}, which is standard on all Unix systems. All
17072 the directories found under a given root directory will be added to the
17073 list.
17075 @smallexample
17076 @iftex
17077 @leftskip=0cm
17078 @font@heightrm=cmr8
17079 @heightrm
17080 @end iftex
17081 # The examples below are based on the following directory hierarchy:
17082 # All the directories can contain any number of files
17083 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17084 #                       ->  ab
17085 #                       ->  ac
17086 #                ->  b  ->  ba  ->  baa
17087 #                       ->  bb
17088 #                       ->  bc
17089 # This Makefile creates a variable called DIRS, that can be reused any time
17090 # you need this list (see the other examples in this section)
17092 # The root of your project's directory hierarchy
17093 ROOT_DIRECTORY=.
17095 ####
17096 # First method: specify explicitly the list of directories
17097 # This allows you to specify any subset of all the directories you need.
17098 ####
17100 DIRS := a/aa/ a/ab/ b/ba/
17102 ####
17103 # Second method: use wildcards
17104 # Note that the argument(s) to wildcard below should end with a '/'.
17105 # Since wildcards also return file names, we have to filter them out
17106 # to avoid duplicate directory names.
17107 # We thus use make's @code{dir} and @code{sort} functions.
17108 # It sets DIRs to the following value (note that the directories aaa and baa
17109 # are not given, unless you change the arguments to wildcard).
17110 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17111 ####
17113 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17114                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17116 ####
17117 # Third method: use an external program
17118 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17119 # This is the most complete command: it sets DIRs to the following value:
17120 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17121 ####
17123 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17125 @end smallexample
17127 @node Generating the Command Line Switches
17128 @section Generating the Command Line Switches
17130 @noindent
17131 Once you have created the list of directories as explained in the
17132 previous section (@pxref{Automatically Creating a List of Directories}),
17133 you can easily generate the command line arguments to pass to gnatmake.
17135 For the sake of completeness, this example assumes that the source path
17136 is not the same as the object path, and that you have two separate lists
17137 of directories.
17139 @smallexample
17140 # see "Automatically creating a list of directories" to create
17141 # these variables
17142 SOURCE_DIRS=
17143 OBJECT_DIRS=
17145 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17146 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17148 all:
17149         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17150 @end smallexample
17152 @node Overcoming Command Line Length Limits
17153 @section Overcoming Command Line Length Limits
17155 @noindent
17156 One problem that might be encountered on big projects is that many
17157 operating systems limit the length of the command line. It is thus hard to give
17158 gnatmake the list of source and object directories.
17160 This example shows how you can set up environment variables, which will
17161 make @code{gnatmake} behave exactly as if the directories had been
17162 specified on the command line, but have a much higher length limit (or
17163 even none on most systems).
17165 It assumes that you have created a list of directories in your Makefile,
17166 using one of the methods presented in
17167 @ref{Automatically Creating a List of Directories}.
17168 For the sake of completeness, we assume that the object
17169 path (where the ALI files are found) is different from the sources patch.
17171 Note a small trick in the Makefile below: for efficiency reasons, we
17172 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17173 expanded immediately by @code{make}. This way we overcome the standard
17174 make behavior which is to expand the variables only when they are
17175 actually used.
17177 On Windows, if you are using the standard Windows command shell, you must
17178 replace colons with semicolons in the assignments to these variables.
17180 @smallexample
17181 @iftex
17182 @leftskip=0cm
17183 @font@heightrm=cmr8
17184 @heightrm
17185 @end iftex
17186 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
17187 # This is the same thing as putting the -I arguments on the command line.
17188 # (the equivalent of using -aI on the command line would be to define
17189 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
17190 # You can of course have different values for these variables.
17192 # Note also that we need to keep the previous values of these variables, since
17193 # they might have been set before running 'make' to specify where the GNAT
17194 # library is installed.
17196 # see "Automatically creating a list of directories" to create these
17197 # variables
17198 SOURCE_DIRS=
17199 OBJECT_DIRS=
17201 empty:=
17202 space:=$@{empty@} $@{empty@}
17203 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17204 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17205 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17206 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
17207 export ADA_INCLUDE_PATH
17208 export ADA_OBJECT_PATH
17210 all:
17211         gnatmake main_unit
17212 @end smallexample
17213 @end ifclear
17216 @node Finding Memory Problems
17217 @chapter Finding Memory Problems
17219 @noindent
17220 This chapter describes
17221 @ifclear vms
17222 the @command{gnatmem} tool, which can be used to track down
17223 ``memory leaks'', and
17224 @end ifclear
17225 the GNAT Debug Pool facility, which can be used to detect incorrect uses of
17226 access values (including ``dangling references'').
17228 @menu
17229 @ifclear vms
17230 * The gnatmem Tool::
17231 @end ifclear
17232 * The GNAT Debug Pool Facility::
17233 @end menu
17236 @ifclear vms
17237 @node The gnatmem Tool
17238 @section The @command{gnatmem} Tool
17239 @findex gnatmem
17241 @noindent
17242 The @code{gnatmem} utility monitors dynamic allocation and
17243 deallocation activity in a program, and displays information about
17244 incorrect deallocations and possible sources of memory leaks.
17245 It provides three type of information:
17246 @itemize @bullet
17247 @item
17248 General information concerning memory management, such as the total
17249 number of allocations and deallocations, the amount of allocated
17250 memory and the high water mark, i.e. the largest amount of allocated
17251 memory in the course of program execution.
17253 @item
17254 Backtraces for all incorrect deallocations, that is to say deallocations
17255 which do not correspond to a valid allocation.
17257 @item
17258 Information on each allocation that is potentially the origin of a memory
17259 leak.
17260 @end itemize
17262 @menu
17263 * Running gnatmem::
17264 * Switches for gnatmem::
17265 * Example of gnatmem Usage::
17266 @end menu
17268 @node Running gnatmem
17269 @subsection Running @code{gnatmem}
17271 @noindent
17272 @code{gnatmem} makes use of the output created by the special version of
17273 allocation and deallocation routines that record call information. This
17274 allows to obtain accurate dynamic memory usage history at a minimal cost to
17275 the execution speed. Note however, that @code{gnatmem} is not supported on
17276 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
17277 Solaris (sparc and x86) and Windows NT/2000/XP (x86).
17279 @noindent
17280 The @code{gnatmem} command has the form
17282 @smallexample
17283    $ gnatmem [switches] user_program
17284 @end smallexample
17286 @noindent
17287 The program must have been linked with the instrumented version of the
17288 allocation and deallocation routines. This is done by linking with the
17289 @file{libgmem.a} library. For correct symbolic backtrace information,
17290 the user program should be compiled with debugging options
17291 @ref{Switches for gcc}. For example to build @file{my_program}:
17293 @smallexample
17294 $ gnatmake -g my_program -largs -lgmem
17295 @end smallexample
17297 @noindent
17298 When running @file{my_program} the file @file{gmem.out} is produced. This file
17299 contains information about all allocations and deallocations done by the
17300 program. It is produced by the instrumented allocations and
17301 deallocations routines and will be used by @code{gnatmem}.
17303 @noindent
17304 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17305 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17306 @code{-i} switch, gnatmem will assume that this file can be found in the
17307 current directory. For example, after you have executed @file{my_program},
17308 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17310 @smallexample
17311 $ gnatmem my_program
17312 @end smallexample
17314 @noindent
17315 This will produce the output with the following format:
17317 *************** debut cc
17318 @smallexample
17319 $ gnatmem my_program
17321 Global information
17322 ------------------
17323    Total number of allocations        :  45
17324    Total number of deallocations      :   6
17325    Final Water Mark (non freed mem)   :  11.29 Kilobytes
17326    High Water Mark                    :  11.40 Kilobytes
17331 Allocation Root # 2
17332 -------------------
17333  Number of non freed allocations    :  11
17334  Final Water Mark (non freed mem)   :   1.16 Kilobytes
17335  High Water Mark                    :   1.27 Kilobytes
17336  Backtrace                          :
17337    my_program.adb:23 my_program.alloc
17341 @end smallexample
17343 The first block of output gives general information. In this case, the
17344 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17345 Unchecked_Deallocation routine occurred.
17347 @noindent
17348 Subsequent paragraphs display  information on all allocation roots.
17349 An allocation root is a specific point in the execution of the program
17350 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17351 construct. This root is represented by an execution backtrace (or subprogram
17352 call stack). By default the backtrace depth for allocations roots is 1, so
17353 that a root corresponds exactly to a source location. The backtrace can
17354 be made deeper, to make the root more specific.
17356 @node Switches for gnatmem
17357 @subsection Switches for @code{gnatmem}
17359 @noindent
17360 @code{gnatmem} recognizes the following switches:
17362 @table @option
17364 @item -q
17365 @cindex @option{-q} (@code{gnatmem})
17366 Quiet. Gives the minimum output needed to identify the origin of the
17367 memory leaks. Omits statistical information.
17369 @item @var{N}
17370 @cindex @var{N} (@code{gnatmem})
17371 N is an integer literal (usually between 1 and 10) which controls the
17372 depth of the backtraces defining allocation root. The default value for
17373 N is 1. The deeper the backtrace, the more precise the localization of
17374 the root. Note that the total number of roots can depend on this
17375 parameter. This parameter must be specified @emph{before} the name of the
17376 executable to be analyzed, to avoid ambiguity.
17378 @item -b n
17379 @cindex @option{-b} (@code{gnatmem})
17380 This switch has the same effect as just depth parameter.
17382 @item -i @var{file}
17383 @cindex @option{-i} (@code{gnatmem})
17384 Do the @code{gnatmem} processing starting from @file{file}, rather than
17385 @file{gmem.out} in the current directory.
17387 @item -m n
17388 @cindex @option{-m} (@code{gnatmem})
17389 This switch causes @code{gnatmem} to mask the allocation roots that have less
17390 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17391 examine even the roots that didn't result in leaks.
17393 @item -s order
17394 @cindex @option{-s} (@code{gnatmem})
17395 This switch causes @code{gnatmem} to sort the allocation roots according to the
17396 specified order of sort criteria, each identified by a single letter. The
17397 currently supported criteria are @code{n, h, w} standing respectively for
17398 number of unfreed allocations, high watermark, and final watermark
17399 corresponding to a specific root. The default order is @code{nwh}.
17401 @end table
17403 @node Example of gnatmem Usage
17404 @subsection Example of @code{gnatmem} Usage
17406 @noindent
17407 The following example shows the use of @code{gnatmem}
17408 on a simple memory-leaking program.
17409 Suppose that we have the following Ada program:
17411 @smallexample @c ada
17412 @group
17413 @cartouche
17414 with Unchecked_Deallocation;
17415 procedure Test_Gm is
17417    type T is array (1..1000) of Integer;
17418    type Ptr is access T;
17419    procedure Free is new Unchecked_Deallocation (T, Ptr);
17420    A : Ptr;
17422    procedure My_Alloc is
17423    begin
17424       A := new T;
17425    end My_Alloc;
17427    procedure My_DeAlloc is
17428       B : Ptr := A;
17429    begin
17430       Free (B);
17431    end My_DeAlloc;
17433 begin
17434    My_Alloc;
17435    for I in 1 .. 5 loop
17436       for J in I .. 5 loop
17437          My_Alloc;
17438       end loop;
17439       My_Dealloc;
17440    end loop;
17441 end;
17442 @end cartouche
17443 @end group
17444 @end smallexample
17446 @noindent
17447 The program needs to be compiled with debugging option and linked with
17448 @code{gmem} library:
17450 @smallexample
17451 $ gnatmake -g test_gm -largs -lgmem
17452 @end smallexample
17454 @noindent
17455 Then we execute the program as usual:
17457 @smallexample
17458 $ test_gm
17459 @end smallexample
17461 @noindent
17462 Then @code{gnatmem} is invoked simply with
17463 @smallexample
17464 $ gnatmem test_gm
17465 @end smallexample
17467 @noindent
17468 which produces the following output (result may vary on different platforms):
17470 @smallexample
17471 Global information
17472 ------------------
17473    Total number of allocations        :  18
17474    Total number of deallocations      :   5
17475    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17476    High Water Mark                    :  56.90 Kilobytes
17478 Allocation Root # 1
17479 -------------------
17480  Number of non freed allocations    :  11
17481  Final Water Mark (non freed mem)   :  42.97 Kilobytes
17482  High Water Mark                    :  46.88 Kilobytes
17483  Backtrace                          :
17484    test_gm.adb:11 test_gm.my_alloc
17486 Allocation Root # 2
17487 -------------------
17488  Number of non freed allocations    :   1
17489  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17490  High Water Mark                    :  10.02 Kilobytes
17491  Backtrace                          :
17492    s-secsta.adb:81 system.secondary_stack.ss_init
17494 Allocation Root # 3
17495 -------------------
17496  Number of non freed allocations    :   1
17497  Final Water Mark (non freed mem)   :  12 Bytes
17498  High Water Mark                    :  12 Bytes
17499  Backtrace                          :
17500    s-secsta.adb:181 system.secondary_stack.ss_init
17501 @end smallexample
17503 @noindent
17504 Note that the GNAT run time contains itself a certain number of
17505 allocations that have no  corresponding deallocation,
17506 as shown here for root #2 and root
17507 #3. This is a normal behavior when the number of non freed allocations
17508 is one, it allocates dynamic data structures that the run time needs for
17509 the complete lifetime of the program. Note also that there is only one
17510 allocation root in the user program with a single line back trace:
17511 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17512 program shows that 'My_Alloc' is called at 2 different points in the
17513 source (line 21 and line 24). If those two allocation roots need to be
17514 distinguished, the backtrace depth parameter can be used:
17516 @smallexample
17517 $ gnatmem 3 test_gm
17518 @end smallexample
17520 @noindent
17521 which will give the following output:
17523 @smallexample
17524 Global information
17525 ------------------
17526    Total number of allocations        :  18
17527    Total number of deallocations      :   5
17528    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17529    High Water Mark                    :  56.90 Kilobytes
17531 Allocation Root # 1
17532 -------------------
17533  Number of non freed allocations    :  10
17534  Final Water Mark (non freed mem)   :  39.06 Kilobytes
17535  High Water Mark                    :  42.97 Kilobytes
17536  Backtrace                          :
17537    test_gm.adb:11 test_gm.my_alloc
17538    test_gm.adb:24 test_gm
17539    b_test_gm.c:52 main
17541 Allocation Root # 2
17542 -------------------
17543  Number of non freed allocations    :   1
17544  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17545  High Water Mark                    :  10.02 Kilobytes
17546  Backtrace                          :
17547    s-secsta.adb:81  system.secondary_stack.ss_init
17548    s-secsta.adb:283 <system__secondary_stack___elabb>
17549    b_test_gm.c:33   adainit
17551 Allocation Root # 3
17552 -------------------
17553  Number of non freed allocations    :   1
17554  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17555  High Water Mark                    :   3.91 Kilobytes
17556  Backtrace                          :
17557    test_gm.adb:11 test_gm.my_alloc
17558    test_gm.adb:21 test_gm
17559    b_test_gm.c:52 main
17561 Allocation Root # 4
17562 -------------------
17563  Number of non freed allocations    :   1
17564  Final Water Mark (non freed mem)   :  12 Bytes
17565  High Water Mark                    :  12 Bytes
17566  Backtrace                          :
17567    s-secsta.adb:181 system.secondary_stack.ss_init
17568    s-secsta.adb:283 <system__secondary_stack___elabb>
17569    b_test_gm.c:33   adainit
17570 @end smallexample
17572 @noindent
17573 The allocation root #1 of the first example has been split in 2 roots #1
17574 and #3 thanks to the more precise associated backtrace.
17576 @end ifclear
17579 @node The GNAT Debug Pool Facility
17580 @section The GNAT Debug Pool Facility
17581 @findex Debug Pool
17582 @cindex storage, pool, memory corruption
17584 @noindent
17585 The use of unchecked deallocation and unchecked conversion can easily
17586 lead to incorrect memory references. The problems generated by such
17587 references are usually difficult to tackle because the symptoms can be
17588 very remote from the origin of the problem. In such cases, it is
17589 very helpful to detect the problem as early as possible. This is the
17590 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17592 In order to use the GNAT specific debugging pool, the user must
17593 associate a debug pool object with each of the access types that may be
17594 related to suspected memory problems. See Ada Reference Manual 13.11.
17595 @smallexample @c ada
17596 type Ptr is access Some_Type;
17597 Pool : GNAT.Debug_Pools.Debug_Pool;
17598 for Ptr'Storage_Pool use Pool;
17599 @end smallexample
17601 @noindent
17602 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17603 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17604 allow the user to redefine allocation and deallocation strategies. They
17605 also provide a checkpoint for each dereference, through the use of
17606 the primitive operation @code{Dereference} which is implicitly called at
17607 each dereference of an access value.
17609 Once an access type has been associated with a debug pool, operations on
17610 values of the type may raise four distinct exceptions,
17611 which correspond to four potential kinds of memory corruption:
17612 @itemize @bullet
17613 @item
17614 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17615 @item
17616 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17617 @item
17618 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17619 @item
17620 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17621 @end itemize
17623 @noindent
17624 For types associated with a Debug_Pool, dynamic allocation is performed using
17625 the standard
17626 GNAT allocation routine. References to all allocated chunks of memory
17627 are kept in an internal dictionary.
17628 Several deallocation strategies are provided, whereupon the user can choose
17629 to release the memory to the system, keep it allocated for further invalid
17630 access checks, or fill it with an easily recognizable pattern for debug
17631 sessions.
17632 The memory pattern is the old IBM hexadecimal convention: @code{16#DEADBEEF#}.
17634 See the documentation in the file g-debpoo.ads for more information on the
17635 various strategies.
17637 Upon each dereference, a check is made that the access value denotes a
17638 properly allocated memory location. Here is a complete example of use of
17639 @code{Debug_Pools}, that includes typical instances of  memory corruption:
17640 @smallexample @c ada
17641 @iftex
17642 @leftskip=0cm
17643 @end iftex
17644 with Gnat.Io; use Gnat.Io;
17645 with Unchecked_Deallocation;
17646 with Unchecked_Conversion;
17647 with GNAT.Debug_Pools;
17648 with System.Storage_Elements;
17649 with Ada.Exceptions; use Ada.Exceptions;
17650 procedure Debug_Pool_Test is
17652    type T is access Integer;
17653    type U is access all T;
17655    P : GNAT.Debug_Pools.Debug_Pool;
17656    for T'Storage_Pool use P;
17658    procedure Free is new Unchecked_Deallocation (Integer, T);
17659    function UC is new Unchecked_Conversion (U, T);
17660    A, B : aliased T;
17662    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17664 begin
17665    Info (P);
17666    A := new Integer;
17667    B := new Integer;
17668    B := A;
17669    Info (P);
17670    Free (A);
17671    begin
17672       Put_Line (Integer'Image(B.all));
17673    exception
17674       when E : others => Put_Line ("raised: " & Exception_Name (E));
17675    end;
17676    begin
17677       Free (B);
17678    exception
17679       when E : others => Put_Line ("raised: " & Exception_Name (E));
17680    end;
17681    B := UC(A'Access);
17682    begin
17683       Put_Line (Integer'Image(B.all));
17684    exception
17685       when E : others => Put_Line ("raised: " & Exception_Name (E));
17686    end;
17687    begin
17688       Free (B);
17689    exception
17690       when E : others => Put_Line ("raised: " & Exception_Name (E));
17691    end;
17692    Info (P);
17693 end Debug_Pool_Test;
17694 @end smallexample
17696 @noindent
17697 The debug pool mechanism provides the following precise diagnostics on the
17698 execution of this erroneous program:
17699 @smallexample
17700 Debug Pool info:
17701   Total allocated bytes :  0
17702   Total deallocated bytes :  0
17703   Current Water Mark:  0
17704   High Water Mark:  0
17706 Debug Pool info:
17707   Total allocated bytes :  8
17708   Total deallocated bytes :  0
17709   Current Water Mark:  8
17710   High Water Mark:  8
17712 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17713 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17714 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17715 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17716 Debug Pool info:
17717   Total allocated bytes :  8
17718   Total deallocated bytes :  4
17719   Current Water Mark:  4
17720   High Water Mark:  8
17721 @end smallexample
17724 @node Creating Sample Bodies Using gnatstub
17725 @chapter Creating Sample Bodies Using @command{gnatstub}
17726 @findex gnatstub
17728 @noindent
17729 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17730 for library unit declarations.
17732 To create a body stub, @command{gnatstub} has to compile the library
17733 unit declaration. Therefore, bodies can be created only for legal
17734 library units. Moreover, if a library unit depends semantically upon
17735 units located outside the current directory, you have to provide
17736 the source search path when calling @command{gnatstub}, see the description
17737 of @command{gnatstub} switches below.
17739 @menu
17740 * Running gnatstub::
17741 * Switches for gnatstub::
17742 @end menu
17744 @node Running gnatstub
17745 @section Running @command{gnatstub}
17747 @noindent
17748 @command{gnatstub} has the command-line interface of the form
17750 @smallexample
17751 $ gnatstub [switches] filename [directory]
17752 @end smallexample
17754 @noindent
17755 where
17756 @table @emph
17757 @item filename
17758 is the name of the source file that contains a library unit declaration
17759 for which a body must be created. The file name may contain the path
17760 information.
17761 The file name does not have to follow the GNAT file name conventions. If the
17762 name
17763 does not follow GNAT file naming conventions, the name of the body file must
17764 be provided
17765 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17766 If the file name follows the GNAT file naming
17767 conventions and the name of the body file is not provided,
17768 @command{gnatstub}
17769 creates the name
17770 of the body file from the argument file name by replacing the @file{.ads}
17771 suffix
17772 with the @file{.adb} suffix.
17774 @item directory
17775 indicates the directory in which the body stub is to be placed (the default
17776 is the
17777 current directory)
17779 @item switches
17780 is an optional sequence of switches as described in the next section
17781 @end table
17783 @node Switches for gnatstub
17784 @section Switches for @command{gnatstub}
17786 @table @option
17787 @c !sort!
17789 @item ^-f^/FULL^
17790 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17791 If the destination directory already contains a file with the name of the
17792 body file
17793 for the argument spec file, replace it with the generated body stub.
17795 @item ^-hs^/HEADER=SPEC^
17796 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17797 Put the comment header (i.e., all the comments preceding the
17798 compilation unit) from the source of the library unit declaration
17799 into the body stub.
17801 @item ^-hg^/HEADER=GENERAL^
17802 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17803 Put a sample comment header into the body stub.
17805 @ifclear vms
17806 @item -IDIR
17807 @cindex @option{-IDIR} (@command{gnatstub})
17808 @itemx -I-
17809 @cindex @option{-I-} (@command{gnatstub})
17810 @end ifclear
17811 @ifset vms
17812 @item /NOCURRENT_DIRECTORY
17813 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17814 @end ifset
17815 ^These switches have ^This switch has^ the same meaning as in calls to
17816 @command{gcc}.
17817 ^They define ^It defines ^ the source search path in the call to
17818 @command{gcc} issued
17819 by @command{gnatstub} to compile an argument source file.
17821 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17822 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17823 This switch has the same meaning as in calls to @command{gcc}.
17824 It defines the additional configuration file to be passed to the call to
17825 @command{gcc} issued
17826 by @command{gnatstub} to compile an argument source file.
17828 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17829 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17830 (@var{n} is a non-negative integer). Set the maximum line length in the
17831 body stub to @var{n}; the default is 79. The maximum value that can be
17832 specified is 32767. Note that in the special case of configuration
17833 pragma files, the maximum is always 32767 regardless of whether or
17834 not this switch appears.
17836 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17837 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17838 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17839 the generated body sample to @var{n}.
17840 The default indentation is 3.
17842 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17843 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17844 Order local bodies alphabetically. (By default local bodies are ordered
17845 in the same way as the corresponding local specs in the argument spec file.)
17847 @item ^-i^/INDENTATION=^@var{n}
17848 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17849 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17851 @item ^-k^/TREE_FILE=SAVE^
17852 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17853 Do not remove the tree file (i.e., the snapshot of the compiler internal
17854 structures used by @command{gnatstub}) after creating the body stub.
17856 @item ^-l^/LINE_LENGTH=^@var{n}
17857 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17858 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17860 @item ^-o^/BODY=^@var{body-name}
17861 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17862 Body file name.  This should be set if the argument file name does not
17863 follow
17864 the GNAT file naming
17865 conventions. If this switch is omitted the default name for the body will be
17866 obtained
17867 from the argument file name according to the GNAT file naming conventions.
17869 @item ^-q^/QUIET^
17870 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17871 Quiet mode: do not generate a confirmation when a body is
17872 successfully created, and do not generate a message when a body is not
17873 required for an
17874 argument unit.
17876 @item ^-r^/TREE_FILE=REUSE^
17877 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17878 Reuse the tree file (if it exists) instead of creating it.  Instead of
17879 creating the tree file for the library unit declaration, @command{gnatstub}
17880 tries to find it in the current directory and use it for creating
17881 a body. If the tree file is not found, no body is created. This option
17882 also implies @option{^-k^/SAVE^}, whether or not
17883 the latter is set explicitly.
17885 @item ^-t^/TREE_FILE=OVERWRITE^
17886 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17887 Overwrite the existing tree file.  If the current directory already
17888 contains the file which, according to the GNAT file naming rules should
17889 be considered as a tree file for the argument source file,
17890 @command{gnatstub}
17891 will refuse to create the tree file needed to create a sample body
17892 unless this option is set.
17894 @item ^-v^/VERBOSE^
17895 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17896 Verbose mode: generate version information.
17898 @end table
17901 @node Other Utility Programs
17902 @chapter Other Utility Programs
17904 @noindent
17905 This chapter discusses some other utility programs available in the Ada
17906 environment.
17908 @menu
17909 * Using Other Utility Programs with GNAT::
17910 * The External Symbol Naming Scheme of GNAT::
17911 @ifclear vms
17912 * Ada Mode for Glide::
17913 @end ifclear
17914 * Converting Ada Files to html with gnathtml::
17915 * Installing gnathtml::
17916 @ifset vms
17917 * LSE::
17918 * Profiling::
17919 @end ifset
17920 @end menu
17922 @node Using Other Utility Programs with GNAT
17923 @section Using Other Utility Programs with GNAT
17925 @noindent
17926 The object files generated by GNAT are in standard system format and in
17927 particular the debugging information uses this format. This means
17928 programs generated by GNAT can be used with existing utilities that
17929 depend on these formats.
17931 @ifclear vms
17932 In general, any utility program that works with C will also often work with
17933 Ada programs generated by GNAT. This includes software utilities such as
17934 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
17935 as Purify.
17936 @end ifclear
17938 @node The External Symbol Naming Scheme of GNAT
17939 @section The External Symbol Naming Scheme of GNAT
17941 @noindent
17942 In order to interpret the output from GNAT, when using tools that are
17943 originally intended for use with other languages, it is useful to
17944 understand the conventions used to generate link names from the Ada
17945 entity names.
17947 All link names are in all lowercase letters. With the exception of library
17948 procedure names, the mechanism used is simply to use the full expanded
17949 Ada name with dots replaced by double underscores. For example, suppose
17950 we have the following package spec:
17952 @smallexample @c ada
17953 @group
17954 @cartouche
17955 package QRS is
17956    MN : Integer;
17957 end QRS;
17958 @end cartouche
17959 @end group
17960 @end smallexample
17962 @noindent
17963 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
17964 the corresponding link name is @code{qrs__mn}.
17965 @findex Export
17966 Of course if a @code{pragma Export} is used this may be overridden:
17968 @smallexample @c ada
17969 @group
17970 @cartouche
17971 package Exports is
17972    Var1 : Integer;
17973    pragma Export (Var1, C, External_Name => "var1_name");
17974    Var2 : Integer;
17975    pragma Export (Var2, C, Link_Name => "var2_link_name");
17976 end Exports;
17977 @end cartouche
17978 @end group
17979 @end smallexample
17981 @noindent
17982 In this case, the link name for @var{Var1} is whatever link name the
17983 C compiler would assign for the C function @var{var1_name}. This typically
17984 would be either @var{var1_name} or @var{_var1_name}, depending on operating
17985 system conventions, but other possibilities exist. The link name for
17986 @var{Var2} is @var{var2_link_name}, and this is not operating system
17987 dependent.
17989 @findex _main
17990 One exception occurs for library level procedures. A potential ambiguity
17991 arises between the required name @code{_main} for the C main program,
17992 and the name we would otherwise assign to an Ada library level procedure
17993 called @code{Main} (which might well not be the main program).
17995 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
17996 names. So if we have a library level procedure such as
17998 @smallexample @c ada
17999 @group
18000 @cartouche
18001 procedure Hello (S : String);
18002 @end cartouche
18003 @end group
18004 @end smallexample
18006 @noindent
18007 the external name of this procedure will be @var{_ada_hello}.
18009 @ifclear vms
18010 @node Ada Mode for Glide
18011 @section Ada Mode for @code{Glide}
18012 @cindex Ada mode (for Glide)
18014 @noindent
18015 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
18016 user to understand and navigate existing code, and facilitates writing
18017 new code. It furthermore provides some utility functions for easier
18018 integration of standard Emacs features when programming in Ada.
18020 Its general features include:
18022 @itemize @bullet
18023 @item
18024 An Integrated Development Environment with functionality such as the
18025 following
18027 @itemize @bullet
18028 @item
18029 ``Project files'' for configuration-specific aspects
18030 (e.g. directories and compilation options)
18032 @item
18033 Compiling and stepping through error messages.
18035 @item
18036 Running and debugging an applications within Glide.
18037 @end itemize
18039 @item
18040 Pull-down menus
18042 @item
18043 User configurability
18044 @end itemize
18046 Some of the specific Ada mode features are:
18048 @itemize @bullet
18049 @item
18050 Functions for easy and quick stepping through Ada code
18052 @item
18053 Getting cross reference information for identifiers (e.g., finding a
18054 defining occurrence)
18056 @item
18057 Displaying an index menu of types and subprograms, allowing
18058 direct selection for browsing
18060 @item
18061 Automatic color highlighting of the various Ada entities
18062 @end itemize
18064 Glide directly supports writing Ada code, via several facilities:
18066 @itemize @bullet
18067 @item
18068 Switching between spec and body files with possible
18069 autogeneration of body files
18071 @item
18072 Automatic formating of subprogram parameter lists
18074 @item
18075 Automatic indentation according to Ada syntax
18077 @item
18078 Automatic completion of identifiers
18080 @item
18081 Automatic (and configurable) casing of identifiers, keywords, and attributes
18083 @item
18084 Insertion of syntactic templates
18086 @item
18087 Block commenting / uncommenting
18088 @end itemize
18090 @noindent
18091 For more information, please refer to the online documentation
18092 available in the @code{Glide} @result{} @code{Help} menu.
18093 @end ifclear
18096 @node Converting Ada Files to html with gnathtml
18097 @section Converting Ada Files to HTML with @code{gnathtml}
18099 @noindent
18100 This @code{Perl} script allows Ada source files to be browsed using
18101 standard Web browsers. For installation procedure, see the section
18102 @xref{Installing gnathtml}.
18104 Ada reserved keywords are highlighted in a bold font and Ada comments in
18105 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18106 switch to suppress the generation of cross-referencing information, user
18107 defined variables and types will appear in a different color; you will
18108 be able to click on any identifier and go to its declaration.
18110 The command line is as follow:
18111 @smallexample
18112 $ perl gnathtml.pl [switches] ada-files
18113 @end smallexample
18115 @noindent
18116 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18117 an html file for every ada file, and a global file called @file{index.htm}.
18118 This file is an index of every identifier defined in the files.
18120 The available switches are the following ones :
18122 @table @option
18123 @item -83
18124 @cindex @option{-83} (@code{gnathtml})
18125 Only the subset on the Ada 83 keywords will be highlighted, not the full
18126 Ada 95 keywords set.
18128 @item -cc @var{color}
18129 @cindex @option{-cc} (@code{gnathtml})
18130 This option allows you to change the color used for comments. The default
18131 value is green. The color argument can be any name accepted by html.
18133 @item -d
18134 @cindex @option{-d} (@code{gnathtml})
18135 If the ada files depend on some other files (using for instance the
18136 @code{with} command, the latter will also be converted to html.
18137 Only the files in the user project will be converted to html, not the files
18138 in the run-time library itself.
18140 @item -D
18141 @cindex @option{-D} (@code{gnathtml})
18142 This command is the same as @option{-d} above, but @command{gnathtml} will
18143 also look for files in the run-time library, and generate html files for them.
18145 @item -ext @var{extension}
18146 @cindex @option{-ext} (@code{gnathtml})
18147 This option allows you to change the extension of the generated HTML files.
18148 If you do not specify an extension, it will default to @file{htm}.
18150 @item -f
18151 @cindex @option{-f} (@code{gnathtml})
18152 By default, gnathtml will generate html links only for global entities
18153 ('with'ed units, global variables and types,...). If you specify the
18154 @option{-f} on the command line, then links will be generated for local
18155 entities too.
18157 @item -l @var{number}
18158 @cindex @option{-l} (@code{gnathtml})
18159 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
18160 will number the html files every @var{number} line.
18162 @item -I @var{dir}
18163 @cindex @option{-I} (@code{gnathtml})
18164 Specify a directory to search for library files (@file{.ALI} files) and
18165 source files. You can provide several -I switches on the command line,
18166 and the directories will be parsed in the order of the command line.
18168 @item -o @var{dir}
18169 @cindex @option{-o} (@code{gnathtml})
18170 Specify the output directory for html files. By default, gnathtml will
18171 saved the generated html files in a subdirectory named @file{html/}.
18173 @item -p @var{file}
18174 @cindex @option{-p} (@code{gnathtml})
18175 If you are using Emacs and the most recent Emacs Ada mode, which provides
18176 a full Integrated Development Environment for compiling, checking,
18177 running and debugging applications, you may use @file{.gpr} files
18178 to give the directories where Emacs can find sources and object files.
18180 Using this switch, you can tell gnathtml to use these files. This allows
18181 you to get an html version of your application, even if it is spread
18182 over multiple directories.
18184 @item -sc @var{color}
18185 @cindex @option{-sc} (@code{gnathtml})
18186 This option allows you to change the color used for symbol definitions.
18187 The default value is red. The color argument can be any name accepted by html.
18189 @item -t @var{file}
18190 @cindex @option{-t} (@code{gnathtml})
18191 This switch provides the name of a file. This file contains a list of
18192 file names to be converted, and the effect is exactly as though they had
18193 appeared explicitly on the command line. This
18194 is the recommended way to work around the command line length limit on some
18195 systems.
18197 @end table
18199 @node Installing gnathtml
18200 @section Installing @code{gnathtml}
18202 @noindent
18203 @code{Perl} needs to be installed on your machine to run this script.
18204 @code{Perl} is freely available for almost every architecture and
18205 Operating System via the Internet.
18207 On Unix systems, you  may want to modify  the  first line of  the script
18208 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18209 is. The syntax of this line is :
18210 @smallexample
18211 #!full_path_name_to_perl
18212 @end smallexample
18214 @noindent
18215 Alternatively, you may run the script using the following command line:
18217 @smallexample
18218 $ perl gnathtml.pl [switches] files
18219 @end smallexample
18221 @ifset vms
18222 @node LSE
18223 @section LSE
18224 @findex LSE
18226 @noindent
18227 The GNAT distribution provides an Ada 95 template for the Digital Language
18228 Sensitive Editor (LSE), a component of DECset. In order to
18229 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18231 @node Profiling
18232 @section Profiling
18233 @findex PCA
18235 @noindent
18236 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
18237 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18238 the collection phase with the /DEBUG qualifier.
18240 @smallexample
18241 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18242 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18243 $ RUN/DEBUG <PROGRAM_NAME>
18244 @end smallexample
18245 @noindent
18246 @end ifset
18248 @node Running and Debugging Ada Programs
18249 @chapter Running and Debugging Ada Programs
18250 @cindex Debugging
18252 @noindent
18253 This chapter discusses how to debug Ada programs. An incorrect Ada program
18254 may be handled in three ways by the GNAT compiler:
18256 @enumerate
18257 @item
18258 The illegality may be a violation of the static semantics of Ada. In
18259 that case GNAT diagnoses the constructs in the program that are illegal.
18260 It is then a straightforward matter for the user to modify those parts of
18261 the program.
18263 @item
18264 The illegality may be a violation of the dynamic semantics of Ada. In
18265 that case the program compiles and executes, but may generate incorrect
18266 results, or may terminate abnormally with some exception.
18268 @item
18269 When presented with a program that contains convoluted errors, GNAT
18270 itself may terminate abnormally without providing full diagnostics on
18271 the incorrect user program.
18272 @end enumerate
18274 @menu
18275 * The GNAT Debugger GDB::
18276 * Running GDB::
18277 * Introduction to GDB Commands::
18278 * Using Ada Expressions::
18279 * Calling User-Defined Subprograms::
18280 * Using the Next Command in a Function::
18281 * Ada Exceptions::
18282 * Ada Tasks::
18283 * Debugging Generic Units::
18284 * GNAT Abnormal Termination or Failure to Terminate::
18285 * Naming Conventions for GNAT Source Files::
18286 * Getting Internal Debugging Information::
18287 * Stack Traceback::
18288 @end menu
18290 @cindex Debugger
18291 @findex gdb
18293 @node The GNAT Debugger GDB
18294 @section The GNAT Debugger GDB
18296 @noindent
18297 @code{GDB} is a general purpose, platform-independent debugger that
18298 can be used to debug mixed-language programs compiled with @code{GCC},
18299 and in particular is capable of debugging Ada programs compiled with
18300 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18301 complex Ada data structures.
18303 The manual @cite{Debugging with GDB}
18304 @ifset vms
18305 , located in the GNU:[DOCS] directory,
18306 @end ifset
18307 contains full details on the usage of @code{GDB}, including a section on
18308 its usage on programs. This manual should be consulted for full
18309 details. The section that follows is a brief introduction to the
18310 philosophy and use of @code{GDB}.
18312 When GNAT programs are compiled, the compiler optionally writes debugging
18313 information into the generated object file, including information on
18314 line numbers, and on declared types and variables. This information is
18315 separate from the generated code. It makes the object files considerably
18316 larger, but it does not add to the size of the actual executable that
18317 will be loaded into memory, and has no impact on run-time performance. The
18318 generation of debug information is triggered by the use of the
18319 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
18320 the compilations. It is important to emphasize that the use of these
18321 options does not change the generated code.
18323 The debugging information is written in standard system formats that
18324 are used by many tools, including debuggers and profilers. The format
18325 of the information is typically designed to describe C types and
18326 semantics, but GNAT implements a translation scheme which allows full
18327 details about Ada types and variables to be encoded into these
18328 standard C formats. Details of this encoding scheme may be found in
18329 the file exp_dbug.ads in the GNAT source distribution. However, the
18330 details of this encoding are, in general, of no interest to a user,
18331 since @code{GDB} automatically performs the necessary decoding.
18333 When a program is bound and linked, the debugging information is
18334 collected from the object files, and stored in the executable image of
18335 the program. Again, this process significantly increases the size of
18336 the generated executable file, but it does not increase the size of
18337 the executable program itself. Furthermore, if this program is run in
18338 the normal manner, it runs exactly as if the debug information were
18339 not present, and takes no more actual memory.
18341 However, if the program is run under control of @code{GDB}, the
18342 debugger is activated.  The image of the program is loaded, at which
18343 point it is ready to run.  If a run command is given, then the program
18344 will run exactly as it would have if @code{GDB} were not present. This
18345 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18346 entirely non-intrusive until a breakpoint is encountered.  If no
18347 breakpoint is ever hit, the program will run exactly as it would if no
18348 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18349 the debugging information and can respond to user commands to inspect
18350 variables, and more generally to report on the state of execution.
18352 @c **************
18353 @node Running GDB
18354 @section Running GDB
18356 @noindent
18357 The debugger can be launched directly and simply from @code{glide} or
18358 through its graphical interface: @code{gvd}. It can also be used
18359 directly in text mode. Here is described the basic use of @code{GDB}
18360 in text mode. All the commands described below can be used in the
18361 @code{gvd} console window even though there is usually other more
18362 graphical ways to achieve the same goals.
18364 @ifclear vms
18365 @noindent
18366 The command to run the graphical interface of the debugger is
18367 @smallexample
18368 $ gvd program
18369 @end smallexample
18370 @end ifclear
18372 @noindent
18373 The command to run @code{GDB} in text mode is
18375 @smallexample
18376 $ ^gdb program^$ GDB PROGRAM^
18377 @end smallexample
18379 @noindent
18380 where @code{^program^PROGRAM^} is the name of the executable file. This
18381 activates the debugger and results in a prompt for debugger commands.
18382 The simplest command is simply @code{run}, which causes the program to run
18383 exactly as if the debugger were not present. The following section
18384 describes some of the additional commands that can be given to @code{GDB}.
18387 @c *******************************
18388 @node Introduction to GDB Commands
18389 @section Introduction to GDB Commands
18391 @noindent
18392 @code{GDB} contains a large repertoire of commands. The manual
18393 @cite{Debugging with GDB}
18394 @ifset vms
18395 , located in the GNU:[DOCS] directory,
18396 @end ifset
18397 includes extensive documentation on the use
18398 of these commands, together with examples of their use. Furthermore,
18399 the command @var{help} invoked from within @code{GDB} activates a simple help
18400 facility which summarizes the available commands and their options.
18401 In this section we summarize a few of the most commonly
18402 used commands to give an idea of what @code{GDB} is about. You should create
18403 a simple program with debugging information and experiment with the use of
18404 these @code{GDB} commands on the program as you read through the
18405 following section.
18407 @table @code
18408 @item set args @var{arguments}
18409 The @var{arguments} list above is a list of arguments to be passed to
18410 the program on a subsequent run command, just as though the arguments
18411 had been entered on a normal invocation of the program. The @code{set args}
18412 command is not needed if the program does not require arguments.
18414 @item run
18415 The @code{run} command causes execution of the program to start from
18416 the beginning. If the program is already running, that is to say if
18417 you are currently positioned at a breakpoint, then a prompt will ask
18418 for confirmation that you want to abandon the current execution and
18419 restart.
18421 @item breakpoint @var{location}
18422 The breakpoint command sets a breakpoint, that is to say a point at which
18423 execution will halt and @code{GDB} will await further
18424 commands. @var{location} is
18425 either a line number within a file, given in the format @code{file:linenumber},
18426 or it is the name of a subprogram. If you request that a breakpoint be set on
18427 a subprogram that is overloaded, a prompt will ask you to specify on which of
18428 those subprograms you want to breakpoint. You can also
18429 specify that all of them should be breakpointed. If the program is run
18430 and execution encounters the breakpoint, then the program
18431 stops and @code{GDB} signals that the breakpoint was encountered by
18432 printing the line of code before which the program is halted.
18434 @item breakpoint exception @var{name}
18435 A special form of the breakpoint command which breakpoints whenever
18436 exception @var{name} is raised.
18437 If @var{name} is omitted,
18438 then a breakpoint will occur when any exception is raised.
18440 @item print @var{expression}
18441 This will print the value of the given expression. Most simple
18442 Ada expression formats are properly handled by @code{GDB}, so the expression
18443 can contain function calls, variables, operators, and attribute references.
18445 @item continue
18446 Continues execution following a breakpoint, until the next breakpoint or the
18447 termination of the program.
18449 @item step
18450 Executes a single line after a breakpoint. If the next statement
18451 is a subprogram call, execution continues into (the first statement of)
18452 the called subprogram.
18454 @item next
18455 Executes a single line. If this line is a subprogram call, executes and
18456 returns from the call.
18458 @item list
18459 Lists a few lines around the current source location. In practice, it
18460 is usually more convenient to have a separate edit window open with the
18461 relevant source file displayed. Successive applications of this command
18462 print subsequent lines. The command can be given an argument which is a
18463 line number, in which case it displays a few lines around the specified one.
18465 @item backtrace
18466 Displays a backtrace of the call chain. This command is typically
18467 used after a breakpoint has occurred, to examine the sequence of calls that
18468 leads to the current breakpoint. The display includes one line for each
18469 activation record (frame) corresponding to an active subprogram.
18471 @item up
18472 At a breakpoint, @code{GDB} can display the values of variables local
18473 to the current frame. The command @code{up} can be used to
18474 examine the contents of other active frames, by moving the focus up
18475 the stack, that is to say from callee to caller, one frame at a time.
18477 @item down
18478 Moves the focus of @code{GDB} down from the frame currently being
18479 examined to the frame of its callee (the reverse of the previous command),
18481 @item frame @var{n}
18482 Inspect the frame with the given number. The value 0 denotes the frame
18483 of the current breakpoint, that is to say the top of the call stack.
18485 @end table
18487 The above list is a very short introduction to the commands that
18488 @code{GDB} provides. Important additional capabilities, including conditional
18489 breakpoints, the ability to execute command sequences on a breakpoint,
18490 the ability to debug at the machine instruction level and many other
18491 features are described in detail in @cite{Debugging with GDB}.
18492 Note that most commands can be abbreviated
18493 (for example, c for continue, bt for backtrace).
18495 @node Using Ada Expressions
18496 @section Using Ada Expressions
18497 @cindex Ada expressions
18499 @noindent
18500 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18501 extensions. The philosophy behind the design of this subset is
18503 @itemize @bullet
18504 @item
18505 That @code{GDB} should provide basic literals and access to operations for
18506 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18507 leaving more sophisticated computations to subprograms written into the
18508 program (which therefore may be called from @code{GDB}).
18510 @item
18511 That type safety and strict adherence to Ada language restrictions
18512 are not particularly important to the @code{GDB} user.
18514 @item
18515 That brevity is important to the @code{GDB} user.
18516 @end itemize
18518 Thus, for brevity, the debugger acts as if there were
18519 implicit @code{with} and @code{use} clauses in effect for all user-written
18520 packages, thus making it unnecessary to fully qualify most names with
18521 their packages, regardless of context. Where this causes ambiguity,
18522 @code{GDB} asks the user's intent.
18524 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
18526 @node Calling User-Defined Subprograms
18527 @section Calling User-Defined Subprograms
18529 @noindent
18530 An important capability of @code{GDB} is the ability to call user-defined
18531 subprograms while debugging. This is achieved simply by entering
18532 a subprogram call statement in the form:
18534 @smallexample
18535 call subprogram-name (parameters)
18536 @end smallexample
18538 @noindent
18539 The keyword @code{call} can be omitted in the normal case where the
18540 @code{subprogram-name} does not coincide with any of the predefined
18541 @code{GDB} commands.
18543 The effect is to invoke the given subprogram, passing it the
18544 list of parameters that is supplied. The parameters can be expressions and
18545 can include variables from the program being debugged. The
18546 subprogram must be defined
18547 at the library level within your program, and @code{GDB} will call the
18548 subprogram within the environment of your program execution (which
18549 means that the subprogram is free to access or even modify variables
18550 within your program).
18552 The most important use of this facility is in allowing the inclusion of
18553 debugging routines that are tailored to particular data structures
18554 in your program. Such debugging routines can be written to provide a suitably
18555 high-level description of an abstract type, rather than a low-level dump
18556 of its physical layout. After all, the standard
18557 @code{GDB print} command only knows the physical layout of your
18558 types, not their abstract meaning. Debugging routines can provide information
18559 at the desired semantic level and are thus enormously useful.
18561 For example, when debugging GNAT itself, it is crucial to have access to
18562 the contents of the tree nodes used to represent the program internally.
18563 But tree nodes are represented simply by an integer value (which in turn
18564 is an index into a table of nodes).
18565 Using the @code{print} command on a tree node would simply print this integer
18566 value, which is not very useful. But the PN routine (defined in file
18567 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18568 a useful high level representation of the tree node, which includes the
18569 syntactic category of the node, its position in the source, the integers
18570 that denote descendant nodes and parent node, as well as varied
18571 semantic information. To study this example in more detail, you might want to
18572 look at the body of the PN procedure in the stated file.
18574 @node Using the Next Command in a Function
18575 @section Using the Next Command in a Function
18577 @noindent
18578 When you use the @code{next} command in a function, the current source
18579 location will advance to the next statement as usual. A special case
18580 arises in the case of a @code{return} statement.
18582 Part of the code for a return statement is the ``epilog'' of the function.
18583 This is the code that returns to the caller. There is only one copy of
18584 this epilog code, and it is typically associated with the last return
18585 statement in the function if there is more than one return. In some
18586 implementations, this epilog is associated with the first statement
18587 of the function.
18589 The result is that if you use the @code{next} command from a return
18590 statement that is not the last return statement of the function you
18591 may see a strange apparent jump to the last return statement or to
18592 the start of the function. You should simply ignore this odd jump.
18593 The value returned is always that from the first return statement
18594 that was stepped through.
18596 @node Ada Exceptions
18597 @section Breaking on Ada Exceptions
18598 @cindex Exceptions
18600 @noindent
18601 You can set breakpoints that trip when your program raises
18602 selected exceptions.
18604 @table @code
18605 @item break exception
18606 Set a breakpoint that trips whenever (any task in the) program raises
18607 any exception.
18609 @item break exception @var{name}
18610 Set a breakpoint that trips whenever (any task in the) program raises
18611 the exception @var{name}.
18613 @item break exception unhandled
18614 Set a breakpoint that trips whenever (any task in the) program raises an
18615 exception for which there is no handler.
18617 @item info exceptions
18618 @itemx info exceptions @var{regexp}
18619 The @code{info exceptions} command permits the user to examine all defined
18620 exceptions within Ada programs. With a regular expression, @var{regexp}, as
18621 argument, prints out only those exceptions whose name matches @var{regexp}.
18622 @end table
18624 @node Ada Tasks
18625 @section Ada Tasks
18626 @cindex Tasks
18628 @noindent
18629 @code{GDB} allows the following task-related commands:
18631 @table @code
18632 @item info tasks
18633 This command shows a list of current Ada tasks, as in the following example:
18635 @smallexample
18636 @iftex
18637 @leftskip=0cm
18638 @end iftex
18639 (gdb) info tasks
18640   ID       TID P-ID   Thread Pri State                 Name
18641    1   8088000   0   807e000  15 Child Activation Wait main_task
18642    2   80a4000   1   80ae000  15 Accept/Select Wait    b
18643    3   809a800   1   80a4800  15 Child Activation Wait a
18644 *  4   80ae800   3   80b8000  15 Running               c
18645 @end smallexample
18647 @noindent
18648 In this listing, the asterisk before the first task indicates it to be the
18649 currently running task. The first column lists the task ID that is used
18650 to refer to tasks in the following commands.
18652 @item break @var{linespec} task @var{taskid}
18653 @itemx break @var{linespec} task @var{taskid} if @dots{}
18654 @cindex Breakpoints and tasks
18655 These commands are like the @code{break @dots{} thread @dots{}}.
18656 @var{linespec} specifies source lines.
18658 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
18659 to specify that you only want @code{GDB} to stop the program when a
18660 particular Ada task reaches this breakpoint. @var{taskid} is one of the
18661 numeric task identifiers assigned by @code{GDB}, shown in the first
18662 column of the @samp{info tasks} display.
18664 If you do not specify @samp{task @var{taskid}} when you set a
18665 breakpoint, the breakpoint applies to @emph{all} tasks of your
18666 program.
18668 You can use the @code{task} qualifier on conditional breakpoints as
18669 well; in this case, place @samp{task @var{taskid}} before the
18670 breakpoint condition (before the @code{if}).
18672 @item task @var{taskno}
18673 @cindex Task switching
18675 This command allows to switch to the task referred by @var{taskno}. In
18676 particular, This allows to browse the backtrace of the specified
18677 task. It is advised to switch back to the original task before
18678 continuing execution otherwise the scheduling of the program may be
18679 perturbated.
18680 @end table
18682 @noindent
18683 For more detailed information on the tasking support,
18684 see @cite{Debugging with GDB}.
18686 @node Debugging Generic Units
18687 @section Debugging Generic Units
18688 @cindex Debugging Generic Units
18689 @cindex Generics
18691 @noindent
18692 GNAT always uses code expansion for generic instantiation. This means that
18693 each time an instantiation occurs, a complete copy of the original code is
18694 made, with appropriate substitutions of formals by actuals.
18696 It is not possible to refer to the original generic entities in
18697 @code{GDB}, but it is always possible to debug a particular instance of
18698 a generic, by using the appropriate expanded names. For example, if we have
18700 @smallexample @c ada
18701 @group
18702 @cartouche
18703 procedure g is
18705    generic package k is
18706       procedure kp (v1 : in out integer);
18707    end k;
18709    package body k is
18710       procedure kp (v1 : in out integer) is
18711       begin
18712          v1 := v1 + 1;
18713       end kp;
18714    end k;
18716    package k1 is new k;
18717    package k2 is new k;
18719    var : integer := 1;
18721 begin
18722    k1.kp (var);
18723    k2.kp (var);
18724    k1.kp (var);
18725    k2.kp (var);
18726 end;
18727 @end cartouche
18728 @end group
18729 @end smallexample
18731 @noindent
18732 Then to break on a call to procedure kp in the k2 instance, simply
18733 use the command:
18735 @smallexample
18736 (gdb) break g.k2.kp
18737 @end smallexample
18739 @noindent
18740 When the breakpoint occurs, you can step through the code of the
18741 instance in the normal manner and examine the values of local variables, as for
18742 other units.
18744 @node GNAT Abnormal Termination or Failure to Terminate
18745 @section GNAT Abnormal Termination or Failure to Terminate
18746 @cindex GNAT Abnormal Termination or Failure to Terminate
18748 @noindent
18749 When presented with programs that contain serious errors in syntax
18750 or semantics,
18751 GNAT may on rare occasions  experience problems in operation, such
18752 as aborting with a
18753 segmentation fault or illegal memory access, raising an internal
18754 exception, terminating abnormally, or failing to terminate at all.
18755 In such cases, you can activate
18756 various features of GNAT that can help you pinpoint the construct in your
18757 program that is the likely source of the problem.
18759 The following strategies are presented in increasing order of
18760 difficulty, corresponding to your experience in using GNAT and your
18761 familiarity with compiler internals.
18763 @enumerate
18764 @item
18765 Run @code{gcc} with the @option{-gnatf}. This first
18766 switch causes all errors on a given line to be reported. In its absence,
18767 only the first error on a line is displayed.
18769 The @option{-gnatdO} switch causes errors to be displayed as soon as they
18770 are encountered, rather than after compilation is terminated. If GNAT
18771 terminates prematurely or goes into an infinite loop, the last error
18772 message displayed may help to pinpoint the culprit.
18774 @item
18775 Run @code{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this mode,
18776 @code{gcc} produces ongoing information about the progress of the
18777 compilation and provides the name of each procedure as code is
18778 generated. This switch allows you to find which Ada procedure was being
18779 compiled when it encountered a code generation problem.
18781 @item
18782 @cindex @option{-gnatdc} switch
18783 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
18784 switch that does for the front-end what @option{^-v^VERBOSE^} does
18785 for the back end. The system prints the name of each unit,
18786 either a compilation unit or nested unit, as it is being analyzed.
18787 @item
18788 Finally, you can start
18789 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
18790 front-end of GNAT, and can be run independently (normally it is just
18791 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
18792 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
18793 @code{where} command is the first line of attack; the variable
18794 @code{lineno} (seen by @code{print lineno}), used by the second phase of
18795 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
18796 which the execution stopped, and @code{input_file name} indicates the name of
18797 the source file.
18798 @end enumerate
18800 @node Naming Conventions for GNAT Source Files
18801 @section Naming Conventions for GNAT Source Files
18803 @noindent
18804 In order to examine the workings of the GNAT system, the following
18805 brief description of its organization may be helpful:
18807 @itemize @bullet
18808 @item
18809 Files with prefix @file{^sc^SC^} contain the lexical scanner.
18811 @item
18812 All files prefixed with @file{^par^PAR^} are components of the parser. The
18813 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
18814 parsing of select statements can be found in @file{par-ch9.adb}.
18816 @item
18817 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
18818 numbers correspond to chapters of the Ada standard. For example, all
18819 issues involving context clauses can be found in @file{sem_ch10.adb}. In
18820 addition, some features of the language require sufficient special processing
18821 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
18822 dynamic dispatching, etc.
18824 @item
18825 All files prefixed with @file{^exp^EXP^} perform normalization and
18826 expansion of the intermediate representation (abstract syntax tree, or AST).
18827 these files use the same numbering scheme as the parser and semantics files.
18828 For example, the construction of record initialization procedures is done in
18829 @file{exp_ch3.adb}.
18831 @item
18832 The files prefixed with @file{^bind^BIND^} implement the binder, which
18833 verifies the consistency of the compilation, determines an order of
18834 elaboration, and generates the bind file.
18836 @item
18837 The files @file{atree.ads} and @file{atree.adb} detail the low-level
18838 data structures used by the front-end.
18840 @item
18841 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
18842 the abstract syntax tree as produced by the parser.
18844 @item
18845 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
18846 all entities, computed during semantic analysis.
18848 @item
18849 Library management issues are dealt with in files with prefix
18850 @file{^lib^LIB^}.
18852 @item
18853 @findex Ada
18854 @cindex Annex A
18855 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
18856 defined in Annex A.
18858 @item
18859 @findex Interfaces
18860 @cindex Annex B
18861 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
18862 defined in Annex B.
18864 @item
18865 @findex System
18866 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
18867 both language-defined children and GNAT run-time routines.
18869 @item
18870 @findex GNAT
18871 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
18872 general-purpose packages, fully documented in their specifications. All
18873 the other @file{.c} files are modifications of common @code{gcc} files.
18874 @end itemize
18876 @node Getting Internal Debugging Information
18877 @section Getting Internal Debugging Information
18879 @noindent
18880 Most compilers have internal debugging switches and modes. GNAT
18881 does also, except GNAT internal debugging switches and modes are not
18882 secret. A summary and full description of all the compiler and binder
18883 debug flags are in the file @file{debug.adb}. You must obtain the
18884 sources of the compiler to see the full detailed effects of these flags.
18886 The switches that print the source of the program (reconstructed from
18887 the internal tree) are of general interest for user programs, as are the
18888 options to print
18889 the full internal tree, and the entity table (the symbol table
18890 information). The reconstructed source provides a readable version of the
18891 program after the front-end has completed analysis and  expansion,
18892 and is useful when studying the performance of specific constructs.
18893 For example, constraint checks are indicated, complex aggregates
18894 are replaced with loops and assignments, and tasking primitives
18895 are replaced with run-time calls.
18897 @node Stack Traceback
18898 @section Stack Traceback
18899 @cindex traceback
18900 @cindex stack traceback
18901 @cindex stack unwinding
18903 @noindent
18904 Traceback is a mechanism to display the sequence of subprogram calls that
18905 leads to a specified execution point in a program. Often (but not always)
18906 the execution point is an instruction at which an exception has been raised.
18907 This mechanism is also known as @i{stack unwinding} because it obtains
18908 its information by scanning the run-time stack and recovering the activation
18909 records of all active subprograms. Stack unwinding is one of the most
18910 important tools for program debugging.
18912 The first entry stored in traceback corresponds to the deepest calling level,
18913 that is to say the subprogram currently executing the instruction
18914 from which we want to obtain the traceback.
18916 Note that there is no runtime performance penalty when stack traceback
18917 is enabled, and no exception is raised during program execution.
18919 @menu
18920 * Non-Symbolic Traceback::
18921 * Symbolic Traceback::
18922 @end menu
18924 @node Non-Symbolic Traceback
18925 @subsection Non-Symbolic Traceback
18926 @cindex traceback, non-symbolic
18928 @noindent
18929 Note: this feature is not supported on all platforms. See
18930 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
18931 platforms.
18933 @menu
18934 * Tracebacks From an Unhandled Exception::
18935 * Tracebacks From Exception Occurrences (non-symbolic)::
18936 * Tracebacks From Anywhere in a Program (non-symbolic)::
18937 @end menu
18939 @node Tracebacks From an Unhandled Exception
18940 @subsubsection Tracebacks From an Unhandled Exception
18942 @noindent
18943 A runtime non-symbolic traceback is a list of addresses of call instructions.
18944 To enable this feature you must use the @option{-E}
18945 @code{gnatbind}'s option. With this option a stack traceback is stored as part
18946 of exception information. You can retrieve this information using the
18947 @code{addr2line} tool.
18949 Here is a simple example:
18951 @smallexample @c ada
18952 @cartouche
18953 procedure STB is
18955    procedure P1 is
18956    begin
18957       raise Constraint_Error;
18958    end P1;
18960    procedure P2 is
18961    begin
18962       P1;
18963    end P2;
18965 begin
18966    P2;
18967 end STB;
18968 @end cartouche
18969 @end smallexample
18971 @smallexample
18972 $ gnatmake stb -bargs -E
18973 $ stb
18975 Execution terminated by unhandled exception
18976 Exception name: CONSTRAINT_ERROR
18977 Message: stb.adb:5
18978 Call stack traceback locations:
18979 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
18980 @end smallexample
18982 @noindent
18983 As we see the traceback lists a sequence of addresses for the unhandled
18984 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
18985 guess that this exception come from procedure P1. To translate these
18986 addresses into the source lines where the calls appear, the
18987 @code{addr2line} tool, described below, is invaluable. The use of this tool
18988 requires the program to be compiled with debug information.
18990 @smallexample
18991 $ gnatmake -g stb -bargs -E
18992 $ stb
18994 Execution terminated by unhandled exception
18995 Exception name: CONSTRAINT_ERROR
18996 Message: stb.adb:5
18997 Call stack traceback locations:
18998 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19000 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19001    0x4011f1 0x77e892a4
19003 00401373 at d:/stb/stb.adb:5
19004 0040138B at d:/stb/stb.adb:10
19005 0040139C at d:/stb/stb.adb:14
19006 00401335 at d:/stb/b~stb.adb:104
19007 004011C4 at /build/.../crt1.c:200
19008 004011F1 at /build/.../crt1.c:222
19009 77E892A4 in ?? at ??:0
19010 @end smallexample
19012 @noindent
19013 The @code{addr2line} tool has several other useful options:
19015 @table @code
19016 @item --functions
19017 to get the function name corresponding to any location
19019 @item --demangle=gnat
19020 to use the gnat decoding mode for the function names. Note that
19021 for binutils version 2.9.x the option is simply @option{--demangle}.
19022 @end table
19024 @smallexample
19025 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19026    0x40139c 0x401335 0x4011c4 0x4011f1
19028 00401373 in stb.p1 at d:/stb/stb.adb:5
19029 0040138B in stb.p2 at d:/stb/stb.adb:10
19030 0040139C in stb at d:/stb/stb.adb:14
19031 00401335 in main at d:/stb/b~stb.adb:104
19032 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
19033 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
19034 @end smallexample
19036 @noindent
19037 From this traceback we can see that the exception was raised in
19038 @file{stb.adb} at line 5, which was reached from a procedure call in
19039 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19040 which contains the call to the main program.
19041 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
19042 and the output will vary from platform to platform.
19044 It is also possible to use @code{GDB} with these traceback addresses to debug
19045 the program. For example, we can break at a given code location, as reported
19046 in the stack traceback:
19048 @smallexample
19049 $ gdb -nw stb
19050 @ifclear vms
19051 @noindent
19052 Furthermore, this feature is not implemented inside Windows DLL. Only
19053 the non-symbolic traceback is reported in this case.
19054 @end ifclear
19056 (gdb) break *0x401373
19057 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19058 @end smallexample
19060 @noindent
19061 It is important to note that the stack traceback addresses
19062 do not change when debug information is included. This is particularly useful
19063 because it makes it possible to release software without debug information (to
19064 minimize object size), get a field report that includes a stack traceback
19065 whenever an internal bug occurs, and then be able to retrieve the sequence
19066 of calls with the same program compiled with debug information.
19068 @node Tracebacks From Exception Occurrences (non-symbolic)
19069 @subsubsection Tracebacks From Exception Occurrences
19071 @noindent
19072 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19073 The stack traceback is attached to the exception information string, and can
19074 be retrieved in an exception handler within the Ada program, by means of the
19075 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19077 @smallexample @c ada
19078 with Ada.Text_IO;
19079 with Ada.Exceptions;
19081 procedure STB is
19083    use Ada;
19084    use Ada.Exceptions;
19086    procedure P1 is
19087       K : Positive := 1;
19088    begin
19089       K := K - 1;
19090    exception
19091       when E : others =>
19092          Text_IO.Put_Line (Exception_Information (E));
19093    end P1;
19095    procedure P2 is
19096    begin
19097       P1;
19098    end P2;
19100 begin
19101    P2;
19102 end STB;
19103 @end smallexample
19105 @noindent
19106 This program will output:
19108 @smallexample
19109 $ stb
19111 Exception name: CONSTRAINT_ERROR
19112 Message: stb.adb:12
19113 Call stack traceback locations:
19114 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19115 @end smallexample
19117 @node Tracebacks From Anywhere in a Program (non-symbolic)
19118 @subsubsection Tracebacks From Anywhere in a Program
19120 @noindent
19121 It is also possible to retrieve a stack traceback from anywhere in a
19122 program. For this you need to
19123 use the @code{GNAT.Traceback} API. This package includes a procedure called
19124 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19125 display procedures described below. It is not necessary to use the
19126 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19127 is invoked explicitly.
19129 @noindent
19130 In the following example we compute a traceback at a specific location in
19131 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19132 convert addresses to strings:
19134 @smallexample @c ada
19135 with Ada.Text_IO;
19136 with GNAT.Traceback;
19137 with GNAT.Debug_Utilities;
19139 procedure STB is
19141    use Ada;
19142    use GNAT;
19143    use GNAT.Traceback;
19145    procedure P1 is
19146       TB  : Tracebacks_Array (1 .. 10);
19147       --  We are asking for a maximum of 10 stack frames.
19148       Len : Natural;
19149       --  Len will receive the actual number of stack frames returned.
19150    begin
19151       Call_Chain (TB, Len);
19153       Text_IO.Put ("In STB.P1 : ");
19155       for K in 1 .. Len loop
19156          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19157          Text_IO.Put (' ');
19158       end loop;
19160       Text_IO.New_Line;
19161    end P1;
19163    procedure P2 is
19164    begin
19165       P1;
19166    end P2;
19168 begin
19169    P2;
19170 end STB;
19171 @end smallexample
19173 @smallexample
19174 $ gnatmake -g stb
19175 $ stb
19177 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19178 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19179 @end smallexample
19181 @noindent
19182 You can then get further information by invoking the @code{addr2line}
19183 tool as described earlier (note that the hexadecimal addresses
19184 need to be specified in C format, with a leading ``0x'').
19187 @node Symbolic Traceback
19188 @subsection Symbolic Traceback
19189 @cindex traceback, symbolic
19191 @noindent
19192 A symbolic traceback is a stack traceback in which procedure names are
19193 associated with each code location.
19195 @noindent
19196 Note that this feature is not supported on all platforms. See
19197 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19198 list of currently supported platforms.
19200 @noindent
19201 Note that the symbolic traceback requires that the program be compiled
19202 with debug information. If it is not compiled with debug information
19203 only the non-symbolic information will be valid.
19205 @menu
19206 * Tracebacks From Exception Occurrences (symbolic)::
19207 * Tracebacks From Anywhere in a Program (symbolic)::
19208 @end menu
19210 @node Tracebacks From Exception Occurrences (symbolic)
19211 @subsubsection Tracebacks From Exception Occurrences
19213 @smallexample @c ada
19214 with Ada.Text_IO;
19215 with GNAT.Traceback.Symbolic;
19217 procedure STB is
19219    procedure P1 is
19220    begin
19221       raise Constraint_Error;
19222    end P1;
19224    procedure P2 is
19225    begin
19226       P1;
19227    end P2;
19229    procedure P3 is
19230    begin
19231       P2;
19232    end P3;
19234 begin
19235    P3;
19236 exception
19237    when E : others =>
19238       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19239 end STB;
19240 @end smallexample
19242 @smallexample
19243 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19244 $ stb
19246 0040149F in stb.p1 at stb.adb:8
19247 004014B7 in stb.p2 at stb.adb:13
19248 004014CF in stb.p3 at stb.adb:18
19249 004015DD in ada.stb at stb.adb:22
19250 00401461 in main at b~stb.adb:168
19251 004011C4 in __mingw_CRTStartup at crt1.c:200
19252 004011F1 in mainCRTStartup at crt1.c:222
19253 77E892A4 in ?? at ??:0
19254 @end smallexample
19256 @noindent
19257 In the above example the ``.\'' syntax in the @command{gnatmake} command
19258 is currently required by @command{addr2line} for files that are in
19259 the current working directory.
19260 Moreover, the exact sequence of linker options may vary from platform
19261 to platform.
19262 The above @option{-largs} section is for Windows platforms. By contrast,
19263 under Unix there is no need for the @option{-largs} section.
19264 Differences across platforms are due to details of linker implementation.
19266 @node Tracebacks From Anywhere in a Program (symbolic)
19267 @subsubsection Tracebacks From Anywhere in a Program
19269 @noindent
19270 It is possible to get a symbolic stack traceback
19271 from anywhere in a program, just as for non-symbolic tracebacks.
19272 The first step is to obtain a non-symbolic
19273 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19274 information. Here is an example:
19276 @smallexample @c ada
19277 with Ada.Text_IO;
19278 with GNAT.Traceback;
19279 with GNAT.Traceback.Symbolic;
19281 procedure STB is
19283    use Ada;
19284    use GNAT.Traceback;
19285    use GNAT.Traceback.Symbolic;
19287    procedure P1 is
19288       TB  : Tracebacks_Array (1 .. 10);
19289       --  We are asking for a maximum of 10 stack frames.
19290       Len : Natural;
19291       --  Len will receive the actual number of stack frames returned.
19292    begin
19293       Call_Chain (TB, Len);
19294       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19295    end P1;
19297    procedure P2 is
19298    begin
19299       P1;
19300    end P2;
19302 begin
19303    P2;
19304 end STB;
19305 @end smallexample
19307 @ifset vms
19308 @node Compatibility with DEC Ada
19309 @chapter Compatibility with DEC Ada
19310 @cindex Compatibility
19312 @noindent
19313 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
19314 OpenVMS Alpha. GNAT achieves a high level of compatibility
19315 with DEC Ada, and it should generally be straightforward to port code
19316 from the DEC Ada environment to GNAT. However, there are a few language
19317 and implementation differences of which the user must be aware. These
19318 differences are discussed in this section. In
19319 addition, the operating environment and command structure for the
19320 compiler are different, and these differences are also discussed.
19322 Note that this discussion addresses specifically the implementation
19323 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
19324 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19325 GNAT always follows the Alpha implementation.
19327 @menu
19328 * Ada 95 Compatibility::
19329 * Differences in the Definition of Package System::
19330 * Language-Related Features::
19331 * The Package STANDARD::
19332 * The Package SYSTEM::
19333 * Tasking and Task-Related Features::
19334 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
19335 * Pragmas and Pragma-Related Features::
19336 * Library of Predefined Units::
19337 * Bindings::
19338 * Main Program Definition::
19339 * Implementation-Defined Attributes::
19340 * Compiler and Run-Time Interfacing::
19341 * Program Compilation and Library Management::
19342 * Input-Output::
19343 * Implementation Limits::
19344 * Tools::
19345 @end menu
19347 @node Ada 95 Compatibility
19348 @section Ada 95 Compatibility
19350 @noindent
19351 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
19352 compiler. Ada 95 is almost completely upwards compatible
19353 with Ada 83, and therefore Ada 83 programs will compile
19354 and run under GNAT with
19355 no changes or only minor changes. The Ada 95 Reference
19356 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
19357 incompatibilities.
19359 GNAT provides the switch /83 on the GNAT COMPILE command,
19360 as well as the pragma ADA_83, to force the compiler to
19361 operate in Ada 83 mode. This mode does not guarantee complete
19362 conformance to Ada 83, but in practice is sufficient to
19363 eliminate most sources of incompatibilities.
19364 In particular, it eliminates the recognition of the
19365 additional Ada 95 keywords, so that their use as identifiers
19366 in Ada83 program is legal, and handles the cases of packages
19367 with optional bodies, and generics that instantiate unconstrained
19368 types without the use of @code{(<>)}.
19370 @node Differences in the Definition of Package System
19371 @section Differences in the Definition of Package System
19373 @noindent
19374 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
19375 implementation-dependent declarations to package System. In normal mode,
19376 GNAT does not take advantage of this permission, and the version of System
19377 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
19379 However, DEC Ada adds an extensive set of declarations to package System,
19380 as fully documented in the DEC Ada manuals. To minimize changes required
19381 for programs that make use of these extensions, GNAT provides the pragma
19382 Extend_System for extending the definition of package System. By using:
19384 @smallexample @c ada
19385 @group
19386 @cartouche
19387 pragma Extend_System (Aux_DEC);
19388 @end cartouche
19389 @end group
19390 @end smallexample
19392 @noindent
19393 The set of definitions in System is extended to include those in package
19394 @code{System.Aux_DEC}.
19395 These definitions are incorporated directly into package
19396 System, as though they had been declared there in the first place. For a
19397 list of the declarations added, see the specification of this package,
19398 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
19399 The pragma Extend_System is a configuration pragma, which means that
19400 it can be placed in the file @file{gnat.adc}, so that it will automatically
19401 apply to all subsequent compilations. See the section on Configuration
19402 Pragmas for further details.
19404 An alternative approach that avoids the use of the non-standard
19405 Extend_System pragma is to add a context clause to the unit that
19406 references these facilities:
19408 @smallexample @c ada
19409 @group
19410 @cartouche
19411 with System.Aux_DEC;
19412 use  System.Aux_DEC;
19413 @end cartouche
19414 @end group
19415 @end smallexample
19417 @noindent
19418 The effect is not quite semantically identical to incorporating
19419 the declarations directly into package @code{System},
19420 but most programs will not notice a difference
19421 unless they use prefix notation (e.g. @code{System.Integer_8})
19422 to reference the
19423 entities directly in package @code{System}.
19424 For units containing such references,
19425 the prefixes must either be removed, or the pragma @code{Extend_System}
19426 must be used.
19428 @node Language-Related Features
19429 @section Language-Related Features
19431 @noindent
19432 The following sections highlight differences in types,
19433 representations of types, operations, alignment, and
19434 related topics.
19436 @menu
19437 * Integer Types and Representations::
19438 * Floating-Point Types and Representations::
19439 * Pragmas Float_Representation and Long_Float::
19440 * Fixed-Point Types and Representations::
19441 * Record and Array Component Alignment::
19442 * Address Clauses::
19443 * Other Representation Clauses::
19444 @end menu
19446 @node Integer Types and Representations
19447 @subsection Integer Types and Representations
19449 @noindent
19450 The set of predefined integer types is identical in DEC Ada and GNAT.
19451 Furthermore the representation of these integer types is also identical,
19452 including the capability of size clauses forcing biased representation.
19454 In addition,
19455 DEC Ada for OpenVMS Alpha systems has defined the
19456 following additional integer types in package System:
19458 @itemize @bullet
19460 @item
19461 INTEGER_8
19463 @item
19464 INTEGER_16
19466 @item
19467 INTEGER_32
19469 @item
19470 INTEGER_64
19472 @item
19473 LARGEST_INTEGER
19474 @end itemize
19476 @noindent
19477 When using GNAT, the first four of these types may be obtained from the
19478 standard Ada 95 package @code{Interfaces}.
19479 Alternatively, by use of the pragma
19480 @code{Extend_System}, identical
19481 declarations can be referenced directly in package @code{System}.
19482 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
19484 @node Floating-Point Types and Representations
19485 @subsection Floating-Point Types and Representations
19486 @cindex Floating-Point types
19488 @noindent
19489 The set of predefined floating-point types is identical in DEC Ada and GNAT.
19490 Furthermore the representation of these floating-point
19491 types is also identical. One important difference is that the default
19492 representation for DEC Ada is VAX_Float, but the default representation
19493 for GNAT is IEEE.
19495 Specific types may be declared to be VAX_Float or IEEE, using the pragma
19496 @code{Float_Representation} as described in the DEC Ada documentation.
19497 For example, the declarations:
19499 @smallexample @c ada
19500 @group
19501 @cartouche
19502 type F_Float is digits 6;
19503 pragma Float_Representation (VAX_Float, F_Float);
19504 @end cartouche
19505 @end group
19506 @end smallexample
19508 @noindent
19509 declare a type F_Float that will be represented in VAX_Float format.
19510 This set of declarations actually appears in System.Aux_DEC, which provides
19511 the full set of additional floating-point declarations provided in
19512 the DEC Ada version of package
19513 System. This and similar declarations may be accessed in a user program
19514 by using pragma @code{Extend_System}. The use of this
19515 pragma, and the related pragma @code{Long_Float} is described in further
19516 detail in the following section.
19518 @node Pragmas Float_Representation and Long_Float
19519 @subsection Pragmas Float_Representation and Long_Float
19521 @noindent
19522 DEC Ada provides the pragma @code{Float_Representation}, which
19523 acts as a program library switch to allow control over
19524 the internal representation chosen for the predefined
19525 floating-point types declared in the package @code{Standard}.
19526 The format of this pragma is as follows:
19528 @smallexample
19529 @group
19530 @cartouche
19531 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
19532 @end cartouche
19533 @end group
19534 @end smallexample
19536 @noindent
19537 This pragma controls the representation of floating-point
19538 types as follows:
19540 @itemize @bullet
19541 @item
19542 @code{VAX_Float} specifies that floating-point
19543 types are represented by default with the VAX hardware types
19544 F-floating, D-floating, G-floating. Note that the H-floating
19545 type is available only on DIGITAL Vax systems, and is not available
19546 in either DEC Ada or GNAT for Alpha systems.
19548 @item
19549 @code{IEEE_Float} specifies that floating-point
19550 types are represented by default with the IEEE single and
19551 double floating-point types.
19552 @end itemize
19554 @noindent
19555 GNAT provides an identical implementation of the pragma
19556 @code{Float_Representation}, except that it functions as a
19557 configuration pragma, as defined by Ada 95. Note that the
19558 notion of configuration pragma corresponds closely to the
19559 DEC Ada notion of a program library switch.
19561 When no pragma is used in GNAT, the default is IEEE_Float, which is different
19562 from DEC Ada 83, where the default is VAX_Float. In addition, the
19563 predefined libraries in GNAT are built using IEEE_Float, so it is not
19564 advisable to change the format of numbers passed to standard library
19565 routines, and if necessary explicit type conversions may be needed.
19567 The use of IEEE_Float is recommended in GNAT since it is more efficient,
19568 and (given that it conforms to an international standard) potentially more
19569 portable. The situation in which VAX_Float may be useful is in interfacing
19570 to existing code and data that expects the use of VAX_Float. There are
19571 two possibilities here. If the requirement for the use of VAX_Float is
19572 localized, then the best approach is to use the predefined VAX_Float
19573 types in package @code{System}, as extended by
19574 @code{Extend_System}. For example, use @code{System.F_Float}
19575 to specify the 32-bit @code{F-Float} format.
19577 Alternatively, if an entire program depends heavily on the use of
19578 the @code{VAX_Float} and in particular assumes that the types in
19579 package @code{Standard} are in @code{Vax_Float} format, then it
19580 may be desirable to reconfigure GNAT to assume Vax_Float by default.
19581 This is done by using the GNAT LIBRARY command to rebuild the library, and
19582 then using the general form of the @code{Float_Representation}
19583 pragma to ensure that this default format is used throughout.
19584 The form of the GNAT LIBRARY command is:
19586 @smallexample
19587 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
19588 @end smallexample
19590 @noindent
19591 where @i{file} contains the new configuration pragmas
19592 and @i{directory} is the directory to be created to contain
19593 the new library.
19595 @noindent
19596 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
19597 to allow control over the internal representation chosen
19598 for the predefined type @code{Long_Float} and for floating-point
19599 type declarations with digits specified in the range 7 .. 15.
19600 The format of this pragma is as follows:
19602 @smallexample @c ada
19603 @cartouche
19604 pragma Long_Float (D_FLOAT | G_FLOAT);
19605 @end cartouche
19606 @end smallexample
19608 @node Fixed-Point Types and Representations
19609 @subsection Fixed-Point Types and Representations
19611 @noindent
19612 On DEC Ada for OpenVMS Alpha systems, rounding is
19613 away from zero for both positive and negative numbers.
19614 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
19616 On GNAT for OpenVMS Alpha, the results of operations
19617 on fixed-point types are in accordance with the Ada 95
19618 rules. In particular, results of operations on decimal
19619 fixed-point types are truncated.
19621 @node Record and Array Component Alignment
19622 @subsection Record and Array Component Alignment
19624 @noindent
19625 On DEC Ada for OpenVMS Alpha, all non composite components
19626 are aligned on natural boundaries. For example, 1-byte
19627 components are aligned on byte boundaries, 2-byte
19628 components on 2-byte boundaries, 4-byte components on 4-byte
19629 byte boundaries, and so on. The OpenVMS Alpha hardware
19630 runs more efficiently with naturally aligned data.
19632 ON GNAT for OpenVMS Alpha, alignment rules are compatible
19633 with DEC Ada for OpenVMS Alpha.
19635 @node Address Clauses
19636 @subsection Address Clauses
19638 @noindent
19639 In DEC Ada and GNAT, address clauses are supported for
19640 objects and imported subprograms.
19641 The predefined type @code{System.Address} is a private type
19642 in both compilers, with the same representation (it is simply
19643 a machine pointer). Addition, subtraction, and comparison
19644 operations are available in the standard Ada 95 package
19645 @code{System.Storage_Elements}, or in package @code{System}
19646 if it is extended to include @code{System.Aux_DEC} using a
19647 pragma @code{Extend_System} as previously described.
19649 Note that code that with's both this extended package @code{System}
19650 and the package @code{System.Storage_Elements} should not @code{use}
19651 both packages, or ambiguities will result. In general it is better
19652 not to mix these two sets of facilities. The Ada 95 package was
19653 designed specifically to provide the kind of features that DEC Ada
19654 adds directly to package @code{System}.
19656 GNAT is compatible with DEC Ada in its handling of address
19657 clauses, except for some limitations in
19658 the form of address clauses for composite objects with
19659 initialization. Such address clauses are easily replaced
19660 by the use of an explicitly-defined constant as described
19661 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
19662 of declarations:
19664 @smallexample @c ada
19665 @cartouche
19666 X, Y : Integer := Init_Func;
19667 Q : String (X .. Y) := "abc";
19669 for Q'Address use Compute_Address;
19670 @end cartouche
19671 @end smallexample
19673 @noindent
19674 will be rejected by GNAT, since the address cannot be computed at the time
19675 that Q is declared. To achieve the intended effect, write instead:
19677 @smallexample @c ada
19678 @group
19679 @cartouche
19680 X, Y : Integer := Init_Func;
19681 Q_Address : constant Address := Compute_Address;
19682 Q : String (X .. Y) := "abc";
19684 for Q'Address use Q_Address;
19685 @end cartouche
19686 @end group
19687 @end smallexample
19689 @noindent
19690 which will be accepted by GNAT (and other Ada 95 compilers), and is also
19691 backwards compatible with Ada 83. A fuller description of the restrictions
19692 on address specifications is found in the GNAT Reference Manual.
19694 @node Other Representation Clauses
19695 @subsection Other Representation Clauses
19697 @noindent
19698 GNAT supports in a compatible manner all the representation
19699 clauses supported by DEC Ada. In addition, it
19700 supports representation clause forms that are new in Ada 95
19701 including COMPONENT_SIZE and SIZE clauses for objects.
19703 @node The Package STANDARD
19704 @section The Package STANDARD
19706 @noindent
19707 The package STANDARD, as implemented by DEC Ada, is fully
19708 described in the Reference Manual for the Ada Programming
19709 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
19710 Language Reference Manual. As implemented by GNAT, the
19711 package STANDARD is described in the Ada 95 Reference
19712 Manual.
19714 In addition, DEC Ada supports the Latin-1 character set in
19715 the type CHARACTER. GNAT supports the Latin-1 character set
19716 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
19717 the type WIDE_CHARACTER.
19719 The floating-point types supported by GNAT are those
19720 supported by DEC Ada, but defaults are different, and are controlled by
19721 pragmas. See @pxref{Floating-Point Types and Representations} for details.
19723 @node The Package SYSTEM
19724 @section The Package SYSTEM
19726 @noindent
19727 DEC Ada provides a system-specific version of the package
19728 SYSTEM for each platform on which the language ships.
19729 For the complete specification of the package SYSTEM, see
19730 Appendix F of the DEC Ada Language Reference Manual.
19732 On DEC Ada, the package SYSTEM includes the following conversion functions:
19733 @itemize @bullet
19734 @item TO_ADDRESS(INTEGER)
19736 @item  TO_ADDRESS(UNSIGNED_LONGWORD)
19738 @item  TO_ADDRESS(universal_integer)
19740 @item  TO_INTEGER(ADDRESS)
19742 @item  TO_UNSIGNED_LONGWORD(ADDRESS)
19744 @item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
19745                  functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
19746 @end itemize
19748 @noindent
19749 By default, GNAT supplies a version of SYSTEM that matches
19750 the definition given in the Ada 95 Reference Manual.
19751 This
19752 is a subset of the DIGITAL system definitions, which is as
19753 close as possible to the original definitions. The only difference
19754 is that the definition of SYSTEM_NAME is different:
19756 @smallexample @c ada
19757 @group
19758 @cartouche
19759 type Name is (SYSTEM_NAME_GNAT);
19760 System_Name : constant Name := SYSTEM_NAME_GNAT;
19761 @end cartouche
19762 @end group
19763 @end smallexample
19765 @noindent
19766 Also, GNAT adds the new Ada 95 declarations for
19767 BIT_ORDER and DEFAULT_BIT_ORDER.
19769 However, the use of the following pragma causes GNAT
19770 to extend the definition of package SYSTEM so that it
19771 encompasses the full set of DIGITAL-specific extensions,
19772 including the functions listed above:
19774 @smallexample @c ada
19775 @cartouche
19776 pragma Extend_System (Aux_DEC);
19777 @end cartouche
19778 @end smallexample
19780 @noindent
19781 The pragma Extend_System is a configuration pragma that
19782 is most conveniently placed in the @file{gnat.adc} file. See the
19783 GNAT Reference Manual for further details.
19785 DEC Ada does not allow the recompilation of the package
19786 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
19787 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
19788 the package SYSTEM. On OpenVMS Alpha systems, the pragma
19789 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
19790 its single argument.
19792 GNAT does permit the recompilation of package SYSTEM using
19793 a special switch (@option{-gnatg}) and this switch can be used if
19794 it is necessary to modify the definitions in SYSTEM. GNAT does
19795 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
19796 or MEMORY_SIZE by any other means.
19798 On GNAT systems, the pragma SYSTEM_NAME takes the
19799 enumeration literal SYSTEM_NAME_GNAT.
19801 The definitions provided by the use of
19803 @smallexample @c ada
19804 pragma Extend_System (AUX_Dec);
19805 @end smallexample
19807 @noindent
19808 are virtually identical to those provided by the DEC Ada 83 package
19809 System. One important difference is that the name of the TO_ADDRESS
19810 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
19811 See the GNAT Reference manual for a discussion of why this change was
19812 necessary.
19814 @noindent
19815 The version of TO_ADDRESS taking a universal integer argument is in fact
19816 an extension to Ada 83 not strictly compatible with the reference manual.
19817 In GNAT, we are constrained to be exactly compatible with the standard,
19818 and this means we cannot provide this capability. In DEC Ada 83, the
19819 point of this definition is to deal with a call like:
19821 @smallexample @c ada
19822 TO_ADDRESS (16#12777#);
19823 @end smallexample
19825 @noindent
19826 Normally, according to the Ada 83 standard, one would expect this to be
19827 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
19828 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
19829 definition using universal_integer takes precedence.
19831 In GNAT, since the version with universal_integer cannot be supplied, it is
19832 not possible to be 100% compatible. Since there are many programs using
19833 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
19834 to change the name of the function in the UNSIGNED_LONGWORD case, so the
19835 declarations provided in the GNAT version of AUX_Dec are:
19837 @smallexample @c ada
19838 function To_Address (X : Integer) return Address;
19839 pragma Pure_Function (To_Address);
19841 function To_Address_Long (X : Unsigned_Longword) return Address;
19842 pragma Pure_Function (To_Address_Long);
19843 @end smallexample
19845 @noindent
19846 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
19847 change the name to TO_ADDRESS_LONG.
19849 @node Tasking and Task-Related Features
19850 @section Tasking and Task-Related Features
19852 @noindent
19853 The concepts relevant to a comparison of tasking on GNAT
19854 and on DEC Ada for OpenVMS Alpha systems are discussed in
19855 the following sections.
19857 For detailed information on concepts related to tasking in
19858 DEC Ada, see the DEC Ada Language Reference Manual and the
19859 relevant run-time reference manual.
19861 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
19862 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
19864 @noindent
19865 On OpenVMS Alpha systems, each Ada task (except a passive
19866 task) is implemented as a single stream of execution
19867 that is created and managed by the kernel. On these
19868 systems, DEC Ada tasking support is based on DECthreads,
19869 an implementation of the POSIX standard for threads.
19871 Although tasks are implemented as threads, all tasks in
19872 an Ada program are part of the same process. As a result,
19873 resources such as open files and virtual memory can be
19874 shared easily among tasks. Having all tasks in one process
19875 allows better integration with the programming environment
19876 (the shell and the debugger, for example).
19878 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
19879 code that calls DECthreads routines can be used together.
19880 The interaction between Ada tasks and DECthreads routines
19881 can have some benefits. For example when on OpenVMS Alpha,
19882 DEC Ada can call C code that is already threaded.
19883 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
19884 and Ada tasks are mapped to threads.
19886 @menu
19887 * Assigning Task IDs::
19888 * Task IDs and Delays::
19889 * Task-Related Pragmas::
19890 * Scheduling and Task Priority::
19891 * The Task Stack::
19892 * External Interrupts::
19893 @end menu
19895 @node Assigning Task IDs
19896 @subsection Assigning Task IDs
19898 @noindent
19899 The DEC Ada Run-Time Library always assigns %TASK 1 to
19900 the environment task that executes the main program. On
19901 OpenVMS Alpha systems, %TASK 0 is often used for tasks
19902 that have been created but are not yet activated.
19904 On OpenVMS Alpha systems, task IDs are assigned at
19905 activation. On GNAT systems, task IDs are also assigned at
19906 task creation but do not have the same form or values as
19907 task ID values in DEC Ada. There is no null task, and the
19908 environment task does not have a specific task ID value.
19910 @node Task IDs and Delays
19911 @subsection Task IDs and Delays
19913 @noindent
19914 On OpenVMS Alpha systems, tasking delays are implemented
19915 using Timer System Services. The Task ID is used for the
19916 identification of the timer request (the REQIDT parameter).
19917 If Timers are used in the application take care not to use
19918 0 for the identification, because cancelling such a timer
19919 will cancel all timers and may lead to unpredictable results.
19921 @node Task-Related Pragmas
19922 @subsection Task-Related Pragmas
19924 @noindent
19925 Ada supplies the pragma TASK_STORAGE, which allows
19926 specification of the size of the guard area for a task
19927 stack. (The guard area forms an area of memory that has no
19928 read or write access and thus helps in the detection of
19929 stack overflow.) On OpenVMS Alpha systems, if the pragma
19930 TASK_STORAGE specifies a value of zero, a minimal guard
19931 area is created. In the absence of a pragma TASK_STORAGE, a default guard
19932 area is created.
19934 GNAT supplies the following task-related pragmas:
19936 @itemize @bullet
19937 @item  TASK_INFO
19939               This pragma appears within a task definition and
19940               applies to the task in which it appears. The argument
19941               must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
19943 @item  TASK_STORAGE
19945               GNAT implements pragma TASK_STORAGE in the same way as
19946               DEC Ada.
19947               Both DEC Ada and GNAT supply the pragmas PASSIVE,
19948               SUPPRESS, and VOLATILE.
19949 @end itemize
19950 @node Scheduling and Task Priority
19951 @subsection Scheduling and Task Priority
19953 @noindent
19954 DEC Ada implements the Ada language requirement that
19955 when two tasks are eligible for execution and they have
19956 different priorities, the lower priority task does not
19957 execute while the higher priority task is waiting. The DEC
19958 Ada Run-Time Library keeps a task running until either the
19959 task is suspended or a higher priority task becomes ready.
19961 On OpenVMS Alpha systems, the default strategy is round-
19962 robin with preemption. Tasks of equal priority take turns
19963 at the processor. A task is run for a certain period of
19964 time and then placed at the rear of the ready queue for
19965 its priority level.
19967 DEC Ada provides the implementation-defined pragma TIME_SLICE,
19968 which can be used to enable or disable round-robin
19969 scheduling of tasks with the same priority.
19970 See the relevant DEC Ada run-time reference manual for
19971 information on using the pragmas to control DEC Ada task
19972 scheduling.
19974 GNAT follows the scheduling rules of Annex D (real-time
19975 Annex) of the Ada 95 Reference Manual. In general, this
19976 scheduling strategy is fully compatible with DEC Ada
19977 although it provides some additional constraints (as
19978 fully documented in Annex D).
19979 GNAT implements time slicing control in a manner compatible with
19980 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
19981 to the DEC Ada 83 pragma of the same name.
19982 Note that it is not possible to mix GNAT tasking and
19983 DEC Ada 83 tasking in the same program, since the two run times are
19984 not compatible.
19986 @node The Task Stack
19987 @subsection The Task Stack
19989 @noindent
19990 In DEC Ada, a task stack is allocated each time a
19991 non passive task is activated. As soon as the task is
19992 terminated, the storage for the task stack is deallocated.
19993 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
19994 a default stack size is used. Also, regardless of the size
19995 specified, some additional space is allocated for task
19996 management purposes. On OpenVMS Alpha systems, at least
19997 one page is allocated.
19999 GNAT handles task stacks in a similar manner. According to
20000 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
20001 an alternative method for controlling the task stack size.
20002 The specification of the attribute T'STORAGE_SIZE is also
20003 supported in a manner compatible with DEC Ada.
20005 @node External Interrupts
20006 @subsection External Interrupts
20008 @noindent
20009 On DEC Ada, external interrupts can be associated with task entries.
20010 GNAT is compatible with DEC Ada in its handling of external interrupts.
20012 @node Pragmas and Pragma-Related Features
20013 @section Pragmas and Pragma-Related Features
20015 @noindent
20016 Both DEC Ada and GNAT supply all language-defined pragmas
20017 as specified by the Ada 83 standard. GNAT also supplies all
20018 language-defined pragmas specified in the Ada 95 Reference Manual.
20019 In addition, GNAT implements the implementation-defined pragmas
20020 from DEC Ada 83.
20022 @itemize @bullet
20023 @item  AST_ENTRY
20025 @item  COMMON_OBJECT
20027 @item  COMPONENT_ALIGNMENT
20029 @item  EXPORT_EXCEPTION
20031 @item  EXPORT_FUNCTION
20033 @item  EXPORT_OBJECT
20035 @item  EXPORT_PROCEDURE
20037 @item  EXPORT_VALUED_PROCEDURE
20039 @item  FLOAT_REPRESENTATION
20041 @item  IDENT
20043 @item  IMPORT_EXCEPTION
20045 @item  IMPORT_FUNCTION
20047 @item  IMPORT_OBJECT
20049 @item  IMPORT_PROCEDURE
20051 @item  IMPORT_VALUED_PROCEDURE
20053 @item  INLINE_GENERIC
20055 @item  INTERFACE_NAME
20057 @item  LONG_FLOAT
20059 @item  MAIN_STORAGE
20061 @item  PASSIVE
20063 @item  PSET_OBJECT
20065 @item  SHARE_GENERIC
20067 @item  SUPPRESS_ALL
20069 @item  TASK_STORAGE
20071 @item  TIME_SLICE
20073 @item  TITLE
20074 @end itemize
20076 @noindent
20077 These pragmas are all fully implemented, with the exception of @code{Title},
20078 @code{Passive}, and @code{Share_Generic}, which are
20079 recognized, but which have no
20080 effect in GNAT. The effect of @code{Passive} may be obtained by the
20081 use of protected objects in Ada 95. In GNAT, all generics are inlined.
20083 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
20084 a separate subprogram specification which must appear before the
20085 subprogram body.
20087 GNAT also supplies a number of implementation-defined pragmas as follows:
20088 @itemize @bullet
20089 @item  C_PASS_BY_COPY
20091 @item  EXTEND_SYSTEM
20093 @item  SOURCE_FILE_NAME
20095 @item  UNSUPPRESS
20097 @item  WARNINGS
20099 @item  ABORT_DEFER
20101 @item  ADA_83
20103 @item  ADA_95
20105 @item  ANNOTATE
20107 @item  ASSERT
20109 @item  CPP_CLASS
20111 @item  CPP_CONSTRUCTOR
20113 @item  CPP_DESTRUCTOR
20115 @item  CPP_VIRTUAL
20117 @item  CP_VTABLE
20119 @item  DEBUG
20121 @item  LINKER_ALIAS
20123 @item  LINKER_SECTION
20125 @item  MACHINE_ATTRIBUTE
20127 @item  NO_RETURN
20129 @item  PURE_FUNCTION
20131 @item  SOURCE_REFERENCE
20133 @item  TASK_INFO
20135 @item  UNCHECKED_UNION
20137 @item  UNIMPLEMENTED_UNIT
20139 @item  UNIVERSAL_DATA
20141 @item  WEAK_EXTERNAL
20142 @end itemize
20144 @noindent
20145 For full details on these GNAT implementation-defined pragmas, see
20146 the GNAT Reference Manual.
20148 @menu
20149 * Restrictions on the Pragma INLINE::
20150 * Restrictions on the Pragma INTERFACE::
20151 * Restrictions on the Pragma SYSTEM_NAME::
20152 @end menu
20154 @node Restrictions on the Pragma INLINE
20155 @subsection Restrictions on the Pragma INLINE
20157 @noindent
20158 DEC Ada applies the following restrictions to the pragma INLINE:
20159 @itemize @bullet
20160 @item  Parameters cannot be a task type.
20162 @item  Function results cannot be task types, unconstrained
20163 array types, or unconstrained types with discriminants.
20165 @item  Bodies cannot declare the following:
20166 @itemize @bullet
20167 @item  Subprogram body or stub (imported subprogram is allowed)
20169 @item  Tasks
20171 @item  Generic declarations
20173 @item  Instantiations
20175 @item  Exceptions
20177 @item  Access types (types derived from access types allowed)
20179 @item  Array or record types
20181 @item  Dependent tasks
20183 @item  Direct recursive calls of subprogram or containing
20184 subprogram, directly or via a renaming
20186 @end itemize
20187 @end itemize
20189 @noindent
20190 In GNAT, the only restriction on pragma INLINE is that the
20191 body must occur before the call if both are in the same
20192 unit, and the size must be appropriately small. There are
20193 no other specific restrictions which cause subprograms to
20194 be incapable of being inlined.
20196 @node  Restrictions on the Pragma INTERFACE
20197 @subsection  Restrictions on the Pragma INTERFACE
20199 @noindent
20200 The following lists and describes the restrictions on the
20201 pragma INTERFACE on DEC Ada and GNAT:
20202 @itemize @bullet
20203 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
20204 Default is the default on OpenVMS Alpha systems.
20206 @item  Parameter passing: Language specifies default
20207 mechanisms but can be overridden with an EXPORT pragma.
20209 @itemize @bullet
20210 @item  Ada: Use internal Ada rules.
20212 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
20213 record or task type. Result cannot be a string, an
20214 array, or a record.
20216 @item  Fortran: Parameters cannot be a task. Result cannot
20217 be a string, an array, or a record.
20218 @end itemize
20219 @end itemize
20221 @noindent
20222 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
20223 record parameters for all languages.
20225 @node  Restrictions on the Pragma SYSTEM_NAME
20226 @subsection  Restrictions on the Pragma SYSTEM_NAME
20228 @noindent
20229 For DEC Ada for OpenVMS Alpha, the enumeration literal
20230 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
20231 literal for the type NAME is SYSTEM_NAME_GNAT.
20233 @node  Library of Predefined Units
20234 @section  Library of Predefined Units
20236 @noindent
20237 A library of predefined units is provided as part of the
20238 DEC Ada and GNAT implementations. DEC Ada does not provide
20239 the package MACHINE_CODE but instead recommends importing
20240 assembler code.
20242 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
20243 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20244 version. During GNAT installation, the DEC Ada Predefined
20245 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
20246 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
20247 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
20248 for details.
20250 The GNAT RTL is contained in
20251 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
20252 the default search path is set up to find DECLIB units in preference
20253 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
20254 for example).
20256 However, it is possible to change the default so that the
20257 reverse is true, or even to mix them using child package
20258 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
20259 is the package name, and the Ada units are available in the
20260 standard manner defined for Ada 95, that is to say as Ada.xxx. To
20261 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
20262 appropriately. For example, to change the default to use the Ada95
20263 versions do:
20265 @smallexample
20266 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
20267                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20268 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
20269                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20270 @end smallexample
20272 @menu
20273 * Changes to DECLIB::
20274 @end menu
20276 @node Changes to DECLIB
20277 @subsection Changes to DECLIB
20279 @noindent
20280 The changes made to the DEC Ada predefined library for GNAT and Ada 95
20281 compatibility are minor and include the following:
20283 @itemize @bullet
20284 @item  Adjusting the location of pragmas and record representation
20285 clauses to obey Ada 95 rules
20287 @item  Adding the proper notation to generic formal parameters
20288 that take unconstrained types in instantiation
20290 @item  Adding pragma ELABORATE_BODY to package specifications
20291 that have package bodies not otherwise allowed
20293 @item  Occurrences of the identifier @code{"PROTECTED"} are renamed to
20294 @code{"PROTECTD"}.
20295 Currently these are found only in the STARLET package spec.
20296 @end itemize
20298 @noindent
20299 None of the above changes is visible to users.
20301 @node Bindings
20302 @section Bindings
20304 @noindent
20305 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
20306 @itemize @bullet
20308 @item  Command Language Interpreter (CLI interface)
20310 @item  DECtalk Run-Time Library (DTK interface)
20312 @item  Librarian utility routines (LBR interface)
20314 @item  General Purpose Run-Time Library (LIB interface)
20316 @item  Math Run-Time Library (MTH interface)
20318 @item  National Character Set Run-Time Library (NCS interface)
20320 @item  Compiled Code Support Run-Time Library (OTS interface)
20322 @item  Parallel Processing Run-Time Library (PPL interface)
20324 @item  Screen Management Run-Time Library (SMG interface)
20326 @item  Sort Run-Time Library (SOR interface)
20328 @item  String Run-Time Library (STR interface)
20330 @item STARLET System Library
20331 @findex Starlet
20333 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
20335 @item  X Windows Toolkit (XT interface)
20337 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
20338 @end itemize
20340 @noindent
20341 GNAT provides implementations of these DEC bindings in the DECLIB directory.
20343 The X/Motif bindings used to build DECLIB are whatever versions are in the
20344 DEC Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20345 The build script will
20346 automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt},
20347 and @code{X_Lib}
20348 causing the default X/Motif sharable image libraries to be linked in. This
20349 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20350 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20352 It may be necessary to edit these options files to update or correct the
20353 library names if, for example, the newer X/Motif bindings from
20354 @file{ADA$EXAMPLES}
20355 had been (previous to installing GNAT) copied and renamed to supersede the
20356 default @file{ADA$PREDEFINED} versions.
20358 @menu
20359 * Shared Libraries and Options Files::
20360 * Interfaces to C::
20361 @end menu
20363 @node Shared Libraries and Options Files
20364 @subsection Shared Libraries and Options Files
20366 @noindent
20367 When using the DEC Ada
20368 predefined X and Motif bindings, the linking with their sharable images is
20369 done automatically by @command{GNAT LINK}.
20370 When using other X and Motif bindings, you need
20371 to add the corresponding sharable images to the command line for
20372 @code{GNAT LINK}. When linking with shared libraries, or with
20373 @file{.OPT} files, you must
20374 also add them to the command line for @command{GNAT LINK}.
20376 A shared library to be used with GNAT is built in the same way as other
20377 libraries under VMS. The VMS Link command can be used in standard fashion.
20379 @node Interfaces to C
20380 @subsection Interfaces to C
20382 @noindent
20383 DEC Ada
20384 provides the following Ada types and operations:
20386 @itemize @bullet
20387 @item C types package (C_TYPES)
20389 @item C strings (C_TYPES.NULL_TERMINATED)
20391 @item Other_types (SHORT_INT)
20392 @end itemize
20394 @noindent
20395 Interfacing to C with GNAT, one can use the above approach
20396 described for DEC Ada or the facilities of Annex B of
20397 the Ada 95 Reference Manual (packages INTERFACES.C,
20398 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
20399 information, see the section ``Interfacing to C'' in the
20400 @cite{GNAT Reference Manual}.
20402 The @option{-gnatF} qualifier forces default and explicit
20403 @code{External_Name} parameters in pragmas Import and Export
20404 to be uppercased for compatibility with the default behavior
20405 of Compaq C. The qualifier has no effect on @code{Link_Name} parameters.
20407 @node Main Program Definition
20408 @section Main Program Definition
20410 @noindent
20411 The following section discusses differences in the
20412 definition of main programs on DEC Ada and GNAT.
20413 On DEC Ada, main programs are defined to meet the
20414 following conditions:
20415 @itemize @bullet
20416 @item  Procedure with no formal parameters (returns 0 upon
20417        normal completion)
20419 @item  Procedure with no formal parameters (returns 42 when
20420        unhandled exceptions are raised)
20422 @item  Function with no formal parameters whose returned value
20423        is of a discrete type
20425 @item  Procedure with one OUT formal of a discrete type for
20426        which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
20428 @end itemize
20430 @noindent
20431 When declared with the pragma EXPORT_VALUED_PROCEDURE,
20432 a main function or main procedure returns a discrete
20433 value whose size is less than 64 bits (32 on VAX systems),
20434 the value is zero- or sign-extended as appropriate.
20435 On GNAT, main programs are defined as follows:
20436 @itemize @bullet
20437 @item  Must be a non-generic, parameter-less subprogram that
20438 is either a procedure or function returning an Ada
20439 STANDARD.INTEGER (the predefined type)
20441 @item  Cannot be a generic subprogram or an instantiation of a
20442 generic subprogram
20443 @end itemize
20445 @node Implementation-Defined Attributes
20446 @section Implementation-Defined Attributes
20448 @noindent
20449 GNAT provides all DEC Ada implementation-defined
20450 attributes.
20452 @node Compiler and Run-Time Interfacing
20453 @section Compiler and Run-Time Interfacing
20455 @noindent
20456 DEC Ada provides the following ways to pass options to the linker
20457 (ACS LINK):
20458 @itemize @bullet
20459 @item  /WAIT and /SUBMIT qualifiers
20461 @item  /COMMAND qualifier
20463 @item  /[NO]MAP qualifier
20465 @item  /OUTPUT=file-spec
20467 @item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
20468 @end itemize
20470 @noindent
20471 To pass options to the linker, GNAT provides the following
20472 switches:
20474 @itemize @bullet
20475 @item   @option{/EXECUTABLE=exec-name}
20477 @item   @option{/VERBOSE qualifier}
20479 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers
20480 @end itemize
20482 @noindent
20483 For more information on these switches, see
20484 @ref{Switches for gnatlink}.
20485 In DEC Ada, the command-line switch @option{/OPTIMIZE} is available
20486 to control optimization. DEC Ada also supplies the
20487 following pragmas:
20488 @itemize @bullet
20489 @item  @code{OPTIMIZE}
20491 @item  @code{INLINE}
20493 @item  @code{INLINE_GENERIC}
20495 @item  @code{SUPPRESS_ALL}
20497 @item  @code{PASSIVE}
20498 @end itemize
20500 @noindent
20501 In GNAT, optimization is controlled strictly by command
20502 line parameters, as described in the corresponding section of this guide.
20503 The DIGITAL pragmas for control of optimization are
20504 recognized but ignored.
20506 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
20507 the default is that optimization is turned on.
20509 @node Program Compilation and Library Management
20510 @section Program Compilation and Library Management
20512 @noindent
20513 DEC Ada and GNAT provide a comparable set of commands to
20514 build programs. DEC Ada also provides a program library,
20515 which is a concept that does not exist on GNAT. Instead,
20516 GNAT provides directories of sources that are compiled as
20517 needed.
20519 The following table summarizes
20520 the DEC Ada commands and provides
20521 equivalent GNAT commands. In this table, some GNAT
20522 equivalents reflect the fact that GNAT does not use the
20523 concept of a program library. Instead, it uses a model
20524 in which collections of source and object files are used
20525 in a manner consistent with other languages like C and
20526 Fortran. Therefore, standard system file commands are used
20527 to manipulate these elements. Those GNAT commands are marked with
20528 an asterisk.
20529 Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards.
20531 @need 1500
20532 @multitable @columnfractions .35 .65
20534 @item @emph{DEC Ada Command}
20535 @tab @emph{GNAT Equivalent / Description}
20537 @item @command{ADA}
20538 @tab @command{GNAT COMPILE}@*
20539 Invokes the compiler to compile one or more Ada source files.
20541 @item @command{ACS ATTACH}@*
20542 @tab [No equivalent]@*
20543 Switches control of terminal from current process running the program
20544 library manager.
20546 @item @command{ACS CHECK}
20547 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
20548 Forms the execution closure of one
20549 or more compiled units and checks completeness and currency.
20551 @item @command{ACS COMPILE}
20552 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20553 Forms the execution closure of one or
20554 more specified units, checks completeness and currency,
20555 identifies units that have revised source files, compiles same,
20556 and recompiles units that are or will become obsolete.
20557 Also completes incomplete generic instantiations.
20559 @item @command{ACS COPY FOREIGN}
20560 @tab Copy (*)@*
20561 Copies a foreign object file into the program library as a
20562 library unit body.
20564 @item @command{ACS COPY UNIT}
20565 @tab Copy (*)@*
20566 Copies a compiled unit from one program library to another.
20568 @item @command{ACS CREATE LIBRARY}
20569 @tab Create /directory (*)@*
20570 Creates a program library.
20572 @item @command{ACS CREATE SUBLIBRARY}
20573 @tab Create /directory (*)@*
20574 Creates a program sublibrary.
20576 @item @command{ACS DELETE LIBRARY}
20577 @tab @*
20578 Deletes a program library and its contents.
20580 @item @command{ACS DELETE SUBLIBRARY}
20581 @tab @*
20582 Deletes a program sublibrary and its contents.
20584 @item @command{ACS DELETE UNIT}
20585 @tab Delete file (*)@*
20586 On OpenVMS systems, deletes one or more compiled units from
20587 the current program library.
20589 @item @command{ACS DIRECTORY}
20590 @tab Directory (*)@*
20591 On OpenVMS systems, lists units contained in the current
20592 program library.
20594 @item @command{ACS ENTER FOREIGN}
20595 @tab Copy (*)@*
20596 Allows the import of a foreign body as an Ada library
20597 specification and enters a reference to a pointer.
20599 @item @command{ACS ENTER UNIT}
20600 @tab Copy (*)@*
20601 Enters a reference (pointer) from the current program library to
20602 a unit compiled into another program library.
20604 @item @command{ACS EXIT}
20605 @tab [No equivalent]@*
20606 Exits from the program library manager.
20608 @item @command{ACS EXPORT}
20609 @tab Copy (*)@*
20610 Creates an object file that contains system-specific object code
20611 for one or more units. With GNAT, object files can simply be copied
20612 into the desired directory.
20614 @item @command{ACS EXTRACT SOURCE}
20615 @tab Copy (*)@*
20616 Allows access to the copied source file for each Ada compilation unit
20618 @item @command{ACS HELP}
20619 @tab @command{HELP GNAT}@*
20620 Provides online help.
20622 @item @command{ACS LINK}
20623 @tab @command{GNAT LINK}@*
20624 Links an object file containing Ada units into an executable file.
20626 @item @command{ACS LOAD}
20627 @tab Copy (*)@*
20628 Loads (partially compiles) Ada units into the program library.
20629 Allows loading a program from a collection of files into a library
20630 without knowing the relationship among units.
20632 @item @command{ACS MERGE}
20633 @tab Copy (*)@*
20634 Merges into the current program library, one or more units from
20635 another library where they were modified.
20637 @item @command{ACS RECOMPILE}
20638 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20639 Recompiles from   external or copied source files any obsolete
20640 unit in the closure. Also, completes any incomplete generic
20641 instantiations.
20643 @item @command{ACS REENTER}
20644 @tab @command{GNAT MAKE}@*
20645 Reenters current references to units compiled after last entered
20646 with the @command{ACS ENTER UNIT} command.
20648 @item @command{ACS SET LIBRARY}
20649 @tab Set default (*)@*
20650 Defines a program library to be the compilation context as well
20651 as the target library for compiler output and commands in general.
20653 @item @command{ACS SET PRAGMA}
20654 @tab Edit @file{gnat.adc} (*)@*
20655 Redefines specified  values of the library characteristics
20656 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
20657 and @code{Float_Representation}.
20659 @item @command{ACS SET SOURCE}
20660 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
20661 Defines the source file search list for the @command{ACS COMPILE} command.
20663 @item @command{ACS SHOW LIBRARY}
20664 @tab Directory (*)@*
20665 Lists information about one or more program libraries.
20667 @item @command{ACS SHOW PROGRAM}
20668 @tab [No equivalent]@*
20669 Lists information about the execution closure of one or
20670 more units in the program library.
20672 @item @command{ACS SHOW SOURCE}
20673 @tab Show logical @code{ADA_INCLUDE_PATH}@*
20674 Shows the source file search used when compiling units.
20676 @item @command{ACS SHOW VERSION}
20677 @tab Compile with @option{VERBOSE} option
20678 Displays the version number of the compiler and program library
20679 manager used.
20681 @item @command{ACS SPAWN}
20682 @tab [No equivalent]@*
20683 Creates a subprocess of the current process (same as @command{DCL SPAWN}
20684 command).
20686 @item @command{ACS VERIFY}
20687 @tab [No equivalent]@*
20688 Performs a series of consistency checks on a program library to
20689 determine whether the library structure and library files are in
20690 valid form.
20691 @end multitable
20693 @noindent
20695 @node Input-Output
20696 @section Input-Output
20698 @noindent
20699 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
20700 Management Services (RMS) to perform operations on
20701 external files.
20703 @noindent
20704 DEC Ada and GNAT predefine an identical set of input-
20705 output packages. To make the use of the
20706 generic TEXT_IO operations more convenient, DEC Ada
20707 provides predefined library packages that instantiate the
20708 integer and floating-point operations for the predefined
20709 integer and floating-point types as shown in the following table.
20711 @multitable @columnfractions .45 .55
20712 @item @emph{Package Name} @tab Instantiation
20714 @item @code{INTEGER_TEXT_IO}
20715 @tab @code{INTEGER_IO(INTEGER)}
20717 @item @code{SHORT_INTEGER_TEXT_IO}
20718 @tab @code{INTEGER_IO(SHORT_INTEGER)}
20720 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
20721 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
20723 @item @code{FLOAT_TEXT_IO}
20724 @tab @code{FLOAT_IO(FLOAT)}
20726 @item @code{LONG_FLOAT_TEXT_IO}
20727 @tab @code{FLOAT_IO(LONG_FLOAT)}
20728 @end multitable
20730 @noindent
20731 The DEC Ada predefined packages and their operations
20732 are implemented using OpenVMS Alpha files and input-
20733 output facilities. DEC Ada supports asynchronous input-
20734 output on OpenVMS Alpha. Familiarity with the following is
20735 recommended:
20736 @itemize @bullet
20737 @item  RMS file organizations and access methods
20739 @item  OpenVMS file specifications and directories
20741 @item  OpenVMS File Definition Language (FDL)
20742 @end itemize
20744 @noindent
20745 GNAT provides I/O facilities that are completely
20746 compatible with DEC Ada. The distribution includes the
20747 standard DEC Ada versions of all I/O packages, operating
20748 in a manner compatible with DEC Ada. In particular, the
20749 following packages are by default the DEC Ada (Ada 83)
20750 versions of these packages rather than the renamings
20751 suggested in annex J of the Ada 95 Reference Manual:
20752 @itemize @bullet
20753 @item  @code{TEXT_IO}
20755 @item  @code{SEQUENTIAL_IO}
20757 @item  @code{DIRECT_IO}
20758 @end itemize
20760 @noindent
20761 The use of the standard Ada 95 syntax for child packages (for
20762 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
20763 packages, as defined in the Ada 95 Reference Manual.
20764 GNAT provides DIGITAL-compatible predefined instantiations
20765 of the @code{TEXT_IO} packages, and also
20766 provides the standard predefined instantiations required
20767 by the Ada 95 Reference Manual.
20769 For further information on how GNAT interfaces to the file
20770 system or how I/O is implemented in programs written in
20771 mixed languages, see the chapter ``Implementation of the
20772 Standard I/O'' in the @cite{GNAT Reference Manual}.
20773 This chapter covers the following:
20774 @itemize @bullet
20775 @item  Standard I/O packages
20777 @item  @code{FORM} strings
20779 @item  @code{ADA.DIRECT_IO}
20781 @item  @code{ADA.SEQUENTIAL_IO}
20783 @item  @code{ADA.TEXT_IO}
20785 @item  Stream pointer positioning
20787 @item  Reading and writing non-regular files
20789 @item  @code{GET_IMMEDIATE}
20791 @item  Treating @code{TEXT_IO} files as streams
20793 @item  Shared files
20795 @item  Open modes
20796 @end itemize
20798 @node Implementation Limits
20799 @section Implementation Limits
20801 @noindent
20802 The following table lists implementation limits for DEC Ada
20803 and GNAT systems.
20804 @multitable @columnfractions .60 .20 .20
20805 @sp 1
20806 @item  @emph{Compilation Parameter}
20807 @tab   @emph{DEC Ada}
20808 @tab   @emph{GNAT}
20809 @sp 1
20811 @item  In a subprogram or entry  declaration, maximum number of
20812        formal parameters that are of an unconstrained record type
20813 @tab   32
20814 @tab   No set limit
20815 @sp 1
20817 @item  Maximum identifier length (number of characters)
20818 @tab   255
20819 @tab   255
20820 @sp 1
20822 @item  Maximum number of characters in a source line
20823 @tab   255
20824 @tab   255
20825 @sp 1
20827 @item  Maximum collection size   (number of bytes)
20828 @tab   2**31-1
20829 @tab   2**31-1
20830 @sp 1
20832 @item  Maximum number of discriminants for a record type
20833 @tab   245
20834 @tab   No set limit
20835 @sp 1
20837 @item  Maximum number of formal parameters in an entry or
20838        subprogram declaration
20839 @tab   246
20840 @tab    No set limit
20841 @sp 1
20843 @item  Maximum number of dimensions in an array type
20844 @tab   255
20845 @tab   No set limit
20846 @sp 1
20848 @item  Maximum number of library  units and subunits in a compilation.
20849 @tab   4095
20850 @tab   No set limit
20851 @sp 1
20853 @item  Maximum number of library units and subunits in an execution.
20854 @tab   16383
20855 @tab   No set limit
20856 @sp 1
20858 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
20859        or @code{PSECT_OBJECT}
20860 @tab   32757
20861 @tab   No set limit
20862 @sp 1
20864 @item  Maximum number of enumeration literals in an enumeration type
20865        definition
20866 @tab   65535
20867 @tab   No set limit
20868 @sp 1
20870 @item  Maximum number of lines in a source file
20871 @tab   65534
20872 @tab   No set limit
20873 @sp 1
20875 @item  Maximum number of bits in any object
20876 @tab   2**31-1
20877 @tab   2**31-1
20878 @sp 1
20880 @item  Maximum size of the static portion of a stack frame (approximate)
20881 @tab   2**31-1
20882 @tab   2**31-1
20883 @end multitable
20885 @node  Tools
20886 @section Tools
20888 @end ifset
20891 @c **************************************
20892 @node Platform-Specific Information for the Run-Time Libraries
20893 @appendix Platform-Specific Information for the Run-Time Libraries
20894 @cindex Tasking and threads libraries
20895 @cindex Threads libraries and tasking
20896 @cindex Run-time libraries (platform-specific information)
20898 @noindent
20899 The GNAT run-time implementation
20900 may vary with respect to both the underlying threads library and
20901 the exception handling scheme.
20902 For threads support, one or more of the following are supplied:
20903 @itemize @bullet
20904 @item @b{native threads library}, a binding to the thread package from
20905 the underlying operating system
20907 @item @b{FSU threads library}, a binding to the Florida State University
20908 threads implementation, which complies fully with the requirements of Annex D
20910 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
20911 POSIX thread package
20912 @end itemize
20914 @noindent
20915 For exception handling, either or both of two models are supplied:
20916 @itemize @bullet
20917 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
20918 Most programs should experience a substantial speed improvement by
20919 being compiled with a ZCX run-time.
20920 This is especially true for
20921 tasking applications or applications with many exception handlers.}
20922 @cindex Zero-Cost Exceptions
20923 @cindex ZCX (Zero-Cost Exceptions)
20924 which uses binder-generated tables that
20925 are interrogated at run time to locate a handler
20927 @item @b{setjmp / longjmp} (``SJLJ''),
20928 @cindex setjmp/longjmp Exception Model
20929 @cindex SJLJ (setjmp/longjmp Exception Model)
20930 which uses dynamically-set data to establish
20931 the set of handlers
20932 @end itemize
20934 @noindent
20935 This appendix summarizes which combinations of threads and exception support
20936 are supplied on various GNAT platforms.
20937 It then shows how to select a particular library either
20938 permanently or temporarily,
20939 explains the properties of (and tradeoffs among) the various threads
20940 libraries, and provides some additional
20941 information about several specific platforms.
20943 @menu
20944 * Summary of Run-Time Configurations::
20945 * Specifying a Run-Time Library::
20946 * Choosing between Native and FSU Threads Libraries::
20947 * Choosing the Scheduling Policy::
20948 * Solaris-Specific Considerations::
20949 * IRIX-Specific Considerations::
20950 * Linux-Specific Considerations::
20951 * AIX-Specific Considerations::
20952 @end menu
20955 @node Summary of Run-Time Configurations
20956 @section Summary of Run-Time Configurations
20959 @multitable @columnfractions .30 .70
20960 @item @b{alpha-openvms}
20961 @item @code{@ @ }@i{rts-native (default)}
20962 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
20963 @item @code{@ @ @ @ }Exceptions @tab ZCX
20965 @item @b{pa-hpux}
20966 @item @code{@ @ }@i{rts-native (default)}
20967 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
20968 @item @code{@ @ @ @ }Exceptions @tab ZCX
20970 @item @code{@ @ }@i{rts-sjlj}
20971 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
20972 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20974 @item @b{sparc-solaris}  @tab
20975 @item @code{@ @ }@i{rts-native (default)}
20976 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
20977 @item @code{@ @ @ @ }Exceptions @tab ZCX
20979 @item @code{@ @ }@i{rts-fsu}    @tab
20980 @item @code{@ @ @ @ }Tasking    @tab FSU threads library
20981 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20983 @item @code{@ @ }@i{rts-m64}
20984 @item @code{@ @ @ @ }Tasking     @tab native Solaris threads library
20985 @item @code{@ @ @ @ }Exceptions  @tab ZCX
20986 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
20987 @item    @tab Use only on Solaris 8 or later.
20988 @item    @tab @xref{Building and Debugging 64-bit Applications}, for details.
20990 @item @code{@ @ }@i{rts-pthread}
20991 @item @code{@ @ @ @ }Tasking    @tab pthreads library
20992 @item @code{@ @ @ @ }Exceptions @tab ZCX
20994 @item @code{@ @ }@i{rts-sjlj}
20995 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
20996 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20998 @item @b{x86-linux}
20999 @item @code{@ @ }@i{rts-native (default)}
21000 @item @code{@ @ @ @ }Tasking    @tab LinuxThread library
21001 @item @code{@ @ @ @ }Exceptions @tab ZCX
21003 @item @code{@ @ }@i{rts-fsu}
21004 @item @code{@ @ @ @ }Tasking    @tab FSU threads library
21005 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21007 @item @code{@ @ }@i{rts-sjlj}
21008 @item @code{@ @ @ @ }Tasking    @tab LinuxThread library
21009 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21011 @item @b{x86-windows}
21012 @item @code{@ @ }@i{rts-native (default)}
21013 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21014 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21016 @end multitable
21020 @node Specifying a Run-Time Library
21021 @section Specifying a Run-Time Library
21023 @noindent
21024 The @file{adainclude} subdirectory containing the sources of the GNAT
21025 run-time library, and the @file{adalib} subdirectory containing the
21026 @file{ALI} files and the static and/or shared GNAT library, are located
21027 in the gcc target-dependent area:
21029 @smallexample
21030 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21031 @end smallexample
21033 @noindent
21034 As indicated above, on some platforms several run-time libraries are supplied.
21035 These libraries are installed in the target dependent area and
21036 contain a complete source and binary subdirectory. The detailed description
21037 below explains the differences between the different libraries in terms of
21038 their thread support.
21040 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21041 This default run time is selected by the means of soft links.
21042 For example on x86-linux:
21044 @smallexample
21045 @group
21046  $(target-dir)
21047      |
21048      +--- adainclude----------+
21049      |                        |
21050      +--- adalib-----------+  |
21051      |                     |  |
21052      +--- rts-native       |  |
21053      |    |                |  |
21054      |    +--- adainclude <---+
21055      |    |                |
21056      |    +--- adalib <----+
21057      |
21058      +--- rts-fsu
21059      |    |
21060      |    +--- adainclude
21061      |    |
21062      |    +--- adalib
21063      |
21064      +--- rts-sjlj
21065           |
21066           +--- adainclude
21067           |
21068           +--- adalib
21069 @end group
21070 @end smallexample
21072 @noindent
21073 If the @i{rts-fsu} library is to be selected on a permanent basis,
21074 these soft links can be modified with the following commands:
21076 @smallexample
21077 $ cd $target
21078 $ rm -f adainclude adalib
21079 $ ln -s rts-fsu/adainclude adainclude
21080 $ ln -s rts-fsu/adalib adalib
21081 @end smallexample
21083 @noindent
21084 Alternatively, you can specify @file{rts-fsu/adainclude} in the file
21085 @file{$target/ada_source_path} and @file{rts-fsu/adalib} in
21086 @file{$target/ada_object_path}.
21088 Selecting another run-time library temporarily can be
21089 achieved by the regular mechanism for GNAT object or source path selection:
21091 @itemize @bullet
21092 @item
21093 Set the environment variables:
21095 @smallexample
21096 $ ADA_INCLUDE_PATH=$target/rts-fsu/adainclude:$ADA_INCLUDE_PATH
21097 $ ADA_OBJECTS_PATH=$target/rts-fsu/adalib:$ADA_OBJECTS_PATH
21098 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
21099 @end smallexample
21101 @item
21102 Use @option{-aI$target/rts-fsu/adainclude}
21103 and @option{-aO$target/rts-fsu/adalib}
21104 on the @command{gnatmake} command line
21106 @item
21107 Use the switch @option{--RTS}; e.g., @option{--RTS=fsu}
21108 @cindex @option{--RTS} option
21109 @end itemize
21111 @noindent
21112 You can similarly switch to @emph{rts-sjlj}.
21114 @node Choosing between Native and FSU Threads Libraries
21115 @section Choosing between Native and FSU Threads Libraries
21116 @cindex Native threads library
21117 @cindex FSU threads library
21119 @noindent
21120 Some GNAT implementations offer a choice between
21121 native threads and FSU threads.
21123 @itemize @bullet
21124 @item
21125 The @emph{native threads} library correspond to the standard system threads
21126 implementation (e.g. LinuxThreads on GNU/Linux,
21127 @cindex LinuxThreads library
21128 POSIX threads on AIX, or
21129 Solaris threads on Solaris). When this option is chosen, GNAT provides
21130 a full and accurate implementation of the core language tasking model
21131 as described in Chapter 9 of the Ada Reference Manual,
21132 but might not (and probably does not) implement
21133 the exact semantics as specified in @w{Annex D} (the Real-Time Systems Annex).
21134 @cindex Annex D (Real-Time Systems Annex) compliance
21135 @cindex Real-Time Systems Annex compliance
21136 Indeed, the reason that a choice of libraries is offered
21137 on a given target is because some of the
21138 ACATS tests for @w{Annex D} fail using the native threads library.
21139 As far as possible, this library is implemented
21140 in accordance with Ada semantics (e.g., modifying priorities as required
21141 to simulate ceiling locking),
21142 but there are often slight inaccuracies, most often in the area of
21143 absolutely respecting the priority rules on a single
21144 processor.
21145 Moreover, it is not possible in general to define the exact behavior,
21146 because the native threads implementations
21147 are not well enough documented.
21149 On systems where the @code{SCHED_FIFO} POSIX scheduling policy is supported,
21150 @cindex POSIX scheduling policies
21151 @cindex @code{SCHED_FIFO} scheduling policy
21152 native threads will provide a behavior very close to the @w{Annex D}
21153 requirements (i.e., a run-till-blocked scheduler with fixed priorities), but
21154 on some systems (in particular GNU/Linux and Solaris), you need to have root
21155 privileges to use the @code{SCHED_FIFO} policy.
21157 @item
21158 The @emph{FSU threads} library provides a completely accurate implementation
21159 of @w{Annex D}.
21160 Thus, operating with this library, GNAT is 100% compliant with both the core
21161 and all @w{Annex D}
21162 requirements.
21163 The formal validations for implementations offering
21164 a choice of threads packages are always carried out using the FSU
21165 threads option.
21166 @end itemize
21168 @noindent
21169 From these considerations, it might seem that FSU threads are the
21170 better choice,
21171 but that is by no means always the case. The FSU threads package
21172 operates with all Ada tasks appearing to the system to be a single
21173 thread. This is often considerably more efficient than operating
21174 with separate threads, since for example, switching between tasks
21175 can be accomplished without the (in some cases considerable)
21176 overhead of a context switch between two system threads. However,
21177 it means that you may well lose concurrency at the system
21178 level. Notably, some system operations (such as I/O) may block all
21179 tasks in a program and not just the calling task. More
21180 significantly, the FSU threads approach likely means you cannot
21181 take advantage of multiple processors, since for this you need
21182 separate threads (or even separate processes) to operate on
21183 different processors.
21185 For most programs, the native threads library is
21186 usually the better choice. Use the FSU threads if absolute
21187 conformance to @w{Annex D} is important for your application, or if
21188 you find that the improved efficiency of FSU threads is significant to you.
21190 Note also that to take full advantage of Florist and Glade, it is highly
21191 recommended that you use native threads.
21194 @node Choosing the Scheduling Policy
21195 @section Choosing the Scheduling Policy
21197 @noindent
21198 When using a POSIX threads implementation, you have a choice of several
21199 scheduling policies: @code{SCHED_FIFO},
21200 @cindex @code{SCHED_FIFO} scheduling policy
21201 @code{SCHED_RR}
21202 @cindex @code{SCHED_RR} scheduling policy
21203 and @code{SCHED_OTHER}.
21204 @cindex @code{SCHED_OTHER} scheduling policy
21205 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21206 or @code{SCHED_RR} requires special (e.g., root) privileges.
21208 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21209 @code{SCHED_FIFO},
21210 @cindex @code{SCHED_FIFO} scheduling policy
21211 you can use one of the following:
21213 @itemize @bullet
21214 @item
21215 @code{pragma Time_Slice (0.0)}
21216 @cindex pragma Time_Slice
21217 @item
21218 the corresponding binder option @option{-T0}
21219 @cindex @option{-T0} option
21220 @item
21221 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21222 @cindex pragma Task_Dispatching_Policy
21223 @end itemize
21225 @noindent
21226 To specify @code{SCHED_RR},
21227 @cindex @code{SCHED_RR} scheduling policy
21228 you should use @code{pragma Time_Slice} with a
21229 value greater than @code{0.0}, or else use the corresponding @option{-T}
21230 binder option.
21234 @node Solaris-Specific Considerations
21235 @section Solaris-Specific Considerations
21236 @cindex Solaris Sparc threads libraries
21238 @noindent
21239 This section addresses some topics related to the various threads libraries
21240 on Sparc Solaris and then provides some information on building and
21241 debugging 64-bit applications.
21243 @menu
21244 * Solaris Threads Issues::
21245 * Building and Debugging 64-bit Applications::
21246 @end menu
21249 @node Solaris Threads Issues
21250 @subsection Solaris Threads Issues
21252 @noindent
21253 Starting with version 3.14, GNAT under Solaris comes with a new tasking
21254 run-time library based on POSIX threads --- @emph{rts-pthread}.
21255 @cindex rts-pthread threads library
21256 This run-time library has the advantage of being mostly shared across all
21257 POSIX-compliant thread implementations, and it also provides under
21258 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21259 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21260 and @code{PTHREAD_PRIO_PROTECT}
21261 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21262 semantics that can be selected using the predefined pragma
21263 @code{Locking_Policy}
21264 @cindex pragma Locking_Policy (under rts-pthread)
21265 with respectively
21266 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21267 @cindex @code{Inheritance_Locking} (under rts-pthread)
21268 @cindex @code{Ceiling_Locking} (under rts-pthread)
21270 As explained above, the native run-time library is based on the Solaris thread
21271 library (@code{libthread}) and is the default library.
21272 The FSU run-time library is based on the FSU threads.
21273 @cindex FSU threads library
21275 Starting with Solaris 2.5.1, when the Solaris threads library is used
21276 (this is the default), programs
21277 compiled with GNAT can automatically take advantage of
21278 and can thus execute on multiple processors.
21279 The user can alternatively specify a processor on which the program should run
21280 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21281 is made by
21282 setting the environment variable @code{GNAT_PROCESSOR}
21283 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21284 to one of the following:
21286 @table @code
21287 @item -2
21288 Use the default configuration (run the program on all
21289          available processors) - this is the same as having
21290          @code{GNAT_PROCESSOR} unset
21292 @item -1
21293 Let the run-time implementation choose one processor and run the program on
21294          that processor
21296 @item 0 .. Last_Proc
21297 Run the program on the specified processor.
21298   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21299 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21300 @end table
21303 @node Building and Debugging 64-bit Applications
21304 @subsection Building and Debugging 64-bit Applications
21306 @noindent
21307 In a 64-bit application, all the sources involved must be compiled with the
21308 @option{-m64} command-line option, and a specific GNAT library (compiled with
21309 this option) is required.
21310 The easiest way to build a 64bit application is to add
21311 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
21313 To debug these applications, dwarf-2 debug information is required, so you
21314 have to add @option{-gdwarf-2} to your gnatmake arguments.
21315 In addition, a special
21316 version of gdb, called @command{gdb64}, needs to be used.
21318 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
21319 amounts to:
21321 @smallexample
21322      $ gnatmake -m64 -gdwarf-2 --RTS=m64 hello.adb
21323      $ gdb64 hello
21324 @end smallexample
21328 @node IRIX-Specific Considerations
21329 @section IRIX-Specific Considerations
21330 @cindex IRIX thread library
21332 @noindent
21333 On SGI IRIX, the thread library depends on which compiler is used.
21334 The @emph{o32 ABI} compiler comes with a run-time library based on the
21335 user-level @code{athread}
21336 library. Thus kernel-level capabilities such as nonblocking system
21337 calls or time slicing can only be achieved reliably by specifying different
21338 @code{sprocs} via the pragma @code{Task_Info}
21339 @cindex pragma Task_Info (and IRIX threads)
21340 and the
21341 @code{System.Task_Info} package.
21342 @cindex @code{System.Task_Info} package (and IRIX threads)
21343 See the @cite{GNAT Reference Manual} for further information.
21345 The @emph{n32 ABI} compiler comes with a run-time library based on the
21346 kernel POSIX threads and thus does not have the limitations mentioned above.
21349 @node Linux-Specific Considerations
21350 @section Linux-Specific Considerations
21351 @cindex Linux threads libraries
21353 @noindent
21354 The default thread library under GNU/Linux has the following disadvantages
21355 compared to other native thread libraries:
21357 @itemize @bullet
21358 @item The size of the task's stack is limited to 2 megabytes.
21359 @item  The signal model is not POSIX compliant, which means that to send a
21360   signal to the process, you need to send the signal to all threads,
21361   e.g. by using @code{killpg()}.
21362 @end itemize
21364 @node AIX-Specific Considerations
21365 @section AIX-Specific Considerations
21366 @cindex AIX resolver library
21368 @noindent
21369 On AIX, the resolver library initializes some internal structure on
21370 the first call to @code{get*by*} functions, which are used to implement
21371 @code{GNAT.Sockets.Get_Host_By_Name} and
21372 @code{GNAT.Sockets.Get_Host_By_Addrss}.
21373 If such initialization occurs within an Ada task, and the stack size for
21374 the task is the default size, a stack overflow may occur.
21376 To avoid this overflow, the user should either ensure that the first call
21377 to @code{GNAT.Sockets.Get_Host_By_Name} or
21378 @code{GNAT.Sockets.Get_Host_By_Addrss}
21379 occurs in the environment task, or use @code{pragma Storage_Size} to
21380 specify a sufficiently large size for the stack of the task that contains
21381 this call.
21383 @c *******************************
21384 @node Example of Binder Output File
21385 @appendix Example of Binder Output File
21387 @noindent
21388 This Appendix displays the source code for @command{gnatbind}'s output
21389 file generated for a simple ``Hello World'' program.
21390 Comments have been added for clarification purposes.
21393 @smallexample @c adanocomment
21394 @iftex
21395 @leftskip=0cm
21396 @end iftex
21397 --  The package is called Ada_Main unless this name is actually used
21398 --  as a unit name in the partition, in which case some other unique
21399 --  name is used.
21401 with System;
21402 package ada_main is
21404    Elab_Final_Code : Integer;
21405    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
21407    --  The main program saves the parameters (argument count,
21408    --  argument values, environment pointer) in global variables
21409    --  for later access by other units including
21410    --  Ada.Command_Line.
21412    gnat_argc : Integer;
21413    gnat_argv : System.Address;
21414    gnat_envp : System.Address;
21416    --  The actual variables are stored in a library routine. This
21417    --  is useful for some shared library situations, where there
21418    --  are problems if variables are not in the library.
21420    pragma Import (C, gnat_argc);
21421    pragma Import (C, gnat_argv);
21422    pragma Import (C, gnat_envp);
21424    --  The exit status is similarly an external location
21426    gnat_exit_status : Integer;
21427    pragma Import (C, gnat_exit_status);
21429    GNAT_Version : constant String :=
21430                     "GNAT Version: 3.15w (20010315)";
21431    pragma Export (C, GNAT_Version, "__gnat_version");
21433    --  This is the generated adafinal routine that performs
21434    --  finalization at the end of execution. In the case where
21435    --  Ada is the main program, this main program makes a call
21436    --  to adafinal at program termination.
21438    procedure adafinal;
21439    pragma Export (C, adafinal, "adafinal");
21441    --  This is the generated adainit routine that performs
21442    --  initialization at the start of execution. In the case
21443    --  where Ada is the main program, this main program makes
21444    --  a call to adainit at program startup.
21446    procedure adainit;
21447    pragma Export (C, adainit, "adainit");
21449    --  This routine is called at the start of execution. It is
21450    --  a dummy routine that is used by the debugger to breakpoint
21451    --  at the start of execution.
21453    procedure Break_Start;
21454    pragma Import (C, Break_Start, "__gnat_break_start");
21456    --  This is the actual generated main program (it would be
21457    --  suppressed if the no main program switch were used). As
21458    --  required by standard system conventions, this program has
21459    --  the external name main.
21461    function main
21462      (argc : Integer;
21463       argv : System.Address;
21464       envp : System.Address)
21465       return Integer;
21466    pragma Export (C, main, "main");
21468    --  The following set of constants give the version
21469    --  identification values for every unit in the bound
21470    --  partition. This identification is computed from all
21471    --  dependent semantic units, and corresponds to the
21472    --  string that would be returned by use of the
21473    --  Body_Version or Version attributes.
21475    type Version_32 is mod 2 ** 32;
21476    u00001 : constant Version_32 := 16#7880BEB3#;
21477    u00002 : constant Version_32 := 16#0D24CBD0#;
21478    u00003 : constant Version_32 := 16#3283DBEB#;
21479    u00004 : constant Version_32 := 16#2359F9ED#;
21480    u00005 : constant Version_32 := 16#664FB847#;
21481    u00006 : constant Version_32 := 16#68E803DF#;
21482    u00007 : constant Version_32 := 16#5572E604#;
21483    u00008 : constant Version_32 := 16#46B173D8#;
21484    u00009 : constant Version_32 := 16#156A40CF#;
21485    u00010 : constant Version_32 := 16#033DABE0#;
21486    u00011 : constant Version_32 := 16#6AB38FEA#;
21487    u00012 : constant Version_32 := 16#22B6217D#;
21488    u00013 : constant Version_32 := 16#68A22947#;
21489    u00014 : constant Version_32 := 16#18CC4A56#;
21490    u00015 : constant Version_32 := 16#08258E1B#;
21491    u00016 : constant Version_32 := 16#367D5222#;
21492    u00017 : constant Version_32 := 16#20C9ECA4#;
21493    u00018 : constant Version_32 := 16#50D32CB6#;
21494    u00019 : constant Version_32 := 16#39A8BB77#;
21495    u00020 : constant Version_32 := 16#5CF8FA2B#;
21496    u00021 : constant Version_32 := 16#2F1EB794#;
21497    u00022 : constant Version_32 := 16#31AB6444#;
21498    u00023 : constant Version_32 := 16#1574B6E9#;
21499    u00024 : constant Version_32 := 16#5109C189#;
21500    u00025 : constant Version_32 := 16#56D770CD#;
21501    u00026 : constant Version_32 := 16#02F9DE3D#;
21502    u00027 : constant Version_32 := 16#08AB6B2C#;
21503    u00028 : constant Version_32 := 16#3FA37670#;
21504    u00029 : constant Version_32 := 16#476457A0#;
21505    u00030 : constant Version_32 := 16#731E1B6E#;
21506    u00031 : constant Version_32 := 16#23C2E789#;
21507    u00032 : constant Version_32 := 16#0F1BD6A1#;
21508    u00033 : constant Version_32 := 16#7C25DE96#;
21509    u00034 : constant Version_32 := 16#39ADFFA2#;
21510    u00035 : constant Version_32 := 16#571DE3E7#;
21511    u00036 : constant Version_32 := 16#5EB646AB#;
21512    u00037 : constant Version_32 := 16#4249379B#;
21513    u00038 : constant Version_32 := 16#0357E00A#;
21514    u00039 : constant Version_32 := 16#3784FB72#;
21515    u00040 : constant Version_32 := 16#2E723019#;
21516    u00041 : constant Version_32 := 16#623358EA#;
21517    u00042 : constant Version_32 := 16#107F9465#;
21518    u00043 : constant Version_32 := 16#6843F68A#;
21519    u00044 : constant Version_32 := 16#63305874#;
21520    u00045 : constant Version_32 := 16#31E56CE1#;
21521    u00046 : constant Version_32 := 16#02917970#;
21522    u00047 : constant Version_32 := 16#6CCBA70E#;
21523    u00048 : constant Version_32 := 16#41CD4204#;
21524    u00049 : constant Version_32 := 16#572E3F58#;
21525    u00050 : constant Version_32 := 16#20729FF5#;
21526    u00051 : constant Version_32 := 16#1D4F93E8#;
21527    u00052 : constant Version_32 := 16#30B2EC3D#;
21528    u00053 : constant Version_32 := 16#34054F96#;
21529    u00054 : constant Version_32 := 16#5A199860#;
21530    u00055 : constant Version_32 := 16#0E7F912B#;
21531    u00056 : constant Version_32 := 16#5760634A#;
21532    u00057 : constant Version_32 := 16#5D851835#;
21534    --  The following Export pragmas export the version numbers
21535    --  with symbolic names ending in B (for body) or S
21536    --  (for spec) so that they can be located in a link. The
21537    --  information provided here is sufficient to track down
21538    --  the exact versions of units used in a given build.
21540    pragma Export (C, u00001, "helloB");
21541    pragma Export (C, u00002, "system__standard_libraryB");
21542    pragma Export (C, u00003, "system__standard_libraryS");
21543    pragma Export (C, u00004, "adaS");
21544    pragma Export (C, u00005, "ada__text_ioB");
21545    pragma Export (C, u00006, "ada__text_ioS");
21546    pragma Export (C, u00007, "ada__exceptionsB");
21547    pragma Export (C, u00008, "ada__exceptionsS");
21548    pragma Export (C, u00009, "gnatS");
21549    pragma Export (C, u00010, "gnat__heap_sort_aB");
21550    pragma Export (C, u00011, "gnat__heap_sort_aS");
21551    pragma Export (C, u00012, "systemS");
21552    pragma Export (C, u00013, "system__exception_tableB");
21553    pragma Export (C, u00014, "system__exception_tableS");
21554    pragma Export (C, u00015, "gnat__htableB");
21555    pragma Export (C, u00016, "gnat__htableS");
21556    pragma Export (C, u00017, "system__exceptionsS");
21557    pragma Export (C, u00018, "system__machine_state_operationsB");
21558    pragma Export (C, u00019, "system__machine_state_operationsS");
21559    pragma Export (C, u00020, "system__machine_codeS");
21560    pragma Export (C, u00021, "system__storage_elementsB");
21561    pragma Export (C, u00022, "system__storage_elementsS");
21562    pragma Export (C, u00023, "system__secondary_stackB");
21563    pragma Export (C, u00024, "system__secondary_stackS");
21564    pragma Export (C, u00025, "system__parametersB");
21565    pragma Export (C, u00026, "system__parametersS");
21566    pragma Export (C, u00027, "system__soft_linksB");
21567    pragma Export (C, u00028, "system__soft_linksS");
21568    pragma Export (C, u00029, "system__stack_checkingB");
21569    pragma Export (C, u00030, "system__stack_checkingS");
21570    pragma Export (C, u00031, "system__tracebackB");
21571    pragma Export (C, u00032, "system__tracebackS");
21572    pragma Export (C, u00033, "ada__streamsS");
21573    pragma Export (C, u00034, "ada__tagsB");
21574    pragma Export (C, u00035, "ada__tagsS");
21575    pragma Export (C, u00036, "system__string_opsB");
21576    pragma Export (C, u00037, "system__string_opsS");
21577    pragma Export (C, u00038, "interfacesS");
21578    pragma Export (C, u00039, "interfaces__c_streamsB");
21579    pragma Export (C, u00040, "interfaces__c_streamsS");
21580    pragma Export (C, u00041, "system__file_ioB");
21581    pragma Export (C, u00042, "system__file_ioS");
21582    pragma Export (C, u00043, "ada__finalizationB");
21583    pragma Export (C, u00044, "ada__finalizationS");
21584    pragma Export (C, u00045, "system__finalization_rootB");
21585    pragma Export (C, u00046, "system__finalization_rootS");
21586    pragma Export (C, u00047, "system__finalization_implementationB");
21587    pragma Export (C, u00048, "system__finalization_implementationS");
21588    pragma Export (C, u00049, "system__string_ops_concat_3B");
21589    pragma Export (C, u00050, "system__string_ops_concat_3S");
21590    pragma Export (C, u00051, "system__stream_attributesB");
21591    pragma Export (C, u00052, "system__stream_attributesS");
21592    pragma Export (C, u00053, "ada__io_exceptionsS");
21593    pragma Export (C, u00054, "system__unsigned_typesS");
21594    pragma Export (C, u00055, "system__file_control_blockS");
21595    pragma Export (C, u00056, "ada__finalization__list_controllerB");
21596    pragma Export (C, u00057, "ada__finalization__list_controllerS");
21598    -- BEGIN ELABORATION ORDER
21599    -- ada (spec)
21600    -- gnat (spec)
21601    -- gnat.heap_sort_a (spec)
21602    -- gnat.heap_sort_a (body)
21603    -- gnat.htable (spec)
21604    -- gnat.htable (body)
21605    -- interfaces (spec)
21606    -- system (spec)
21607    -- system.machine_code (spec)
21608    -- system.parameters (spec)
21609    -- system.parameters (body)
21610    -- interfaces.c_streams (spec)
21611    -- interfaces.c_streams (body)
21612    -- system.standard_library (spec)
21613    -- ada.exceptions (spec)
21614    -- system.exception_table (spec)
21615    -- system.exception_table (body)
21616    -- ada.io_exceptions (spec)
21617    -- system.exceptions (spec)
21618    -- system.storage_elements (spec)
21619    -- system.storage_elements (body)
21620    -- system.machine_state_operations (spec)
21621    -- system.machine_state_operations (body)
21622    -- system.secondary_stack (spec)
21623    -- system.stack_checking (spec)
21624    -- system.soft_links (spec)
21625    -- system.soft_links (body)
21626    -- system.stack_checking (body)
21627    -- system.secondary_stack (body)
21628    -- system.standard_library (body)
21629    -- system.string_ops (spec)
21630    -- system.string_ops (body)
21631    -- ada.tags (spec)
21632    -- ada.tags (body)
21633    -- ada.streams (spec)
21634    -- system.finalization_root (spec)
21635    -- system.finalization_root (body)
21636    -- system.string_ops_concat_3 (spec)
21637    -- system.string_ops_concat_3 (body)
21638    -- system.traceback (spec)
21639    -- system.traceback (body)
21640    -- ada.exceptions (body)
21641    -- system.unsigned_types (spec)
21642    -- system.stream_attributes (spec)
21643    -- system.stream_attributes (body)
21644    -- system.finalization_implementation (spec)
21645    -- system.finalization_implementation (body)
21646    -- ada.finalization (spec)
21647    -- ada.finalization (body)
21648    -- ada.finalization.list_controller (spec)
21649    -- ada.finalization.list_controller (body)
21650    -- system.file_control_block (spec)
21651    -- system.file_io (spec)
21652    -- system.file_io (body)
21653    -- ada.text_io (spec)
21654    -- ada.text_io (body)
21655    -- hello (body)
21656    -- END ELABORATION ORDER
21658 end ada_main;
21660 --  The following source file name pragmas allow the generated file
21661 --  names to be unique for different main programs. They are needed
21662 --  since the package name will always be Ada_Main.
21664 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
21665 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
21667 --  Generated package body for Ada_Main starts here
21669 package body ada_main is
21671    --  The actual finalization is performed by calling the
21672    --  library routine in System.Standard_Library.Adafinal
21674    procedure Do_Finalize;
21675    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
21677    -------------
21678    -- adainit --
21679    -------------
21681 @findex adainit
21682    procedure adainit is
21684       --  These booleans are set to True once the associated unit has
21685       --  been elaborated. It is also used to avoid elaborating the
21686       --  same unit twice.
21688       E040 : Boolean;
21689       pragma Import (Ada, E040, "interfaces__c_streams_E");
21691       E008 : Boolean;
21692       pragma Import (Ada, E008, "ada__exceptions_E");
21694       E014 : Boolean;
21695       pragma Import (Ada, E014, "system__exception_table_E");
21697       E053 : Boolean;
21698       pragma Import (Ada, E053, "ada__io_exceptions_E");
21700       E017 : Boolean;
21701       pragma Import (Ada, E017, "system__exceptions_E");
21703       E024 : Boolean;
21704       pragma Import (Ada, E024, "system__secondary_stack_E");
21706       E030 : Boolean;
21707       pragma Import (Ada, E030, "system__stack_checking_E");
21709       E028 : Boolean;
21710       pragma Import (Ada, E028, "system__soft_links_E");
21712       E035 : Boolean;
21713       pragma Import (Ada, E035, "ada__tags_E");
21715       E033 : Boolean;
21716       pragma Import (Ada, E033, "ada__streams_E");
21718       E046 : Boolean;
21719       pragma Import (Ada, E046, "system__finalization_root_E");
21721       E048 : Boolean;
21722       pragma Import (Ada, E048, "system__finalization_implementation_E");
21724       E044 : Boolean;
21725       pragma Import (Ada, E044, "ada__finalization_E");
21727       E057 : Boolean;
21728       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
21730       E055 : Boolean;
21731       pragma Import (Ada, E055, "system__file_control_block_E");
21733       E042 : Boolean;
21734       pragma Import (Ada, E042, "system__file_io_E");
21736       E006 : Boolean;
21737       pragma Import (Ada, E006, "ada__text_io_E");
21739       --  Set_Globals is a library routine that stores away the
21740       --  value of the indicated set of global values in global
21741       --  variables within the library.
21743       procedure Set_Globals
21744         (Main_Priority            : Integer;
21745          Time_Slice_Value         : Integer;
21746          WC_Encoding              : Character;
21747          Locking_Policy           : Character;
21748          Queuing_Policy           : Character;
21749          Task_Dispatching_Policy  : Character;
21750          Adafinal                 : System.Address;
21751          Unreserve_All_Interrupts : Integer;
21752          Exception_Tracebacks     : Integer);
21753 @findex __gnat_set_globals
21754       pragma Import (C, Set_Globals, "__gnat_set_globals");
21756       --  SDP_Table_Build is a library routine used to build the
21757       --  exception tables. See unit Ada.Exceptions in files
21758       --  a-except.ads/adb for full details of how zero cost
21759       --  exception handling works. This procedure, the call to
21760       --  it, and the two following tables are all omitted if the
21761       --  build is in longjmp/setjump exception mode.
21763 @findex SDP_Table_Build
21764 @findex Zero Cost Exceptions
21765       procedure SDP_Table_Build
21766         (SDP_Addresses   : System.Address;
21767          SDP_Count       : Natural;
21768          Elab_Addresses  : System.Address;
21769          Elab_Addr_Count : Natural);
21770       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
21772       --  Table of Unit_Exception_Table addresses. Used for zero
21773       --  cost exception handling to build the top level table.
21775       ST : aliased constant array (1 .. 23) of System.Address := (
21776         Hello'UET_Address,
21777         Ada.Text_Io'UET_Address,
21778         Ada.Exceptions'UET_Address,
21779         Gnat.Heap_Sort_A'UET_Address,
21780         System.Exception_Table'UET_Address,
21781         System.Machine_State_Operations'UET_Address,
21782         System.Secondary_Stack'UET_Address,
21783         System.Parameters'UET_Address,
21784         System.Soft_Links'UET_Address,
21785         System.Stack_Checking'UET_Address,
21786         System.Traceback'UET_Address,
21787         Ada.Streams'UET_Address,
21788         Ada.Tags'UET_Address,
21789         System.String_Ops'UET_Address,
21790         Interfaces.C_Streams'UET_Address,
21791         System.File_Io'UET_Address,
21792         Ada.Finalization'UET_Address,
21793         System.Finalization_Root'UET_Address,
21794         System.Finalization_Implementation'UET_Address,
21795         System.String_Ops_Concat_3'UET_Address,
21796         System.Stream_Attributes'UET_Address,
21797         System.File_Control_Block'UET_Address,
21798         Ada.Finalization.List_Controller'UET_Address);
21800       --  Table of addresses of elaboration routines. Used for
21801       --  zero cost exception handling to make sure these
21802       --  addresses are included in the top level procedure
21803       --  address table.
21805       EA : aliased constant array (1 .. 23) of System.Address := (
21806         adainit'Code_Address,
21807         Do_Finalize'Code_Address,
21808         Ada.Exceptions'Elab_Spec'Address,
21809         System.Exceptions'Elab_Spec'Address,
21810         Interfaces.C_Streams'Elab_Spec'Address,
21811         System.Exception_Table'Elab_Body'Address,
21812         Ada.Io_Exceptions'Elab_Spec'Address,
21813         System.Stack_Checking'Elab_Spec'Address,
21814         System.Soft_Links'Elab_Body'Address,
21815         System.Secondary_Stack'Elab_Body'Address,
21816         Ada.Tags'Elab_Spec'Address,
21817         Ada.Tags'Elab_Body'Address,
21818         Ada.Streams'Elab_Spec'Address,
21819         System.Finalization_Root'Elab_Spec'Address,
21820         Ada.Exceptions'Elab_Body'Address,
21821         System.Finalization_Implementation'Elab_Spec'Address,
21822         System.Finalization_Implementation'Elab_Body'Address,
21823         Ada.Finalization'Elab_Spec'Address,
21824         Ada.Finalization.List_Controller'Elab_Spec'Address,
21825         System.File_Control_Block'Elab_Spec'Address,
21826         System.File_Io'Elab_Body'Address,
21827         Ada.Text_Io'Elab_Spec'Address,
21828         Ada.Text_Io'Elab_Body'Address);
21830    --  Start of processing for adainit
21832    begin
21834       --  Call SDP_Table_Build to build the top level procedure
21835       --  table for zero cost exception handling (omitted in
21836       --  longjmp/setjump mode).
21838       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
21840       --  Call Set_Globals to record various information for
21841       --  this partition.  The values are derived by the binder
21842       --  from information stored in the ali files by the compiler.
21844 @findex __gnat_set_globals
21845       Set_Globals
21846         (Main_Priority            => -1,
21847          --  Priority of main program, -1 if no pragma Priority used
21849          Time_Slice_Value         => -1,
21850          --  Time slice from Time_Slice pragma, -1 if none used
21852          WC_Encoding              => 'b',
21853          --  Wide_Character encoding used, default is brackets
21855          Locking_Policy           => ' ',
21856          --  Locking_Policy used, default of space means not
21857          --  specified, otherwise it is the first character of
21858          --  the policy name.
21860          Queuing_Policy           => ' ',
21861          --  Queuing_Policy used, default of space means not
21862          --  specified, otherwise it is the first character of
21863          --  the policy name.
21865          Task_Dispatching_Policy  => ' ',
21866          --  Task_Dispatching_Policy used, default of space means
21867          --  not specified, otherwise first character of the
21868          --  policy name.
21870          Adafinal                 => System.Null_Address,
21871          --  Address of Adafinal routine, not used anymore
21873          Unreserve_All_Interrupts => 0,
21874          --  Set true if pragma Unreserve_All_Interrupts was used
21876          Exception_Tracebacks     => 0);
21877          --  Indicates if exception tracebacks are enabled
21879       Elab_Final_Code := 1;
21881       --  Now we have the elaboration calls for all units in the partition.
21882       --  The Elab_Spec and Elab_Body attributes generate references to the
21883       --  implicit elaboration procedures generated by the compiler for
21884       --  each unit that requires elaboration.
21886       if not E040 then
21887          Interfaces.C_Streams'Elab_Spec;
21888       end if;
21889       E040 := True;
21890       if not E008 then
21891          Ada.Exceptions'Elab_Spec;
21892       end if;
21893       if not E014 then
21894          System.Exception_Table'Elab_Body;
21895          E014 := True;
21896       end if;
21897       if not E053 then
21898          Ada.Io_Exceptions'Elab_Spec;
21899          E053 := True;
21900       end if;
21901       if not E017 then
21902          System.Exceptions'Elab_Spec;
21903          E017 := True;
21904       end if;
21905       if not E030 then
21906          System.Stack_Checking'Elab_Spec;
21907       end if;
21908       if not E028 then
21909          System.Soft_Links'Elab_Body;
21910          E028 := True;
21911       end if;
21912       E030 := True;
21913       if not E024 then
21914          System.Secondary_Stack'Elab_Body;
21915          E024 := True;
21916       end if;
21917       if not E035 then
21918          Ada.Tags'Elab_Spec;
21919       end if;
21920       if not E035 then
21921          Ada.Tags'Elab_Body;
21922          E035 := True;
21923       end if;
21924       if not E033 then
21925          Ada.Streams'Elab_Spec;
21926          E033 := True;
21927       end if;
21928       if not E046 then
21929          System.Finalization_Root'Elab_Spec;
21930       end if;
21931       E046 := True;
21932       if not E008 then
21933          Ada.Exceptions'Elab_Body;
21934          E008 := True;
21935       end if;
21936       if not E048 then
21937          System.Finalization_Implementation'Elab_Spec;
21938       end if;
21939       if not E048 then
21940          System.Finalization_Implementation'Elab_Body;
21941          E048 := True;
21942       end if;
21943       if not E044 then
21944          Ada.Finalization'Elab_Spec;
21945       end if;
21946       E044 := True;
21947       if not E057 then
21948          Ada.Finalization.List_Controller'Elab_Spec;
21949       end if;
21950       E057 := True;
21951       if not E055 then
21952          System.File_Control_Block'Elab_Spec;
21953          E055 := True;
21954       end if;
21955       if not E042 then
21956          System.File_Io'Elab_Body;
21957          E042 := True;
21958       end if;
21959       if not E006 then
21960          Ada.Text_Io'Elab_Spec;
21961       end if;
21962       if not E006 then
21963          Ada.Text_Io'Elab_Body;
21964          E006 := True;
21965       end if;
21967       Elab_Final_Code := 0;
21968    end adainit;
21970    --------------
21971    -- adafinal --
21972    --------------
21974 @findex adafinal
21975    procedure adafinal is
21976    begin
21977       Do_Finalize;
21978    end adafinal;
21980    ----------
21981    -- main --
21982    ----------
21984    --  main is actually a function, as in the ANSI C standard,
21985    --  defined to return the exit status. The three parameters
21986    --  are the argument count, argument values and environment
21987    --  pointer.
21989 @findex Main Program
21990    function main
21991      (argc : Integer;
21992       argv : System.Address;
21993       envp : System.Address)
21994       return Integer
21995    is
21996       --  The initialize routine performs low level system
21997       --  initialization using a standard library routine which
21998       --  sets up signal handling and performs any other
21999       --  required setup. The routine can be found in file
22000       --  a-init.c.
22002 @findex __gnat_initialize
22003       procedure initialize;
22004       pragma Import (C, initialize, "__gnat_initialize");
22006       --  The finalize routine performs low level system
22007       --  finalization using a standard library routine. The
22008       --  routine is found in file a-final.c and in the standard
22009       --  distribution is a dummy routine that does nothing, so
22010       --  really this is a hook for special user finalization.
22012 @findex __gnat_finalize
22013       procedure finalize;
22014       pragma Import (C, finalize, "__gnat_finalize");
22016       --  We get to the main program of the partition by using
22017       --  pragma Import because if we try to with the unit and
22018       --  call it Ada style, then not only do we waste time
22019       --  recompiling it, but also, we don't really know the right
22020       --  switches (e.g. identifier character set) to be used
22021       --  to compile it.
22023       procedure Ada_Main_Program;
22024       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22026    --  Start of processing for main
22028    begin
22029       --  Save global variables
22031       gnat_argc := argc;
22032       gnat_argv := argv;
22033       gnat_envp := envp;
22035       --  Call low level system initialization
22037       Initialize;
22039       --  Call our generated Ada initialization routine
22041       adainit;
22043       --  This is the point at which we want the debugger to get
22044       --  control
22046       Break_Start;
22048       --  Now we call the main program of the partition
22050       Ada_Main_Program;
22052       --  Perform Ada finalization
22054       adafinal;
22056       --  Perform low level system finalization
22058       Finalize;
22060       --  Return the proper exit status
22061       return (gnat_exit_status);
22062    end;
22064 --  This section is entirely comments, so it has no effect on the
22065 --  compilation of the Ada_Main package. It provides the list of
22066 --  object files and linker options, as well as some standard
22067 --  libraries needed for the link. The gnatlink utility parses
22068 --  this b~hello.adb file to read these comment lines to generate
22069 --  the appropriate command line arguments for the call to the
22070 --  system linker. The BEGIN/END lines are used for sentinels for
22071 --  this parsing operation.
22073 --  The exact file names will of course depend on the environment,
22074 --  host/target and location of files on the host system.
22076 @findex Object file list
22077 -- BEGIN Object file/option list
22078    --   ./hello.o
22079    --   -L./
22080    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22081    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22082 -- END Object file/option list
22084 end ada_main;
22085 @end smallexample
22087 @noindent
22088 The Ada code in the above example is exactly what is generated by the
22089 binder. We have added comments to more clearly indicate the function
22090 of each part of the generated @code{Ada_Main} package.
22092 The code is standard Ada in all respects, and can be processed by any
22093 tools that handle Ada. In particular, it is possible to use the debugger
22094 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22095 suppose that for reasons that you do not understand, your program is crashing
22096 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22097 you can place a breakpoint on the call:
22099 @smallexample @c ada
22100 Ada.Text_Io'Elab_Body;
22101 @end smallexample
22103 @noindent
22104 and trace the elaboration routine for this package to find out where
22105 the problem might be (more usually of course you would be debugging
22106 elaboration code in your own application).
22109 @node Elaboration Order Handling in GNAT
22110 @appendix Elaboration Order Handling in GNAT
22111 @cindex Order of elaboration
22112 @cindex Elaboration control
22114 @menu
22115 * Elaboration Code in Ada 95::
22116 * Checking the Elaboration Order in Ada 95::
22117 * Controlling the Elaboration Order in Ada 95::
22118 * Controlling Elaboration in GNAT - Internal Calls::
22119 * Controlling Elaboration in GNAT - External Calls::
22120 * Default Behavior in GNAT - Ensuring Safety::
22121 * Treatment of Pragma Elaborate::
22122 * Elaboration Issues for Library Tasks::
22123 * Mixing Elaboration Models::
22124 * What to Do If the Default Elaboration Behavior Fails::
22125 * Elaboration for Access-to-Subprogram Values::
22126 * Summary of Procedures for Elaboration Control::
22127 * Other Elaboration Order Considerations::
22128 @end menu
22130 @noindent
22131 This chapter describes the handling of elaboration code in Ada 95 and
22132 in GNAT, and discusses how the order of elaboration of program units can
22133 be controlled in GNAT, either automatically or with explicit programming
22134 features.
22136 @node Elaboration Code in Ada 95
22137 @section Elaboration Code in Ada 95
22139 @noindent
22140 Ada 95 provides rather general mechanisms for executing code at elaboration
22141 time, that is to say before the main program starts executing. Such code arises
22142 in three contexts:
22144 @table @asis
22145 @item Initializers for variables.
22146 Variables declared at the library level, in package specs or bodies, can
22147 require initialization that is performed at elaboration time, as in:
22148 @smallexample @c ada
22149 @cartouche
22150 Sqrt_Half : Float := Sqrt (0.5);
22151 @end cartouche
22152 @end smallexample
22154 @item Package initialization code
22155 Code in a @code{BEGIN-END} section at the outer level of a package body is
22156 executed as part of the package body elaboration code.
22158 @item Library level task allocators
22159 Tasks that are declared using task allocators at the library level
22160 start executing immediately and hence can execute at elaboration time.
22161 @end table
22163 @noindent
22164 Subprogram calls are possible in any of these contexts, which means that
22165 any arbitrary part of the program may be executed as part of the elaboration
22166 code. It is even possible to write a program which does all its work at
22167 elaboration time, with a null main program, although stylistically this
22168 would usually be considered an inappropriate way to structure
22169 a program.
22171 An important concern arises in the context of elaboration code:
22172 we have to be sure that it is executed in an appropriate order. What we
22173 have is a series of elaboration code sections, potentially one section
22174 for each unit in the program. It is important that these execute
22175 in the correct order. Correctness here means that, taking the above
22176 example of the declaration of @code{Sqrt_Half},
22177 if some other piece of
22178 elaboration code references @code{Sqrt_Half},
22179 then it must run after the
22180 section of elaboration code that contains the declaration of
22181 @code{Sqrt_Half}.
22183 There would never be any order of elaboration problem if we made a rule
22184 that whenever you @code{with} a unit, you must elaborate both the spec and body
22185 of that unit before elaborating the unit doing the @code{with}'ing:
22187 @smallexample @c ada
22188 @group
22189 @cartouche
22190 with Unit_1;
22191 package Unit_2 is ...
22192 @end cartouche
22193 @end group
22194 @end smallexample
22196 @noindent
22197 would require that both the body and spec of @code{Unit_1} be elaborated
22198 before the spec of @code{Unit_2}. However, a rule like that would be far too
22199 restrictive. In particular, it would make it impossible to have routines
22200 in separate packages that were mutually recursive.
22202 You might think that a clever enough compiler could look at the actual
22203 elaboration code and determine an appropriate correct order of elaboration,
22204 but in the general case, this is not possible. Consider the following
22205 example.
22207 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22208 that references
22209 the variable @code{Sqrt_1}, which is declared in the elaboration code
22210 of the body of @code{Unit_1}:
22212 @smallexample @c ada
22213 @cartouche
22214 Sqrt_1 : Float := Sqrt (0.1);
22215 @end cartouche
22216 @end smallexample
22218 @noindent
22219 The elaboration code of the body of @code{Unit_1} also contains:
22221 @smallexample @c ada
22222 @group
22223 @cartouche
22224 if expression_1 = 1 then
22225    Q := Unit_2.Func_2;
22226 end if;
22227 @end cartouche
22228 @end group
22229 @end smallexample
22231 @noindent
22232 @code{Unit_2} is exactly parallel,
22233 it has a procedure @code{Func_2} that references
22234 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22235 the body @code{Unit_2}:
22237 @smallexample @c ada
22238 @cartouche
22239 Sqrt_2 : Float := Sqrt (0.1);
22240 @end cartouche
22241 @end smallexample
22243 @noindent
22244 The elaboration code of the body of @code{Unit_2} also contains:
22246 @smallexample @c ada
22247 @group
22248 @cartouche
22249 if expression_2 = 2 then
22250    Q := Unit_1.Func_1;
22251 end if;
22252 @end cartouche
22253 @end group
22254 @end smallexample
22256 @noindent
22257 Now the question is, which of the following orders of elaboration is
22258 acceptable:
22260 @smallexample
22261 @group
22262 Spec of Unit_1
22263 Spec of Unit_2
22264 Body of Unit_1
22265 Body of Unit_2
22266 @end group
22267 @end smallexample
22269 @noindent
22272 @smallexample
22273 @group
22274 Spec of Unit_2
22275 Spec of Unit_1
22276 Body of Unit_2
22277 Body of Unit_1
22278 @end group
22279 @end smallexample
22281 @noindent
22282 If you carefully analyze the flow here, you will see that you cannot tell
22283 at compile time the answer to this question.
22284 If @code{expression_1} is not equal to 1,
22285 and @code{expression_2} is not equal to 2,
22286 then either order is acceptable, because neither of the function calls is
22287 executed. If both tests evaluate to true, then neither order is acceptable
22288 and in fact there is no correct order.
22290 If one of the two expressions is true, and the other is false, then one
22291 of the above orders is correct, and the other is incorrect. For example,
22292 if @code{expression_1} = 1 and @code{expression_2} /= 2,
22293 then the call to @code{Func_2}
22294 will occur, but not the call to @code{Func_1.}
22295 This means that it is essential
22296 to elaborate the body of @code{Unit_1} before
22297 the body of @code{Unit_2}, so the first
22298 order of elaboration is correct and the second is wrong.
22300 By making @code{expression_1} and @code{expression_2}
22301 depend on input data, or perhaps
22302 the time of day, we can make it impossible for the compiler or binder
22303 to figure out which of these expressions will be true, and hence it
22304 is impossible to guarantee a safe order of elaboration at run time.
22306 @node Checking the Elaboration Order in Ada 95
22307 @section Checking the Elaboration Order in Ada 95
22309 @noindent
22310 In some languages that involve the same kind of elaboration problems,
22311 e.g. Java and C++, the programmer is expected to worry about these
22312 ordering problems himself, and it is common to
22313 write a program in which an incorrect elaboration order  gives
22314 surprising results, because it references variables before they
22315 are initialized.
22316 Ada 95 is designed to be a safe language, and a programmer-beware approach is
22317 clearly not sufficient. Consequently, the language provides three lines
22318 of defense:
22320 @table @asis
22321 @item Standard rules
22322 Some standard rules restrict the possible choice of elaboration
22323 order. In particular, if you @code{with} a unit, then its spec is always
22324 elaborated before the unit doing the @code{with}. Similarly, a parent
22325 spec is always elaborated before the child spec, and finally
22326 a spec is always elaborated before its corresponding body.
22328 @item Dynamic elaboration checks
22329 @cindex Elaboration checks
22330 @cindex Checks, elaboration
22331 Dynamic checks are made at run time, so that if some entity is accessed
22332 before it is elaborated (typically  by means of a subprogram call)
22333 then the exception (@code{Program_Error}) is raised.
22335 @item Elaboration control
22336 Facilities are provided for the programmer to specify the desired order
22337 of elaboration.
22338 @end table
22340 Let's look at these facilities in more detail. First, the rules for
22341 dynamic checking. One possible rule would be simply to say that the
22342 exception is raised if you access a variable which has not yet been
22343 elaborated. The trouble with this approach is that it could require
22344 expensive checks on every variable reference. Instead Ada 95 has two
22345 rules which are a little more restrictive, but easier to check, and
22346 easier to state:
22348 @table @asis
22349 @item Restrictions on calls
22350 A subprogram can only be called at elaboration time if its body
22351 has been elaborated. The rules for elaboration given above guarantee
22352 that the spec of the subprogram has been elaborated before the
22353 call, but not the body. If this rule is violated, then the
22354 exception @code{Program_Error} is raised.
22356 @item Restrictions on instantiations
22357 A generic unit can only be instantiated if the body of the generic
22358 unit has been elaborated. Again, the rules for elaboration given above
22359 guarantee that the spec of the generic unit has been elaborated
22360 before the instantiation, but not the body. If this rule is
22361 violated, then the exception @code{Program_Error} is raised.
22362 @end table
22364 @noindent
22365 The idea is that if the body has been elaborated, then any variables
22366 it references must have been elaborated; by checking for the body being
22367 elaborated we guarantee that none of its references causes any
22368 trouble. As we noted above, this is a little too restrictive, because a
22369 subprogram that has no non-local references in its body may in fact be safe
22370 to call. However, it really would be unsafe to rely on this, because
22371 it would mean that the caller was aware of details of the implementation
22372 in the body. This goes against the basic tenets of Ada.
22374 A plausible implementation can be described as follows.
22375 A Boolean variable is associated with each subprogram
22376 and each generic unit. This variable is initialized to False, and is set to
22377 True at the point body is elaborated. Every call or instantiation checks the
22378 variable, and raises @code{Program_Error} if the variable is False.
22380 Note that one might think that it would be good enough to have one Boolean
22381 variable for each package, but that would not deal with cases of trying
22382 to call a body in the same package as the call
22383 that has not been elaborated yet.
22384 Of course a compiler may be able to do enough analysis to optimize away
22385 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
22386 does such optimizations, but still the easiest conceptual model is to
22387 think of there being one variable per subprogram.
22389 @node Controlling the Elaboration Order in Ada 95
22390 @section Controlling the Elaboration Order in Ada 95
22392 @noindent
22393 In the previous section we discussed the rules in Ada 95 which ensure
22394 that @code{Program_Error} is raised if an incorrect elaboration order is
22395 chosen. This prevents erroneous executions, but we need mechanisms to
22396 specify a correct execution and avoid the exception altogether.
22397 To achieve this, Ada 95 provides a number of features for controlling
22398 the order of elaboration. We discuss these features in this section.
22400 First, there are several ways of indicating to the compiler that a given
22401 unit has no elaboration problems:
22403 @table @asis
22404 @item packages that do not require a body
22405 In Ada 95, a library package that does not require a body does not permit
22406 a body. This means that if we have a such a package, as in:
22408 @smallexample @c ada
22409 @group
22410 @cartouche
22411 package Definitions is
22412    generic
22413       type m is new integer;
22414    package Subp is
22415       type a is array (1 .. 10) of m;
22416       type b is array (1 .. 20) of m;
22417    end Subp;
22418 end Definitions;
22419 @end cartouche
22420 @end group
22421 @end smallexample
22423 @noindent
22424 A package that @code{with}'s @code{Definitions} may safely instantiate
22425 @code{Definitions.Subp} because the compiler can determine that there
22426 definitely is no package body to worry about in this case
22428 @item pragma Pure
22429 @cindex pragma Pure
22430 @findex Pure
22431 Places sufficient restrictions on a unit to guarantee that
22432 no call to any subprogram in the unit can result in an
22433 elaboration problem. This means that the compiler does not need
22434 to worry about the point of elaboration of such units, and in
22435 particular, does not need to check any calls to any subprograms
22436 in this unit.
22438 @item pragma Preelaborate
22439 @findex Preelaborate
22440 @cindex pragma Preelaborate
22441 This pragma places slightly less stringent restrictions on a unit than
22442 does pragma Pure,
22443 but these restrictions are still sufficient to ensure that there
22444 are no elaboration problems with any calls to the unit.
22446 @item pragma Elaborate_Body
22447 @findex Elaborate_Body
22448 @cindex pragma Elaborate_Body
22449 This pragma requires that the body of a unit be elaborated immediately
22450 after its spec. Suppose a unit @code{A} has such a pragma,
22451 and unit @code{B} does
22452 a @code{with} of unit @code{A}. Recall that the standard rules require
22453 the spec of unit @code{A}
22454 to be elaborated before the @code{with}'ing unit; given the pragma in
22455 @code{A}, we also know that the body of @code{A}
22456 will be elaborated before @code{B}, so
22457 that calls to @code{A} are safe and do not need a check.
22458 @end table
22460 @noindent
22461 Note that,
22462 unlike pragma @code{Pure} and pragma @code{Preelaborate},
22463 the use of
22464 @code{Elaborate_Body} does not guarantee that the program is
22465 free of elaboration problems, because it may not be possible
22466 to satisfy the requested elaboration order.
22467 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
22468 If a programmer
22469 marks @code{Unit_1} as @code{Elaborate_Body},
22470 and not @code{Unit_2,} then the order of
22471 elaboration will be:
22473 @smallexample
22474 @group
22475 Spec of Unit_2
22476 Spec of Unit_1
22477 Body of Unit_1
22478 Body of Unit_2
22479 @end group
22480 @end smallexample
22482 @noindent
22483 Now that means that the call to @code{Func_1} in @code{Unit_2}
22484 need not be checked,
22485 it must be safe. But the call to @code{Func_2} in
22486 @code{Unit_1} may still fail if
22487 @code{Expression_1} is equal to 1,
22488 and the programmer must still take
22489 responsibility for this not being the case.
22491 If all units carry a pragma @code{Elaborate_Body}, then all problems are
22492 eliminated, except for calls entirely within a body, which are
22493 in any case fully under programmer control. However, using the pragma
22494 everywhere is not always possible.
22495 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
22496 we marked both of them as having pragma @code{Elaborate_Body}, then
22497 clearly there would be no possible elaboration order.
22499 The above pragmas allow a server to guarantee safe use by clients, and
22500 clearly this is the preferable approach. Consequently a good rule in
22501 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
22502 and if this is not possible,
22503 mark them as @code{Elaborate_Body} if possible.
22504 As we have seen, there are situations where neither of these
22505 three pragmas can be used.
22506 So we also provide methods for clients to control the
22507 order of elaboration of the servers on which they depend:
22509 @table @asis
22510 @item pragma Elaborate (unit)
22511 @findex Elaborate
22512 @cindex pragma Elaborate
22513 This pragma is placed in the context clause, after a @code{with} clause,
22514 and it requires that the body of the named unit be elaborated before
22515 the unit in which the pragma occurs. The idea is to use this pragma
22516 if the current unit calls at elaboration time, directly or indirectly,
22517 some subprogram in the named unit.
22519 @item pragma Elaborate_All (unit)
22520 @findex Elaborate_All
22521 @cindex pragma Elaborate_All
22522 This is a stronger version of the Elaborate pragma. Consider the
22523 following example:
22525 @smallexample
22526 Unit A @code{with}'s unit B and calls B.Func in elab code
22527 Unit B @code{with}'s unit C, and B.Func calls C.Func
22528 @end smallexample
22530 @noindent
22531 Now if we put a pragma @code{Elaborate (B)}
22532 in unit @code{A}, this ensures that the
22533 body of @code{B} is elaborated before the call, but not the
22534 body of @code{C}, so
22535 the call to @code{C.Func} could still cause @code{Program_Error} to
22536 be raised.
22538 The effect of a pragma @code{Elaborate_All} is stronger, it requires
22539 not only that the body of the named unit be elaborated before the
22540 unit doing the @code{with}, but also the bodies of all units that the
22541 named unit uses, following @code{with} links transitively. For example,
22542 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
22543 then it requires
22544 not only that the body of @code{B} be elaborated before @code{A},
22545 but also the
22546 body of @code{C}, because @code{B} @code{with}'s @code{C}.
22547 @end table
22549 @noindent
22550 We are now in a position to give a usage rule in Ada 95 for avoiding
22551 elaboration problems, at least if dynamic dispatching and access to
22552 subprogram values are not used. We will handle these cases separately
22553 later.
22555 The rule is simple. If a unit has elaboration code that can directly or
22556 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
22557 a generic unit in a @code{with}'ed unit,
22558 then if the @code{with}'ed unit does not have
22559 pragma @code{Pure} or @code{Preelaborate}, then the client should have
22560 a pragma @code{Elaborate_All}
22561 for the @code{with}'ed unit. By following this rule a client is
22562 assured that calls can be made without risk of an exception.
22563 If this rule is not followed, then a program may be in one of four
22564 states:
22566 @table @asis
22567 @item No order exists
22568 No order of elaboration exists which follows the rules, taking into
22569 account any @code{Elaborate}, @code{Elaborate_All},
22570 or @code{Elaborate_Body} pragmas. In
22571 this case, an Ada 95 compiler must diagnose the situation at bind
22572 time, and refuse to build an executable program.
22574 @item One or more orders exist, all incorrect
22575 One or more acceptable elaboration orders exists, and all of them
22576 generate an elaboration order problem. In this case, the binder
22577 can build an executable program, but @code{Program_Error} will be raised
22578 when the program is run.
22580 @item Several orders exist, some right, some incorrect
22581 One or more acceptable elaboration orders exists, and some of them
22582 work, and some do not. The programmer has not controlled
22583 the order of elaboration, so the binder may or may not pick one of
22584 the correct orders, and the program may or may not raise an
22585 exception when it is run. This is the worst case, because it means
22586 that the program may fail when moved to another compiler, or even
22587 another version of the same compiler.
22589 @item One or more orders exists, all correct
22590 One ore more acceptable elaboration orders exist, and all of them
22591 work. In this case the program runs successfully. This state of
22592 affairs can be guaranteed by following the rule we gave above, but
22593 may be true even if the rule is not followed.
22594 @end table
22596 @noindent
22597 Note that one additional advantage of following our Elaborate_All rule
22598 is that the program continues to stay in the ideal (all orders OK) state
22599 even if maintenance
22600 changes some bodies of some subprograms. Conversely, if a program that does
22601 not follow this rule happens to be safe at some point, this state of affairs
22602 may deteriorate silently as a result of maintenance changes.
22604 You may have noticed that the above discussion did not mention
22605 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
22606 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
22607 code in the body makes calls to some other unit, so it is still necessary
22608 to use @code{Elaborate_All} on such units.
22610 @node Controlling Elaboration in GNAT - Internal Calls
22611 @section Controlling Elaboration in GNAT - Internal Calls
22613 @noindent
22614 In the case of internal calls, i.e. calls within a single package, the
22615 programmer has full control over the order of elaboration, and it is up
22616 to the programmer to elaborate declarations in an appropriate order. For
22617 example writing:
22619 @smallexample @c ada
22620 @group
22621 @cartouche
22622 function One return Float;
22624 Q : Float := One;
22626 function One return Float is
22627 begin
22628      return 1.0;
22629 end One;
22630 @end cartouche
22631 @end group
22632 @end smallexample
22634 @noindent
22635 will obviously raise @code{Program_Error} at run time, because function
22636 One will be called before its body is elaborated. In this case GNAT will
22637 generate a warning that the call will raise @code{Program_Error}:
22639 @smallexample
22640 @group
22641 @cartouche
22642  1. procedure y is
22643  2.    function One return Float;
22644  3.
22645  4.    Q : Float := One;
22646                     |
22647     >>> warning: cannot call "One" before body is elaborated
22648     >>> warning: Program_Error will be raised at run time
22650  5.
22651  6.    function One return Float is
22652  7.    begin
22653  8.         return 1.0;
22654  9.    end One;
22656 11. begin
22657 12.    null;
22658 13. end;
22659 @end cartouche
22660 @end group
22661 @end smallexample
22663 @noindent
22664 Note that in this particular case, it is likely that the call is safe, because
22665 the function @code{One} does not access any global variables.
22666 Nevertheless in Ada 95, we do not want the validity of the check to depend on
22667 the contents of the body (think about the separate compilation case), so this
22668 is still wrong, as we discussed in the previous sections.
22670 The error is easily corrected by rearranging the declarations so that the
22671 body of One appears before the declaration containing the call
22672 (note that in Ada 95,
22673 declarations can appear in any order, so there is no restriction that
22674 would prevent this reordering, and if we write:
22676 @smallexample @c ada
22677 @group
22678 @cartouche
22679 function One return Float;
22681 function One return Float is
22682 begin
22683      return 1.0;
22684 end One;
22686 Q : Float := One;
22687 @end cartouche
22688 @end group
22689 @end smallexample
22691 @noindent
22692 then all is well, no warning is generated, and no
22693 @code{Program_Error} exception
22694 will be raised.
22695 Things are more complicated when a chain of subprograms is executed:
22697 @smallexample @c ada
22698 @group
22699 @cartouche
22700 function A return Integer;
22701 function B return Integer;
22702 function C return Integer;
22704 function B return Integer is begin return A; end;
22705 function C return Integer is begin return B; end;
22707 X : Integer := C;
22709 function A return Integer is begin return 1; end;
22710 @end cartouche
22711 @end group
22712 @end smallexample
22714 @noindent
22715 Now the call to @code{C}
22716 at elaboration time in the declaration of @code{X} is correct, because
22717 the body of @code{C} is already elaborated,
22718 and the call to @code{B} within the body of
22719 @code{C} is correct, but the call
22720 to @code{A} within the body of @code{B} is incorrect, because the body
22721 of @code{A} has not been elaborated, so @code{Program_Error}
22722 will be raised on the call to @code{A}.
22723 In this case GNAT will generate a
22724 warning that @code{Program_Error} may be
22725 raised at the point of the call. Let's look at the warning:
22727 @smallexample
22728 @group
22729 @cartouche
22730  1. procedure x is
22731  2.    function A return Integer;
22732  3.    function B return Integer;
22733  4.    function C return Integer;
22734  5.
22735  6.    function B return Integer is begin return A; end;
22736                                                     |
22737     >>> warning: call to "A" before body is elaborated may
22738                  raise Program_Error
22739     >>> warning: "B" called at line 7
22740     >>> warning: "C" called at line 9
22742  7.    function C return Integer is begin return B; end;
22743  8.
22744  9.    X : Integer := C;
22746 11.    function A return Integer is begin return 1; end;
22748 13. begin
22749 14.    null;
22750 15. end;
22751 @end cartouche
22752 @end group
22753 @end smallexample
22755 @noindent
22756 Note that the message here says ``may raise'', instead of the direct case,
22757 where the message says ``will be raised''. That's because whether
22758 @code{A} is
22759 actually called depends in general on run-time flow of control.
22760 For example, if the body of @code{B} said
22762 @smallexample @c ada
22763 @group
22764 @cartouche
22765 function B return Integer is
22766 begin
22767    if some-condition-depending-on-input-data then
22768       return A;
22769    else
22770       return 1;
22771    end if;
22772 end B;
22773 @end cartouche
22774 @end group
22775 @end smallexample
22777 @noindent
22778 then we could not know until run time whether the incorrect call to A would
22779 actually occur, so @code{Program_Error} might
22780 or might not be raised. It is possible for a compiler to
22781 do a better job of analyzing bodies, to
22782 determine whether or not @code{Program_Error}
22783 might be raised, but it certainly
22784 couldn't do a perfect job (that would require solving the halting problem
22785 and is provably impossible), and because this is a warning anyway, it does
22786 not seem worth the effort to do the analysis. Cases in which it
22787 would be relevant are rare.
22789 In practice, warnings of either of the forms given
22790 above will usually correspond to
22791 real errors, and should be examined carefully and eliminated.
22792 In the rare case where a warning is bogus, it can be suppressed by any of
22793 the following methods:
22795 @itemize @bullet
22796 @item
22797 Compile with the @option{-gnatws} switch set
22799 @item
22800 Suppress @code{Elaboration_Check} for the called subprogram
22802 @item
22803 Use pragma @code{Warnings_Off} to turn warnings off for the call
22804 @end itemize
22806 @noindent
22807 For the internal elaboration check case,
22808 GNAT by default generates the
22809 necessary run-time checks to ensure
22810 that @code{Program_Error} is raised if any
22811 call fails an elaboration check. Of course this can only happen if a
22812 warning has been issued as described above. The use of pragma
22813 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
22814 some of these checks, meaning that it may be possible (but is not
22815 guaranteed) for a program to be able to call a subprogram whose body
22816 is not yet elaborated, without raising a @code{Program_Error} exception.
22818 @node Controlling Elaboration in GNAT - External Calls
22819 @section Controlling Elaboration in GNAT - External Calls
22821 @noindent
22822 The previous section discussed the case in which the execution of a
22823 particular thread of elaboration code occurred entirely within a
22824 single unit. This is the easy case to handle, because a programmer
22825 has direct and total control over the order of elaboration, and
22826 furthermore, checks need only be generated in cases which are rare
22827 and which the compiler can easily detect.
22828 The situation is more complex when separate compilation is taken into account.
22829 Consider the following:
22831 @smallexample @c ada
22832 @cartouche
22833 @group
22834 package Math is
22835    function Sqrt (Arg : Float) return Float;
22836 end Math;
22838 package body Math is
22839    function Sqrt (Arg : Float) return Float is
22840    begin
22841          ...
22842    end Sqrt;
22843 end Math;
22844 @end group
22845 @group
22846 with Math;
22847 package Stuff is
22848    X : Float := Math.Sqrt (0.5);
22849 end Stuff;
22851 with Stuff;
22852 procedure Main is
22853 begin
22854    ...
22855 end Main;
22856 @end group
22857 @end cartouche
22858 @end smallexample
22860 @noindent
22861 where @code{Main} is the main program. When this program is executed, the
22862 elaboration code must first be executed, and one of the jobs of the
22863 binder is to determine the order in which the units of a program are
22864 to be elaborated. In this case we have four units: the spec and body
22865 of @code{Math},
22866 the spec of @code{Stuff} and the body of @code{Main}).
22867 In what order should the four separate sections of elaboration code
22868 be executed?
22870 There are some restrictions in the order of elaboration that the binder
22871 can choose. In particular, if unit U has a @code{with}
22872 for a package @code{X}, then you
22873 are assured that the spec of @code{X}
22874 is elaborated before U , but you are
22875 not assured that the body of @code{X}
22876 is elaborated before U.
22877 This means that in the above case, the binder is allowed to choose the
22878 order:
22880 @smallexample
22881 spec of Math
22882 spec of Stuff
22883 body of Math
22884 body of Main
22885 @end smallexample
22887 @noindent
22888 but that's not good, because now the call to @code{Math.Sqrt}
22889 that happens during
22890 the elaboration of the @code{Stuff}
22891 spec happens before the body of @code{Math.Sqrt} is
22892 elaborated, and hence causes @code{Program_Error} exception to be raised.
22893 At first glance, one might say that the binder is misbehaving, because
22894 obviously you want to elaborate the body of something you @code{with}
22895 first, but
22896 that is not a general rule that can be followed in all cases. Consider
22898 @smallexample @c ada
22899 @group
22900 @cartouche
22901 package X is ...
22903 package Y is ...
22905 with X;
22906 package body Y is ...
22908 with Y;
22909 package body X is ...
22910 @end cartouche
22911 @end group
22912 @end smallexample
22914 @noindent
22915 This is a common arrangement, and, apart from the order of elaboration
22916 problems that might arise in connection with elaboration code, this works fine.
22917 A rule that says that you must first elaborate the body of anything you
22918 @code{with} cannot work in this case:
22919 the body of @code{X} @code{with}'s @code{Y},
22920 which means you would have to
22921 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
22922 which means
22923 you have to elaborate the body of @code{X} first, but ... and we have a
22924 loop that cannot be broken.
22926 It is true that the binder can in many cases guess an order of elaboration
22927 that is unlikely to cause a @code{Program_Error}
22928 exception to be raised, and it tries to do so (in the
22929 above example of @code{Math/Stuff/Spec}, the GNAT binder will
22930 by default
22931 elaborate the body of @code{Math} right after its spec, so all will be well).
22933 However, a program that blindly relies on the binder to be helpful can
22934 get into trouble, as we discussed in the previous sections, so
22935 GNAT
22936 provides a number of facilities for assisting the programmer in
22937 developing programs that are robust with respect to elaboration order.
22939 @node Default Behavior in GNAT - Ensuring Safety
22940 @section Default Behavior in GNAT - Ensuring Safety
22942 @noindent
22943 The default behavior in GNAT ensures elaboration safety. In its
22944 default mode GNAT implements the
22945 rule we previously described as the right approach. Let's restate it:
22947 @itemize
22948 @item
22949 @emph{If a unit has elaboration code that can directly or indirectly make a
22950 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
22951 in a @code{with}'ed unit, then if the @code{with}'ed unit
22952 does not have pragma @code{Pure} or
22953 @code{Preelaborate}, then the client should have an
22954 @code{Elaborate_All} for the @code{with}'ed unit.}
22955 @end itemize
22957 @noindent
22958 By following this rule a client is assured that calls and instantiations
22959 can be made without risk of an exception.
22961 In this mode GNAT traces all calls that are potentially made from
22962 elaboration code, and puts in any missing implicit @code{Elaborate_All}
22963 pragmas.
22964 The advantage of this approach is that no elaboration problems
22965 are possible if the binder can find an elaboration order that is
22966 consistent with these implicit @code{Elaborate_All} pragmas. The
22967 disadvantage of this approach is that no such order may exist.
22969 If the binder does not generate any diagnostics, then it means that it
22970 has found an elaboration order that is guaranteed to be safe. However,
22971 the binder may still be relying on implicitly generated
22972 @code{Elaborate_All} pragmas so portability to other compilers than
22973 GNAT is not guaranteed.
22975 If it is important to guarantee portability, then the compilations should
22976 use the
22977 @option{-gnatwl}
22978 (warn on elaboration problems) switch. This will cause warning messages
22979 to be generated indicating the missing @code{Elaborate_All} pragmas.
22980 Consider the following source program:
22982 @smallexample @c ada
22983 @group
22984 @cartouche
22985 with k;
22986 package j is
22987   m : integer := k.r;
22988 end;
22989 @end cartouche
22990 @end group
22991 @end smallexample
22993 @noindent
22994 where it is clear that there
22995 should be a pragma @code{Elaborate_All}
22996 for unit @code{k}. An implicit pragma will be generated, and it is
22997 likely that the binder will be able to honor it. However, if you want
22998 to port this program to some other Ada compiler than GNAT.
22999 it is safer to include the pragma explicitly in the source. If this
23000 unit is compiled with the
23001 @option{-gnatwl}
23002 switch, then the compiler outputs a warning:
23004 @smallexample
23005 @group
23006 @cartouche
23007 1. with k;
23008 2. package j is
23009 3.   m : integer := k.r;
23010                      |
23011    >>> warning: call to "r" may raise Program_Error
23012    >>> warning: missing pragma Elaborate_All for "k"
23014 4. end;
23015 @end cartouche
23016 @end group
23017 @end smallexample
23019 @noindent
23020 and these warnings can be used as a guide for supplying manually
23021 the missing pragmas. It is usually a bad idea to use this warning
23022 option during development. That's because it will warn you when
23023 you need to put in a pragma, but cannot warn you when it is time
23024 to take it out. So the use of pragma Elaborate_All may lead to
23025 unnecessary dependencies and even false circularities.
23027 This default mode is more restrictive than the Ada Reference
23028 Manual, and it is possible to construct programs which will compile
23029 using the dynamic model described there, but will run into a
23030 circularity using the safer static model we have described.
23032 Of course any Ada compiler must be able to operate in a mode
23033 consistent with the requirements of the Ada Reference Manual,
23034 and in particular must have the capability of implementing the
23035 standard dynamic model of elaboration with run-time checks.
23037 In GNAT, this standard mode can be achieved either by the use of
23038 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
23039 command, or by the use of the configuration pragma:
23041 @smallexample @c ada
23042 pragma Elaboration_Checks (RM);
23043 @end smallexample
23045 @noindent
23046 Either approach will cause the unit affected to be compiled using the
23047 standard dynamic run-time elaboration checks described in the Ada
23048 Reference Manual. The static model is generally preferable, since it
23049 is clearly safer to rely on compile and link time checks rather than
23050 run-time checks. However, in the case of legacy code, it may be
23051 difficult to meet the requirements of the static model. This
23052 issue is further discussed in
23053 @ref{What to Do If the Default Elaboration Behavior Fails}.
23055 Note that the static model provides a strict subset of the allowed
23056 behavior and programs of the Ada Reference Manual, so if you do
23057 adhere to the static model and no circularities exist,
23058 then you are assured that your program will
23059 work using the dynamic model, providing that you remove any
23060 pragma Elaborate statements from the source.
23062 @node Treatment of Pragma Elaborate
23063 @section Treatment of Pragma Elaborate
23064 @cindex Pragma Elaborate
23066 @noindent
23067 The use of @code{pragma Elaborate}
23068 should generally be avoided in Ada 95 programs.
23069 The reason for this is that there is no guarantee that transitive calls
23070 will be properly handled. Indeed at one point, this pragma was placed
23071 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23073 Now that's a bit restrictive. In practice, the case in which
23074 @code{pragma Elaborate} is useful is when the caller knows that there
23075 are no transitive calls, or that the called unit contains all necessary
23076 transitive @code{pragma Elaborate} statements, and legacy code often
23077 contains such uses.
23079 Strictly speaking the static mode in GNAT should ignore such pragmas,
23080 since there is no assurance at compile time that the necessary safety
23081 conditions are met. In practice, this would cause GNAT to be incompatible
23082 with correctly written Ada 83 code that had all necessary
23083 @code{pragma Elaborate} statements in place. Consequently, we made the
23084 decision that GNAT in its default mode will believe that if it encounters
23085 a @code{pragma Elaborate} then the programmer knows what they are doing,
23086 and it will trust that no elaboration errors can occur.
23088 The result of this decision is two-fold. First to be safe using the
23089 static mode, you should remove all @code{pragma Elaborate} statements.
23090 Second, when fixing circularities in existing code, you can selectively
23091 use @code{pragma Elaborate} statements to convince the static mode of
23092 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23093 statement.
23095 When using the static mode with @option{-gnatwl}, any use of
23096 @code{pragma Elaborate} will generate a warning about possible
23097 problems.
23099 @node Elaboration Issues for Library Tasks
23100 @section Elaboration Issues for Library Tasks
23101 @cindex Library tasks, elaboration issues
23102 @cindex Elaboration of library tasks
23104 @noindent
23105 In this section we examine special elaboration issues that arise for
23106 programs that declare library level tasks.
23108 Generally the model of execution of an Ada program is that all units are
23109 elaborated, and then execution of the program starts. However, the
23110 declaration of library tasks definitely does not fit this model. The
23111 reason for this is that library tasks start as soon as they are declared
23112 (more precisely, as soon as the statement part of the enclosing package
23113 body is reached), that is to say before elaboration
23114 of the program is complete. This means that if such a task calls a
23115 subprogram, or an entry in another task, the callee may or may not be
23116 elaborated yet, and in the standard
23117 Reference Manual model of dynamic elaboration checks, you can even
23118 get timing dependent Program_Error exceptions, since there can be
23119 a race between the elaboration code and the task code.
23121 The static model of elaboration in GNAT seeks to avoid all such
23122 dynamic behavior, by being conservative, and the conservative
23123 approach in this particular case is to assume that all the code
23124 in a task body is potentially executed at elaboration time if
23125 a task is declared at the library level.
23127 This can definitely result in unexpected circularities. Consider
23128 the following example
23130 @smallexample @c ada
23131 package Decls is
23132   task Lib_Task is
23133      entry Start;
23134   end Lib_Task;
23136   type My_Int is new Integer;
23138   function Ident (M : My_Int) return My_Int;
23139 end Decls;
23141 with Utils;
23142 package body Decls is
23143   task body Lib_Task is
23144   begin
23145      accept Start;
23146      Utils.Put_Val (2);
23147   end Lib_Task;
23149   function Ident (M : My_Int) return My_Int is
23150   begin
23151      return M;
23152   end Ident;
23153 end Decls;
23155 with Decls;
23156 package Utils is
23157   procedure Put_Val (Arg : Decls.My_Int);
23158 end Utils;
23160 with Text_IO;
23161 package body Utils is
23162   procedure Put_Val (Arg : Decls.My_Int) is
23163   begin
23164      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23165   end Put_Val;
23166 end Utils;
23168 with Decls;
23169 procedure Main is
23170 begin
23171    Decls.Lib_Task.Start;
23172 end;
23173 @end smallexample
23175 @noindent
23176 If the above example is compiled in the default static elaboration
23177 mode, then a circularity occurs. The circularity comes from the call
23178 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23179 this call occurs in elaboration code, we need an implicit pragma
23180 @code{Elaborate_All} for @code{Utils}. This means that not only must
23181 the spec and body of @code{Utils} be elaborated before the body
23182 of @code{Decls}, but also the spec and body of any unit that is
23183 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23184 the body of @code{Decls}. This is the transitive implication of
23185 pragma @code{Elaborate_All} and it makes sense, because in general
23186 the body of @code{Put_Val} might have a call to something in a
23187 @code{with'ed} unit.
23189 In this case, the body of Utils (actually its spec) @code{with's}
23190 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23191 must be elaborated before itself, in case there is a call from the
23192 body of @code{Utils}.
23194 Here is the exact chain of events we are worrying about:
23196 @enumerate
23197 @item
23198 In the body of @code{Decls} a call is made from within the body of a library
23199 task to a subprogram in the package @code{Utils}. Since this call may
23200 occur at elaboration time (given that the task is activated at elaboration
23201 time), we have to assume the worst, i.e. that the
23202 call does happen at elaboration time.
23204 @item
23205 This means that the body and spec of @code{Util} must be elaborated before
23206 the body of @code{Decls} so that this call does not cause an access before
23207 elaboration.
23209 @item
23210 Within the body of @code{Util}, specifically within the body of
23211 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23212 by this package.
23214 @item
23215 One such @code{with}'ed package is package @code{Decls}, so there
23216 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23217 In fact there is such a call in this example, but we would have to
23218 assume that there was such a call even if it were not there, since
23219 we are not supposed to write the body of @code{Decls} knowing what
23220 is in the body of @code{Utils}; certainly in the case of the
23221 static elaboration model, the compiler does not know what is in
23222 other bodies and must assume the worst.
23224 @item
23225 This means that the spec and body of @code{Decls} must also be
23226 elaborated before we elaborate the unit containing the call, but
23227 that unit is @code{Decls}! This means that the body of @code{Decls}
23228 must be elaborated before itself, and that's a circularity.
23229 @end enumerate
23231 @noindent
23232 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
23233 the body of @code{Decls} you will get a true Ada Reference Manual
23234 circularity that makes the program illegal.
23236 In practice, we have found that problems with the static model of
23237 elaboration in existing code often arise from library tasks, so
23238 we must address this particular situation.
23240 Note that if we compile and run the program above, using the dynamic model of
23241 elaboration (that is to say use the @option{-gnatE} switch),
23242 then it compiles, binds,
23243 links, and runs, printing the expected result of 2. Therefore in some sense
23244 the circularity here is only apparent, and we need to capture
23245 the properties of this program that  distinguish it from other library-level
23246 tasks that have real elaboration problems.
23248 We have four possible answers to this question:
23250 @itemize @bullet
23252 @item
23253 Use the dynamic model of elaboration.
23255 If we use the @option{-gnatE} switch, then as noted above, the program works.
23256 Why is this? If we examine the task body, it is apparent that the task cannot
23257 proceed past the
23258 @code{accept} statement until after elaboration has been completed, because
23259 the corresponding entry call comes from the main program, not earlier.
23260 This is why the dynamic model works here. But that's really giving
23261 up on a precise analysis, and we prefer to take this approach only if we cannot
23262 solve the
23263 problem in any other manner. So let us examine two ways to reorganize
23264 the program to avoid the potential elaboration problem.
23266 @item
23267 Split library tasks into separate packages.
23269 Write separate packages, so that library tasks are isolated from
23270 other declarations as much as possible. Let us look at a variation on
23271 the above program.
23273 @smallexample @c ada
23274 package Decls1 is
23275   task Lib_Task is
23276      entry Start;
23277   end Lib_Task;
23278 end Decls1;
23280 with Utils;
23281 package body Decls1 is
23282   task body Lib_Task is
23283   begin
23284      accept Start;
23285      Utils.Put_Val (2);
23286   end Lib_Task;
23287 end Decls1;
23289 package Decls2 is
23290   type My_Int is new Integer;
23291   function Ident (M : My_Int) return My_Int;
23292 end Decls2;
23294 with Utils;
23295 package body Decls2 is
23296   function Ident (M : My_Int) return My_Int is
23297   begin
23298      return M;
23299   end Ident;
23300 end Decls2;
23302 with Decls2;
23303 package Utils is
23304   procedure Put_Val (Arg : Decls2.My_Int);
23305 end Utils;
23307 with Text_IO;
23308 package body Utils is
23309   procedure Put_Val (Arg : Decls2.My_Int) is
23310   begin
23311      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23312   end Put_Val;
23313 end Utils;
23315 with Decls1;
23316 procedure Main is
23317 begin
23318    Decls1.Lib_Task.Start;
23319 end;
23320 @end smallexample
23322 @noindent
23323 All we have done is to split @code{Decls} into two packages, one
23324 containing the library task, and one containing everything else. Now
23325 there is no cycle, and the program compiles, binds, links and executes
23326 using the default static model of elaboration.
23328 @item
23329 Declare separate task types.
23331 A significant part of the problem arises because of the use of the
23332 single task declaration form. This means that the elaboration of
23333 the task type, and the elaboration of the task itself (i.e. the
23334 creation of the task) happen at the same time. A good rule
23335 of style in Ada 95 is to always create explicit task types. By
23336 following the additional step of placing task objects in separate
23337 packages from the task type declaration, many elaboration problems
23338 are avoided. Here is another modified example of the example program:
23340 @smallexample @c ada
23341 package Decls is
23342   task type Lib_Task_Type is
23343      entry Start;
23344   end Lib_Task_Type;
23346   type My_Int is new Integer;
23348   function Ident (M : My_Int) return My_Int;
23349 end Decls;
23351 with Utils;
23352 package body Decls is
23353   task body Lib_Task_Type is
23354   begin
23355      accept Start;
23356      Utils.Put_Val (2);
23357   end Lib_Task_Type;
23359   function Ident (M : My_Int) return My_Int is
23360   begin
23361      return M;
23362   end Ident;
23363 end Decls;
23365 with Decls;
23366 package Utils is
23367   procedure Put_Val (Arg : Decls.My_Int);
23368 end Utils;
23370 with Text_IO;
23371 package body Utils is
23372   procedure Put_Val (Arg : Decls.My_Int) is
23373   begin
23374      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23375   end Put_Val;
23376 end Utils;
23378 with Decls;
23379 package Declst is
23380    Lib_Task : Decls.Lib_Task_Type;
23381 end Declst;
23383 with Declst;
23384 procedure Main is
23385 begin
23386    Declst.Lib_Task.Start;
23387 end;
23388 @end smallexample
23390 @noindent
23391 What we have done here is to replace the @code{task} declaration in
23392 package @code{Decls} with a @code{task type} declaration. Then we
23393 introduce a separate package @code{Declst} to contain the actual
23394 task object. This separates the elaboration issues for
23395 the @code{task type}
23396 declaration, which causes no trouble, from the elaboration issues
23397 of the task object, which is also unproblematic, since it is now independent
23398 of the elaboration of  @code{Utils}.
23399 This separation of concerns also corresponds to
23400 a generally sound engineering principle of separating declarations
23401 from instances. This version of the program also compiles, binds, links,
23402 and executes, generating the expected output.
23404 @item
23405 Use No_Entry_Calls_In_Elaboration_Code restriction.
23406 @cindex No_Entry_Calls_In_Elaboration_Code
23408 The previous two approaches described how a program can be restructured
23409 to avoid the special problems caused by library task bodies. in practice,
23410 however, such restructuring may be difficult to apply to existing legacy code,
23411 so we must consider solutions that do not require massive rewriting.
23413 Let us consider more carefully why our original sample program works
23414 under the dynamic model of elaboration. The reason is that the code
23415 in the task body blocks immediately on the @code{accept}
23416 statement. Now of course there is nothing to prohibit elaboration
23417 code from making entry calls (for example from another library level task),
23418 so we cannot tell in isolation that
23419 the task will not execute the accept statement  during elaboration.
23421 However, in practice it is very unusual to see elaboration code
23422 make any entry calls, and the pattern of tasks starting
23423 at elaboration time and then immediately blocking on @code{accept} or
23424 @code{select} statements is very common. What this means is that
23425 the compiler is being too pessimistic when it analyzes the
23426 whole package body as though it might be executed at elaboration
23427 time.
23429 If we know that the elaboration code contains no entry calls, (a very safe
23430 assumption most of the time, that could almost be made the default
23431 behavior), then we can compile all units of the program under control
23432 of the following configuration pragma:
23434 @smallexample
23435 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
23436 @end smallexample
23438 @noindent
23439 This pragma can be placed in the @file{gnat.adc} file in the usual
23440 manner. If we take our original unmodified program and compile it
23441 in the presence of a @file{gnat.adc} containing the above pragma,
23442 then once again, we can compile, bind, link, and execute, obtaining
23443 the expected result. In the presence of this pragma, the compiler does
23444 not trace calls in a task body, that appear after the first @code{accept}
23445 or @code{select} statement, and therefore does not report a potential
23446 circularity in the original program.
23448 The compiler will check to the extent it can that the above
23449 restriction is not violated, but it is not always possible to do a
23450 complete check at compile time, so it is important to use this
23451 pragma only if the stated restriction is in fact met, that is to say
23452 no task receives an entry call before elaboration of all units is completed.
23454 @end itemize
23456 @node Mixing Elaboration Models
23457 @section Mixing Elaboration Models
23458 @noindent
23459 So far, we have assumed that the entire program is either compiled
23460 using the dynamic model or static model, ensuring consistency. It
23461 is possible to mix the two models, but rules have to be followed
23462 if this mixing is done to ensure that elaboration checks are not
23463 omitted.
23465 The basic rule is that @emph{a unit compiled with the static model cannot
23466 be @code{with'ed} by a unit compiled with the dynamic model}. The
23467 reason for this is that in the static model, a unit assumes that
23468 its clients guarantee to use (the equivalent of) pragma
23469 @code{Elaborate_All} so that no elaboration checks are required
23470 in inner subprograms, and this assumption is violated if the
23471 client is compiled with dynamic checks.
23473 The precise rule is as follows. A unit that is compiled with dynamic
23474 checks can only @code{with} a unit that meets at least one of the
23475 following criteria:
23477 @itemize @bullet
23479 @item
23480 The @code{with'ed} unit is itself compiled with dynamic elaboration
23481 checks (that is with the @option{-gnatE} switch.
23483 @item
23484 The @code{with'ed} unit is an internal GNAT implementation unit from
23485 the System, Interfaces, Ada, or GNAT hierarchies.
23487 @item
23488 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
23490 @item
23491 The @code{with'ing} unit (that is the client) has an explicit pragma
23492 @code{Elaborate_All} for the @code{with'ed} unit.
23494 @end itemize
23496 @noindent
23497 If this rule is violated, that is if a unit with dynamic elaboration
23498 checks @code{with's} a unit that does not meet one of the above four
23499 criteria, then the binder (@code{gnatbind}) will issue a warning
23500 similar to that in the following example:
23502 @smallexample
23503 warning: "x.ads" has dynamic elaboration checks and with's
23504 warning:   "y.ads" which has static elaboration checks
23505 @end smallexample
23507 @noindent
23508 These warnings indicate that the rule has been violated, and that as a result
23509 elaboration checks may be missed in the resulting executable file.
23510 This warning may be suppressed using the @option{-ws} binder switch
23511 in the usual manner.
23513 One useful application of this mixing rule is in the case of a subsystem
23514 which does not itself @code{with} units from the remainder of the
23515 application. In this case, the entire subsystem can be compiled with
23516 dynamic checks to resolve a circularity in the subsystem, while
23517 allowing the main application that uses this subsystem to be compiled
23518 using the more reliable default static model.
23520 @node What to Do If the Default Elaboration Behavior Fails
23521 @section What to Do If the Default Elaboration Behavior Fails
23523 @noindent
23524 If the binder cannot find an acceptable order, it outputs detailed
23525 diagnostics. For example:
23526 @smallexample
23527 @group
23528 @iftex
23529 @leftskip=0cm
23530 @end iftex
23531 error: elaboration circularity detected
23532 info:   "proc (body)" must be elaborated before "pack (body)"
23533 info:     reason: Elaborate_All probably needed in unit "pack (body)"
23534 info:     recompile "pack (body)" with -gnatwl
23535 info:                             for full details
23536 info:       "proc (body)"
23537 info:         is needed by its spec:
23538 info:       "proc (spec)"
23539 info:         which is withed by:
23540 info:       "pack (body)"
23541 info:  "pack (body)" must be elaborated before "proc (body)"
23542 info:     reason: pragma Elaborate in unit "proc (body)"
23543 @end group
23545 @end smallexample
23547 @noindent
23548 In this case we have a cycle that the binder cannot break. On the one
23549 hand, there is an explicit pragma Elaborate in @code{proc} for
23550 @code{pack}. This means that the body of @code{pack} must be elaborated
23551 before the body of @code{proc}. On the other hand, there is elaboration
23552 code in @code{pack} that calls a subprogram in @code{proc}. This means
23553 that for maximum safety, there should really be a pragma
23554 Elaborate_All in @code{pack} for @code{proc} which would require that
23555 the body of @code{proc} be elaborated before the body of
23556 @code{pack}. Clearly both requirements cannot be satisfied.
23557 Faced with a circularity of this kind, you have three different options.
23559 @table @asis
23560 @item Fix the program
23561 The most desirable option from the point of view of long-term maintenance
23562 is to rearrange the program so that the elaboration problems are avoided.
23563 One useful technique is to place the elaboration code into separate
23564 child packages. Another is to move some of the initialization code to
23565 explicitly called subprograms, where the program controls the order
23566 of initialization explicitly. Although this is the most desirable option,
23567 it may be impractical and involve too much modification, especially in
23568 the case of complex legacy code.
23570 @item Perform dynamic checks
23571 If the compilations are done using the
23572 @option{-gnatE}
23573 (dynamic elaboration check) switch, then GNAT behaves in
23574 a quite different manner. Dynamic checks are generated for all calls
23575 that could possibly result in raising an exception. With this switch,
23576 the compiler does not generate implicit @code{Elaborate_All} pragmas.
23577 The behavior then is exactly as specified in the Ada 95 Reference Manual.
23578 The binder will generate an executable program that may or may not
23579 raise @code{Program_Error}, and then it is the programmer's job to ensure
23580 that it does not raise an exception. Note that it is important to
23581 compile all units with the switch, it cannot be used selectively.
23583 @item Suppress checks
23584 The drawback of dynamic checks is that they generate a
23585 significant overhead at run time, both in space and time. If you
23586 are absolutely sure that your program cannot raise any elaboration
23587 exceptions, and you still want to use the dynamic elaboration model,
23588 then you can use the configuration pragma
23589 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
23590 example this pragma could be placed in the @file{gnat.adc} file.
23592 @item Suppress checks selectively
23593 When you know that certain calls in elaboration code cannot possibly
23594 lead to an elaboration error, and the binder nevertheless generates warnings
23595 on those calls and inserts Elaborate_All pragmas that lead to elaboration
23596 circularities, it is possible to remove those warnings locally and obtain
23597 a program that will bind. Clearly this can be unsafe, and it is the
23598 responsibility of the programmer to make sure that the resulting program has
23599 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
23600 be used with different granularity to suppress warnings and break
23601 elaboration circularities:
23603 @itemize @bullet
23604 @item
23605 Place the pragma that names the called subprogram in the declarative part
23606 that contains the call.
23608 @item
23609 Place the pragma in the declarative part, without naming an entity. This
23610 disables warnings on all calls in the corresponding  declarative region.
23612 @item
23613 Place the pragma in the package spec that declares the called subprogram,
23614 and name the subprogram. This disables warnings on all elaboration calls to
23615 that subprogram.
23617 @item
23618 Place the pragma in the package spec that declares the called subprogram,
23619 without naming any entity. This disables warnings on all elaboration calls to
23620 all subprograms declared in this spec.
23622 @item Use Pragma Elaborate
23623 As previously described in section @xref{Treatment of Pragma Elaborate},
23624 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
23625 that no elaboration checks are required on calls to the designated unit.
23626 There may be cases in which the caller knows that no transitive calls
23627 can occur, so that a @code{pragma Elaborate} will be sufficient in a
23628 case where @code{pragma Elaborate_All} would cause a circularity.
23629 @end itemize
23631 @noindent
23632 These five cases are listed in order of decreasing safety, and therefore
23633 require increasing programmer care in their application. Consider the
23634 following program:
23636 @smallexample @c adanocomment
23637 package Pack1 is
23638   function F1 return Integer;
23639   X1 : Integer;
23640 end Pack1;
23642 package Pack2 is
23643   function F2 return Integer;
23644   function Pure (x : integer) return integer;
23645   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
23646   --  pragma Suppress (Elaboration_Check);              -- (4)
23647 end Pack2;
23649 with Pack2;
23650 package body Pack1 is
23651   function F1 return Integer is
23652   begin
23653     return 100;
23654   end F1;
23655   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
23656 begin
23657   declare
23658     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
23659     --  pragma Suppress(Elaboration_Check);             -- (2)
23660   begin
23661     X1 := Pack2.F2 + 1;                --  Elab. call (2)
23662   end;
23663 end Pack1;
23665 with Pack1;
23666 package body Pack2 is
23667   function F2 return Integer is
23668   begin
23669      return Pack1.F1;
23670   end F2;
23671   function Pure (x : integer) return integer is
23672   begin
23673      return x ** 3 - 3 * x;
23674   end;
23675 end Pack2;
23677 with Pack1, Ada.Text_IO;
23678 procedure Proc3 is
23679 begin
23680   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
23681 end Proc3;
23682 @end smallexample
23683 In the absence of any pragmas, an attempt to bind this program produces
23684 the following diagnostics:
23685 @smallexample
23686 @group
23687 @iftex
23688 @leftskip=.5cm
23689 @end iftex
23690 error: elaboration circularity detected
23691 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
23692 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
23693 info:       recompile "pack1 (body)" with -gnatwl for full details
23694 info:          "pack1 (body)"
23695 info:             must be elaborated along with its spec:
23696 info:          "pack1 (spec)"
23697 info:             which is withed by:
23698 info:          "pack2 (body)"
23699 info:             which must be elaborated along with its spec:
23700 info:          "pack2 (spec)"
23701 info:             which is withed by:
23702 info:          "pack1 (body)"
23703 @end group
23704 @end smallexample
23705 The sources of the circularity are the two calls to @code{Pack2.Pure} and
23706 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
23707 F2 is safe, even though F2 calls F1, because the call appears after the
23708 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
23709 remove the warning on the call. It is also possible to use pragma (2)
23710 because there are no other potentially unsafe calls in the block.
23712 @noindent
23713 The call to @code{Pure} is safe because this function does not depend on the
23714 state of @code{Pack2}. Therefore any call to this function is safe, and it
23715 is correct to place pragma (3) in the corresponding package spec.
23717 @noindent
23718 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
23719 warnings on all calls to functions declared therein. Note that this is not
23720 necessarily safe, and requires more detailed examination of the subprogram
23721 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
23722 be already elaborated.
23723 @end table
23725 @noindent
23726 It is hard to generalize on which of these four approaches should be
23727 taken. Obviously if it is possible to fix the program so that the default
23728 treatment works, this is preferable, but this may not always be practical.
23729 It is certainly simple enough to use
23730 @option{-gnatE}
23731 but the danger in this case is that, even if the GNAT binder
23732 finds a correct elaboration order, it may not always do so,
23733 and certainly a binder from another Ada compiler might not. A
23734 combination of testing and analysis (for which the warnings generated
23735 with the
23736 @option{-gnatwl}
23737 switch can be useful) must be used to ensure that the program is free
23738 of errors. One switch that is useful in this testing is the
23739 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
23740 switch for
23741 @code{gnatbind}.
23742 Normally the binder tries to find an order that has the best chance of
23743 of avoiding elaboration problems. With this switch, the binder
23744 plays a devil's advocate role, and tries to choose the order that
23745 has the best chance of failing. If your program works even with this
23746 switch, then it has a better chance of being error free, but this is still
23747 not a guarantee.
23749 For an example of this approach in action, consider the C-tests (executable
23750 tests) from the ACVC suite. If these are compiled and run with the default
23751 treatment, then all but one of them succeed without generating any error
23752 diagnostics from the binder. However, there is one test that fails, and
23753 this is not surprising, because the whole point of this test is to ensure
23754 that the compiler can handle cases where it is impossible to determine
23755 a correct order statically, and it checks that an exception is indeed
23756 raised at run time.
23758 This one test must be compiled and run using the
23759 @option{-gnatE}
23760 switch, and then it passes. Alternatively, the entire suite can
23761 be run using this switch. It is never wrong to run with the dynamic
23762 elaboration switch if your code is correct, and we assume that the
23763 C-tests are indeed correct (it is less efficient, but efficiency is
23764 not a factor in running the ACVC tests.)
23766 @node Elaboration for Access-to-Subprogram Values
23767 @section Elaboration for Access-to-Subprogram Values
23768 @cindex Access-to-subprogram
23770 @noindent
23771 The introduction of access-to-subprogram types in Ada 95 complicates
23772 the handling of elaboration. The trouble is that it becomes
23773 impossible to tell at compile time which procedure
23774 is being called. This means that it is not possible for the binder
23775 to analyze the elaboration requirements in this case.
23777 If at the point at which the access value is created
23778 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
23779 the body of the subprogram is
23780 known to have been elaborated, then the access value is safe, and its use
23781 does not require a check. This may be achieved by appropriate arrangement
23782 of the order of declarations if the subprogram is in the current unit,
23783 or, if the subprogram is in another unit, by using pragma
23784 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
23785 on the referenced unit.
23787 If the referenced body is not known to have been elaborated at the point
23788 the access value is created, then any use of the access value must do a
23789 dynamic check, and this dynamic check will fail and raise a
23790 @code{Program_Error} exception if the body has not been elaborated yet.
23791 GNAT will generate the necessary checks, and in addition, if the
23792 @option{-gnatwl}
23793 switch is set, will generate warnings that such checks are required.
23795 The use of dynamic dispatching for tagged types similarly generates
23796 a requirement for dynamic checks, and premature calls to any primitive
23797 operation of a tagged type before the body of the operation has been
23798 elaborated, will result in the raising of @code{Program_Error}.
23800 @node Summary of Procedures for Elaboration Control
23801 @section Summary of Procedures for Elaboration Control
23802 @cindex Elaboration control
23804 @noindent
23805 First, compile your program with the default options, using none of
23806 the special elaboration control switches. If the binder successfully
23807 binds your program, then you can be confident that, apart from issues
23808 raised by the use of access-to-subprogram types and dynamic dispatching,
23809 the program is free of elaboration errors. If it is important that the
23810 program be portable, then use the
23811 @option{-gnatwl}
23812 switch to generate warnings about missing @code{Elaborate_All}
23813 pragmas, and supply the missing pragmas.
23815 If the program fails to bind using the default static elaboration
23816 handling, then you can fix the program to eliminate the binder
23817 message, or recompile the entire program with the
23818 @option{-gnatE} switch to generate dynamic elaboration checks,
23819 and, if you are sure there really are no elaboration problems,
23820 use a global pragma @code{Suppress (Elaboration_Check)}.
23822 @node Other Elaboration Order Considerations
23823 @section Other Elaboration Order Considerations
23824 @noindent
23825 This section has been entirely concerned with the issue of finding a valid
23826 elaboration order, as defined by the Ada Reference Manual. In a case
23827 where several elaboration orders are valid, the task is to find one
23828 of the possible valid elaboration orders (and the static model in GNAT
23829 will ensure that this is achieved).
23831 The purpose of the elaboration rules in the Ada Reference Manual is to
23832 make sure that no entity is accessed before it has been elaborated. For
23833 a subprogram, this means that the spec and body must have been elaborated
23834 before the subprogram is called. For an object, this means that the object
23835 must have been elaborated before its value is read or written. A violation
23836 of either of these two requirements is an access before elaboration order,
23837 and this section has been all about avoiding such errors.
23839 In the case where more than one order of elaboration is possible, in the
23840 sense that access before elaboration errors are avoided, then any one of
23841 the orders is ``correct'' in the sense that it meets the requirements of
23842 the Ada Reference Manual, and no such error occurs.
23844 However, it may be the case for a given program, that there are
23845 constraints on the order of elaboration that come not from consideration
23846 of avoiding elaboration errors, but rather from extra-lingual logic
23847 requirements. Consider this example:
23849 @smallexample @c ada
23850 with Init_Constants;
23851 package Constants is
23852    X : Integer := 0;
23853    Y : Integer := 0;
23854 end Constants;
23856 package Init_Constants is
23857    procedure P; -- require a body
23858 end Init_Constants;
23860 with Constants;
23861 package body Init_Constants is
23862    procedure P is begin null; end;
23863 begin
23864    Constants.X := 3;
23865    Constants.Y := 4;
23866 end Init_Constants;
23868 with Constants;
23869 package Calc is
23870    Z : Integer := Constants.X + Constants.Y;
23871 end Calc;
23873 with Calc;
23874 with Text_IO; use Text_IO;
23875 procedure Main is
23876 begin
23877    Put_Line (Calc.Z'Img);
23878 end Main;
23879 @end smallexample
23881 @noindent
23882 In this example, there is more than one valid order of elaboration. For
23883 example both the following are correct orders:
23885 @smallexample
23886 Init_Constants spec
23887 Constants spec
23888 Calc spec
23889 Init_Constants body
23890 Main body
23892   and
23894 Init_Constants spec
23895 Init_Constants body
23896 Constants spec
23897 Calc spec
23898 Main body
23899 @end smallexample
23901 @noindent
23902 There is no language rule to prefer one or the other, both are correct
23903 from an order of elaboration point of view. But the programmatic effects
23904 of the two orders are very different. In the first, the elaboration routine
23905 of @code{Calc} initializes @code{Z} to zero, and then the main program
23906 runs with this value of zero. But in the second order, the elaboration
23907 routine of @code{Calc} runs after the body of Init_Constants has set
23908 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
23909 runs.
23911 One could perhaps by applying pretty clever non-artificial intelligence
23912 to the situation guess that it is more likely that the second order of
23913 elaboration is the one desired, but there is no formal linguistic reason
23914 to prefer one over the other. In fact in this particular case, GNAT will
23915 prefer the second order, because of the rule that bodies are elaborated
23916 as soon as possible, but it's just luck that this is what was wanted
23917 (if indeed the second order was preferred).
23919 If the program cares about the order of elaboration routines in a case like
23920 this, it is important to specify the order required. In this particular
23921 case, that could have been achieved by adding to the spec of Calc:
23923 @smallexample @c ada
23924 pragma Elaborate_All (Constants);
23925 @end smallexample
23927 @noindent
23928 which requires that the body (if any) and spec of @code{Constants},
23929 as well as the body and spec of any unit @code{with}'ed by
23930 @code{Constants} be elaborated before @code{Calc} is elaborated.
23932 Clearly no automatic method can always guess which alternative you require,
23933 and if you are working with legacy code that had constraints of this kind
23934 which were not properly specified by adding @code{Elaborate} or
23935 @code{Elaborate_All} pragmas, then indeed it is possible that two different
23936 compilers can choose different orders.
23938 The @code{gnatbind}
23939 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
23940 out problems. This switch causes bodies to be elaborated as late as possible
23941 instead of as early as possible. In the example above, it would have forced
23942 the choice of the first elaboration order. If you get different results
23943 when using this switch, and particularly if one set of results is right,
23944 and one is wrong as far as you are concerned, it shows that you have some
23945 missing @code{Elaborate} pragmas. For the example above, we have the
23946 following output:
23948 @smallexample
23949 gnatmake -f -q main
23950 main
23952 gnatmake -f -q main -bargs -p
23953 main
23955 @end smallexample
23957 @noindent
23958 It is of course quite unlikely that both these results are correct, so
23959 it is up to you in a case like this to investigate the source of the
23960 difference, by looking at the two elaboration orders that are chosen,
23961 and figuring out which is correct, and then adding the necessary
23962 @code{Elaborate_All} pragmas to ensure the desired order.
23965 @node Inline Assembler
23966 @appendix Inline Assembler
23968 @noindent
23969 If you need to write low-level software that interacts directly
23970 with the hardware, Ada provides two ways to incorporate assembly
23971 language code into your program.  First, you can import and invoke
23972 external routines written in assembly language, an Ada feature fully
23973 supported by GNAT.  However, for small sections of code it may be simpler
23974 or more efficient to include assembly language statements directly
23975 in your Ada source program, using the facilities of the implementation-defined
23976 package @code{System.Machine_Code}, which incorporates the gcc
23977 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
23978 including the following:
23980 @itemize @bullet
23981 @item No need to use non-Ada tools
23982 @item Consistent interface over different targets
23983 @item Automatic usage of the proper calling conventions
23984 @item Access to Ada constants and variables
23985 @item Definition of intrinsic routines
23986 @item Possibility of inlining a subprogram comprising assembler code
23987 @item Code optimizer can take Inline Assembler code into account
23988 @end itemize
23990 This chapter presents a series of examples to show you how to use
23991 the Inline Assembler.  Although it focuses on the Intel x86,
23992 the general approach applies also to other processors.
23993 It is assumed that you are familiar with Ada
23994 and with assembly language programming.
23996 @menu
23997 * Basic Assembler Syntax::
23998 * A Simple Example of Inline Assembler::
23999 * Output Variables in Inline Assembler::
24000 * Input Variables in Inline Assembler::
24001 * Inlining Inline Assembler Code::
24002 * Other Asm Functionality::
24003 * A Complete Example::
24004 @end menu
24006 @c ---------------------------------------------------------------------------
24007 @node Basic Assembler Syntax
24008 @section Basic Assembler Syntax
24010 @noindent
24011 The assembler used by GNAT and gcc is based not on the Intel assembly
24012 language, but rather on a language that descends from the AT&T Unix
24013 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
24014 The following table summarizes the main features of @emph{as} syntax
24015 and points out the differences from the Intel conventions.
24016 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
24017 pre-processor) documentation for further information.
24019 @table @asis
24020 @item Register names
24021 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
24023 Intel: No extra punctuation; for example @code{eax}
24025 @item Immediate operand
24026 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
24028 Intel: No extra punctuation; for example @code{4}
24030 @item Address
24031 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
24033 Intel: No extra punctuation; for example @code{loc}
24035 @item Memory contents
24036 gcc / @emph{as}: No extra punctuation; for example @code{loc}
24038 Intel: Square brackets; for example @code{[loc]}
24040 @item Register contents
24041 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
24043 Intel: Square brackets; for example @code{[eax]}
24045 @item Hexadecimal numbers
24046 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
24048 Intel: Trailing ``h''; for example @code{A0h}
24050 @item Operand size
24051 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
24052 a 16-bit word
24054 Intel: Implicit, deduced by assembler; for example @code{mov}
24056 @item Instruction repetition
24057 gcc / @emph{as}: Split into two lines; for example
24059 @code{rep}
24061 @code{stosl}
24063 Intel: Keep on one line; for example @code{rep stosl}
24065 @item Order of operands
24066 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
24068 Intel: Destination first; for example @code{mov eax, 4}
24069 @end table
24071 @c ---------------------------------------------------------------------------
24072 @node A Simple Example of Inline Assembler
24073 @section A Simple Example of Inline Assembler
24075 @noindent
24076 The following example will generate a single assembly language statement,
24077 @code{nop}, which does nothing.  Despite its lack of run-time effect,
24078 the example will be useful in illustrating the basics of
24079 the Inline Assembler facility.
24081 @smallexample @c ada
24082 @group
24083 with System.Machine_Code; use System.Machine_Code;
24084 procedure Nothing is
24085 begin
24086    Asm ("nop");
24087 end Nothing;
24088 @end group
24089 @end smallexample
24091 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
24092 here it takes one parameter, a @emph{template string} that must be a static
24093 expression and that will form the generated instruction.
24094 @code{Asm} may be regarded as a compile-time procedure that parses
24095 the template string and additional parameters (none here),
24096 from which it generates a sequence of assembly language instructions.
24098 The examples in this chapter will illustrate several of the forms
24099 for invoking @code{Asm}; a complete specification of the syntax
24100 is found in the @cite{GNAT Reference Manual}.
24102 Under the standard GNAT conventions, the @code{Nothing} procedure
24103 should be in a file named @file{nothing.adb}.
24104 You can build the executable in the usual way:
24105 @smallexample
24106 gnatmake nothing
24107 @end smallexample
24108 However, the interesting aspect of this example is not its run-time behavior
24109 but rather the generated assembly code.
24110 To see this output, invoke the compiler as follows:
24111 @smallexample
24112    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
24113 @end smallexample
24114 where the options are:
24116 @table @code
24117 @item -c
24118 compile only (no bind or link)
24119 @item -S
24120 generate assembler listing
24121 @item -fomit-frame-pointer
24122 do not set up separate stack frames
24123 @item -gnatp
24124 do not add runtime checks
24125 @end table
24127 This gives a human-readable assembler version of the code. The resulting
24128 file will have the same name as the Ada source file, but with a @code{.s}
24129 extension. In our example, the file @file{nothing.s} has the following
24130 contents:
24132 @smallexample
24133 @group
24134 .file "nothing.adb"
24135 gcc2_compiled.:
24136 ___gnu_compiled_ada:
24137 .text
24138    .align 4
24139 .globl __ada_nothing
24140 __ada_nothing:
24141 #APP
24142    nop
24143 #NO_APP
24144    jmp L1
24145    .align 2,0x90
24147    ret
24148 @end group
24149 @end smallexample
24151 The assembly code you included is clearly indicated by
24152 the compiler, between the @code{#APP} and @code{#NO_APP}
24153 delimiters. The character before the 'APP' and 'NOAPP'
24154 can differ on different targets. For example, GNU/Linux uses '#APP' while
24155 on NT you will see '/APP'.
24157 If you make a mistake in your assembler code (such as using the
24158 wrong size modifier, or using a wrong operand for the instruction) GNAT
24159 will report this error in a temporary file, which will be deleted when
24160 the compilation is finished.  Generating an assembler file will help
24161 in such cases, since you can assemble this file separately using the
24162 @emph{as} assembler that comes with gcc.
24164 Assembling the file using the command
24166 @smallexample
24167 as @file{nothing.s}
24168 @end smallexample
24169 @noindent
24170 will give you error messages whose lines correspond to the assembler
24171 input file, so you can easily find and correct any mistakes you made.
24172 If there are no errors, @emph{as} will generate an object file
24173 @file{nothing.out}.
24175 @c ---------------------------------------------------------------------------
24176 @node Output Variables in Inline Assembler
24177 @section Output Variables in Inline Assembler
24179 @noindent
24180 The examples in this section, showing how to access the processor flags,
24181 illustrate how to specify the destination operands for assembly language
24182 statements.
24184 @smallexample @c ada
24185 @group
24186 with Interfaces; use Interfaces;
24187 with Ada.Text_IO; use Ada.Text_IO;
24188 with System.Machine_Code; use System.Machine_Code;
24189 procedure Get_Flags is
24190    Flags : Unsigned_32;
24191    use ASCII;
24192 begin
24193    Asm ("pushfl"          & LF & HT & -- push flags on stack
24194         "popl %%eax"      & LF & HT & -- load eax with flags
24195         "movl %%eax, %0",             -- store flags in variable
24196         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24197    Put_Line ("Flags register:" & Flags'Img);
24198 end Get_Flags;
24199 @end group
24200 @end smallexample
24202 In order to have a nicely aligned assembly listing, we have separated
24203 multiple assembler statements in the Asm template string with linefeed
24204 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
24205 The resulting section of the assembly output file is:
24207 @smallexample
24208 @group
24209 #APP
24210    pushfl
24211    popl %eax
24212    movl %eax, -40(%ebp)
24213 #NO_APP
24214 @end group
24215 @end smallexample
24217 It would have been legal to write the Asm invocation as:
24219 @smallexample
24220 Asm ("pushfl popl %%eax movl %%eax, %0")
24221 @end smallexample
24223 but in the generated assembler file, this would come out as:
24225 @smallexample
24226 #APP
24227    pushfl popl %eax movl %eax, -40(%ebp)
24228 #NO_APP
24229 @end smallexample
24231 which is not so convenient for the human reader.
24233 We use Ada comments
24234 at the end of each line to explain what the assembler instructions
24235 actually do.  This is a useful convention.
24237 When writing Inline Assembler instructions, you need to precede each register
24238 and variable name with a percent sign.  Since the assembler already requires
24239 a percent sign at the beginning of a register name, you need two consecutive
24240 percent signs for such names in the Asm template string, thus @code{%%eax}.
24241 In the generated assembly code, one of the percent signs will be stripped off.
24243 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
24244 variables: operands you later define using @code{Input} or @code{Output}
24245 parameters to @code{Asm}.
24246 An output variable is illustrated in
24247 the third statement in the Asm template string:
24248 @smallexample
24249 movl %%eax, %0
24250 @end smallexample
24251 The intent is to store the contents of the eax register in a variable that can
24252 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
24253 necessarily work, since the compiler might optimize by using a register
24254 to hold Flags, and the expansion of the @code{movl} instruction would not be
24255 aware of this optimization.  The solution is not to store the result directly
24256 but rather to advise the compiler to choose the correct operand form;
24257 that is the purpose of the @code{%0} output variable.
24259 Information about the output variable is supplied in the @code{Outputs}
24260 parameter to @code{Asm}:
24261 @smallexample
24262 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24263 @end smallexample
24265 The output is defined by the @code{Asm_Output} attribute of the target type;
24266 the general format is
24267 @smallexample
24268 Type'Asm_Output (constraint_string, variable_name)
24269 @end smallexample
24271 The constraint string directs the compiler how
24272 to store/access the associated variable.  In the example
24273 @smallexample
24274 Unsigned_32'Asm_Output ("=m", Flags);
24275 @end smallexample
24276 the @code{"m"} (memory) constraint tells the compiler that the variable
24277 @code{Flags} should be stored in a memory variable, thus preventing
24278 the optimizer from keeping it in a register.  In contrast,
24279 @smallexample
24280 Unsigned_32'Asm_Output ("=r", Flags);
24281 @end smallexample
24282 uses the @code{"r"} (register) constraint, telling the compiler to
24283 store the variable in a register.
24285 If the constraint is preceded by the equal character (@strong{=}), it tells
24286 the compiler that the variable will be used to store data into it.
24288 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
24289 allowing the optimizer to choose whatever it deems best.
24291 There are a fairly large number of constraints, but the ones that are
24292 most useful (for the Intel x86 processor) are the following:
24294 @table @code
24295 @item =
24296 output constraint
24297 @item g
24298 global (i.e. can be stored anywhere)
24299 @item m
24300 in memory
24301 @item I
24302 a constant
24303 @item a
24304 use eax
24305 @item b
24306 use ebx
24307 @item c
24308 use ecx
24309 @item d
24310 use edx
24311 @item S
24312 use esi
24313 @item D
24314 use edi
24315 @item r
24316 use one of eax, ebx, ecx or edx
24317 @item q
24318 use one of eax, ebx, ecx, edx, esi or edi
24319 @end table
24321 The full set of constraints is described in the gcc and @emph{as}
24322 documentation; note that it is possible to combine certain constraints
24323 in one constraint string.
24325 You specify the association of an output variable with an assembler operand
24326 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
24327 integer.  Thus in
24328 @smallexample @c ada
24329 @group
24330 Asm ("pushfl"          & LF & HT & -- push flags on stack
24331      "popl %%eax"      & LF & HT & -- load eax with flags
24332      "movl %%eax, %0",             -- store flags in variable
24333      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24334 @end group
24335 @end smallexample
24336 @noindent
24337 @code{%0} will be replaced in the expanded code by the appropriate operand,
24338 whatever
24339 the compiler decided for the @code{Flags} variable.
24341 In general, you may have any number of output variables:
24342 @itemize @bullet
24343 @item
24344 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
24345 @item
24346 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
24347 of @code{Asm_Output} attributes
24348 @end itemize
24350 For example:
24351 @smallexample @c ada
24352 @group
24353 Asm ("movl %%eax, %0" & LF & HT &
24354      "movl %%ebx, %1" & LF & HT &
24355      "movl %%ecx, %2",
24356      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
24357                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
24358                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
24359 @end group
24360 @end smallexample
24361 @noindent
24362 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
24363 in the Ada program.
24365 As a variation on the @code{Get_Flags} example, we can use the constraints
24366 string to direct the compiler to store the eax register into the @code{Flags}
24367 variable, instead of including the store instruction explicitly in the
24368 @code{Asm} template string:
24370 @smallexample @c ada
24371 @group
24372 with Interfaces; use Interfaces;
24373 with Ada.Text_IO; use Ada.Text_IO;
24374 with System.Machine_Code; use System.Machine_Code;
24375 procedure Get_Flags_2 is
24376    Flags : Unsigned_32;
24377    use ASCII;
24378 begin
24379    Asm ("pushfl"      & LF & HT & -- push flags on stack
24380         "popl %%eax",             -- save flags in eax
24381         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
24382    Put_Line ("Flags register:" & Flags'Img);
24383 end Get_Flags_2;
24384 @end group
24385 @end smallexample
24387 @noindent
24388 The @code{"a"} constraint tells the compiler that the @code{Flags}
24389 variable will come from the eax register. Here is the resulting code:
24391 @smallexample
24392 @group
24393 #APP
24394    pushfl
24395    popl %eax
24396 #NO_APP
24397    movl %eax,-40(%ebp)
24398 @end group
24399 @end smallexample
24401 @noindent
24402 The compiler generated the store of eax into Flags after
24403 expanding the assembler code.
24405 Actually, there was no need to pop the flags into the eax register;
24406 more simply, we could just pop the flags directly into the program variable:
24408 @smallexample @c ada
24409 @group
24410 with Interfaces; use Interfaces;
24411 with Ada.Text_IO; use Ada.Text_IO;
24412 with System.Machine_Code; use System.Machine_Code;
24413 procedure Get_Flags_3 is
24414    Flags : Unsigned_32;
24415    use ASCII;
24416 begin
24417    Asm ("pushfl"  & LF & HT & -- push flags on stack
24418         "pop %0",             -- save flags in Flags
24419         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24420    Put_Line ("Flags register:" & Flags'Img);
24421 end Get_Flags_3;
24422 @end group
24423 @end smallexample
24425 @c ---------------------------------------------------------------------------
24426 @node Input Variables in Inline Assembler
24427 @section Input Variables in Inline Assembler
24429 @noindent
24430 The example in this section illustrates how to specify the source operands
24431 for assembly language statements.
24432 The program simply increments its input value by 1:
24434 @smallexample @c ada
24435 @group
24436 with Interfaces; use Interfaces;
24437 with Ada.Text_IO; use Ada.Text_IO;
24438 with System.Machine_Code; use System.Machine_Code;
24439 procedure Increment is
24441    function Incr (Value : Unsigned_32) return Unsigned_32 is
24442       Result : Unsigned_32;
24443    begin
24444       Asm ("incl %0",
24445            Inputs  => Unsigned_32'Asm_Input ("a", Value),
24446            Outputs => Unsigned_32'Asm_Output ("=a", Result));
24447       return Result;
24448    end Incr;
24450    Value : Unsigned_32;
24452 begin
24453    Value := 5;
24454    Put_Line ("Value before is" & Value'Img);
24455    Value := Incr (Value);
24456    Put_Line ("Value after is" & Value'Img);
24457 end Increment;
24458 @end group
24459 @end smallexample
24461 The @code{Outputs} parameter to @code{Asm} specifies
24462 that the result will be in the eax register and that it is to be stored
24463 in the @code{Result} variable.
24465 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
24466 but with an @code{Asm_Input} attribute.
24467 The @code{"="} constraint, indicating an output value, is not present.
24469 You can have multiple input variables, in the same way that you can have more
24470 than one output variable.
24472 The parameter count (%0, %1) etc, now starts at the first input
24473 statement, and continues with the output statements.
24474 When both parameters use the same variable, the
24475 compiler will treat them as the same %n operand, which is the case here.
24477 Just as the @code{Outputs} parameter causes the register to be stored into the
24478 target variable after execution of the assembler statements, so does the
24479 @code{Inputs} parameter cause its variable to be loaded into the register
24480 before execution of the assembler statements.
24482 Thus the effect of the @code{Asm} invocation is:
24483 @enumerate
24484 @item load the 32-bit value of @code{Value} into eax
24485 @item execute the @code{incl %eax} instruction
24486 @item store the contents of eax into the @code{Result} variable
24487 @end enumerate
24489 The resulting assembler file (with @option{-O2} optimization) contains:
24490 @smallexample
24491 @group
24492 _increment__incr.1:
24493    subl $4,%esp
24494    movl 8(%esp),%eax
24495 #APP
24496    incl %eax
24497 #NO_APP
24498    movl %eax,%edx
24499    movl %ecx,(%esp)
24500    addl $4,%esp
24501    ret
24502 @end group
24503 @end smallexample
24505 @c ---------------------------------------------------------------------------
24506 @node Inlining Inline Assembler Code
24507 @section Inlining Inline Assembler Code
24509 @noindent
24510 For a short subprogram such as the @code{Incr} function in the previous
24511 section, the overhead of the call and return (creating / deleting the stack
24512 frame) can be significant, compared to the amount of code in the subprogram
24513 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
24514 which directs the compiler to expand invocations of the subprogram at the
24515 point(s) of call, instead of setting up a stack frame for out-of-line calls.
24516 Here is the resulting program:
24518 @smallexample @c ada
24519 @group
24520 with Interfaces; use Interfaces;
24521 with Ada.Text_IO; use Ada.Text_IO;
24522 with System.Machine_Code; use System.Machine_Code;
24523 procedure Increment_2 is
24525    function Incr (Value : Unsigned_32) return Unsigned_32 is
24526       Result : Unsigned_32;
24527    begin
24528       Asm ("incl %0",
24529            Inputs  => Unsigned_32'Asm_Input ("a", Value),
24530            Outputs => Unsigned_32'Asm_Output ("=a", Result));
24531       return Result;
24532    end Incr;
24533    pragma Inline (Increment);
24535    Value : Unsigned_32;
24537 begin
24538    Value := 5;
24539    Put_Line ("Value before is" & Value'Img);
24540    Value := Increment (Value);
24541    Put_Line ("Value after is" & Value'Img);
24542 end Increment_2;
24543 @end group
24544 @end smallexample
24546 Compile the program with both optimization (@option{-O2}) and inlining
24547 enabled (@option{-gnatpn} instead of @option{-gnatp}).
24549 The @code{Incr} function is still compiled as usual, but at the
24550 point in @code{Increment} where our function used to be called:
24552 @smallexample
24553 @group
24554 pushl %edi
24555 call _increment__incr.1
24556 @end group
24557 @end smallexample
24559 @noindent
24560 the code for the function body directly appears:
24562 @smallexample
24563 @group
24564 movl %esi,%eax
24565 #APP
24566    incl %eax
24567 #NO_APP
24568    movl %eax,%edx
24569 @end group
24570 @end smallexample
24572 @noindent
24573 thus saving the overhead of stack frame setup and an out-of-line call.
24575 @c ---------------------------------------------------------------------------
24576 @node Other Asm Functionality
24577 @section Other @code{Asm} Functionality
24579 @noindent
24580 This section describes two important parameters to the @code{Asm}
24581 procedure: @code{Clobber}, which identifies register usage;
24582 and @code{Volatile}, which inhibits unwanted optimizations.
24584 @menu
24585 * The Clobber Parameter::
24586 * The Volatile Parameter::
24587 @end menu
24589 @c ---------------------------------------------------------------------------
24590 @node The Clobber Parameter
24591 @subsection The @code{Clobber} Parameter
24593 @noindent
24594 One of the dangers of intermixing assembly language and a compiled language
24595 such as Ada is that the compiler needs to be aware of which registers are
24596 being used by the assembly code.  In some cases, such as the earlier examples,
24597 the constraint string is sufficient to indicate register usage (e.g.,
24598 @code{"a"} for
24599 the eax register).  But more generally, the compiler needs an explicit
24600 identification of the registers that are used by the Inline Assembly
24601 statements.
24603 Using a register that the compiler doesn't know about
24604 could be a side effect of an instruction (like @code{mull}
24605 storing its result in both eax and edx).
24606 It can also arise from explicit register usage in your
24607 assembly code; for example:
24608 @smallexample
24609 @group
24610 Asm ("movl %0, %%ebx" & LF & HT &
24611      "movl %%ebx, %1",
24612      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
24613      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
24614 @end group
24615 @end smallexample
24616 @noindent
24617 where the compiler (since it does not analyze the @code{Asm} template string)
24618 does not know you are using the ebx register.
24620 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
24621 to identify the registers that will be used by your assembly code:
24623 @smallexample
24624 @group
24625 Asm ("movl %0, %%ebx" & LF & HT &
24626      "movl %%ebx, %1",
24627      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
24628      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
24629      Clobber => "ebx");
24630 @end group
24631 @end smallexample
24633 The Clobber parameter is a static string expression specifying the
24634 register(s) you are using.  Note that register names are @emph{not} prefixed
24635 by a percent sign. Also, if more than one register is used then their names
24636 are separated by commas; e.g., @code{"eax, ebx"}
24638 The @code{Clobber} parameter has several additional uses:
24639 @enumerate
24640 @item Use ``register'' name @code{cc} to indicate that flags might have changed
24641 @item Use ``register'' name @code{memory} if you changed a memory location
24642 @end enumerate
24644 @c ---------------------------------------------------------------------------
24645 @node The Volatile Parameter
24646 @subsection The @code{Volatile} Parameter
24647 @cindex Volatile parameter
24649 @noindent
24650 Compiler optimizations in the presence of Inline Assembler may sometimes have
24651 unwanted effects.  For example, when an @code{Asm} invocation with an input
24652 variable is inside a loop, the compiler might move the loading of the input
24653 variable outside the loop, regarding it as a one-time initialization.
24655 If this effect is not desired, you can disable such optimizations by setting
24656 the @code{Volatile} parameter to @code{True}; for example:
24658 @smallexample @c ada
24659 @group
24660 Asm ("movl %0, %%ebx" & LF & HT &
24661      "movl %%ebx, %1",
24662      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
24663      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
24664      Clobber  => "ebx",
24665      Volatile => True);
24666 @end group
24667 @end smallexample
24669 By default, @code{Volatile} is set to @code{False} unless there is no
24670 @code{Outputs} parameter.
24672 Although setting @code{Volatile} to @code{True} prevents unwanted
24673 optimizations, it will also disable other optimizations that might be
24674 important for efficiency. In general, you should set @code{Volatile}
24675 to @code{True} only if the compiler's optimizations have created
24676 problems.
24678 @c ---------------------------------------------------------------------------
24679 @node A Complete Example
24680 @section A Complete Example
24682 @noindent
24683 This section contains a complete program illustrating a realistic usage
24684 of GNAT's Inline Assembler capabilities.  It comprises a main procedure
24685 @code{Check_CPU} and a package @code{Intel_CPU}.
24686 The package declares a collection of functions that detect the properties
24687 of the 32-bit x86 processor that is running the program.
24688 The main procedure invokes these functions and displays the information.
24690 The Intel_CPU package could be enhanced by adding functions to
24691 detect the type of x386 co-processor, the processor caching options and
24692 special operations such as the SIMD extensions.
24694 Although the Intel_CPU package has been written for 32-bit Intel
24695 compatible CPUs, it is OS neutral. It has been tested on DOS,
24696 Windows/NT and GNU/Linux.
24698 @menu
24699 * Check_CPU Procedure::
24700 * Intel_CPU Package Specification::
24701 * Intel_CPU Package Body::
24702 @end menu
24704 @c ---------------------------------------------------------------------------
24705 @node Check_CPU Procedure
24706 @subsection @code{Check_CPU} Procedure
24707 @cindex Check_CPU procedure
24709 @smallexample @c adanocomment
24710 ---------------------------------------------------------------------
24711 --                                                                 --
24712 --  Uses the Intel_CPU package to identify the CPU the program is  --
24713 --  running on, and some of the features it supports.              --
24714 --                                                                 --
24715 ---------------------------------------------------------------------
24717 with Intel_CPU;                     --  Intel CPU detection functions
24718 with Ada.Text_IO;                   --  Standard text I/O
24719 with Ada.Command_Line;              --  To set the exit status
24721 procedure Check_CPU is
24723    Type_Found : Boolean := False;
24724    --  Flag to indicate that processor was identified
24726    Features   : Intel_CPU.Processor_Features;
24727    --  The processor features
24729    Signature  : Intel_CPU.Processor_Signature;
24730    --  The processor type signature
24732 begin
24734    -----------------------------------
24735    --  Display the program banner.  --
24736    -----------------------------------
24738    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
24739                          ": check Intel CPU version and features, v1.0");
24740    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
24741    Ada.Text_IO.New_Line;
24743    -----------------------------------------------------------------------
24744    --  We can safely start with the assumption that we are on at least  --
24745    --  a x386 processor. If the CPUID instruction is present, then we   --
24746    --  have a later processor type.                                     --
24747    -----------------------------------------------------------------------
24749    if Intel_CPU.Has_CPUID = False then
24751       --  No CPUID instruction, so we assume this is indeed a x386
24752       --  processor. We can still check if it has a FP co-processor.
24753       if Intel_CPU.Has_FPU then
24754          Ada.Text_IO.Put_Line
24755            ("x386-type processor with a FP co-processor");
24756       else
24757          Ada.Text_IO.Put_Line
24758            ("x386-type processor without a FP co-processor");
24759       end if;  --  check for FPU
24761       --  Program done
24762       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24763       return;
24765    end if;  --  check for CPUID
24767    -----------------------------------------------------------------------
24768    --  If CPUID is supported, check if this is a true Intel processor,  --
24769    --  if it is not, display a warning.                                 --
24770    -----------------------------------------------------------------------
24772    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
24773       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
24774       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
24775    end if;  --  check if Intel
24777    ----------------------------------------------------------------------
24778    --  With the CPUID instruction present, we can assume at least a    --
24779    --  x486 processor. If the CPUID support level is < 1 then we have  --
24780    --  to leave it at that.                                            --
24781    ----------------------------------------------------------------------
24783    if Intel_CPU.CPUID_Level < 1 then
24785       --  Ok, this is a x486 processor. we still can get the Vendor ID
24786       Ada.Text_IO.Put_Line ("x486-type processor");
24787       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
24789       --  We can also check if there is a FPU present
24790       if Intel_CPU.Has_FPU then
24791          Ada.Text_IO.Put_Line ("Floating-Point support");
24792       else
24793          Ada.Text_IO.Put_Line ("No Floating-Point support");
24794       end if;  --  check for FPU
24796       --  Program done
24797       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24798       return;
24800    end if;  --  check CPUID level
24802    ---------------------------------------------------------------------
24803    --  With a CPUID level of 1 we can use the processor signature to  --
24804    --  determine it's exact type.                                     --
24805    ---------------------------------------------------------------------
24807    Signature := Intel_CPU.Signature;
24809    ----------------------------------------------------------------------
24810    --  Ok, now we go into a lot of messy comparisons to get the        --
24811    --  processor type. For clarity, no attememt to try to optimize the --
24812    --  comparisons has been made. Note that since Intel_CPU does not   --
24813    --  support getting cache info, we cannot distinguish between P5    --
24814    --  and Celeron types yet.                                          --
24815    ----------------------------------------------------------------------
24817    --  x486SL
24818    if Signature.Processor_Type = 2#00#   and
24819      Signature.Family          = 2#0100# and
24820      Signature.Model           = 2#0100# then
24821       Type_Found := True;
24822       Ada.Text_IO.Put_Line ("x486SL processor");
24823    end if;
24825    --  x486DX2 Write-Back
24826    if Signature.Processor_Type = 2#00#   and
24827      Signature.Family          = 2#0100# and
24828      Signature.Model           = 2#0111# then
24829       Type_Found := True;
24830       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
24831    end if;
24833    --  x486DX4
24834    if Signature.Processor_Type = 2#00#   and
24835      Signature.Family          = 2#0100# and
24836      Signature.Model           = 2#1000# then
24837       Type_Found := True;
24838       Ada.Text_IO.Put_Line ("x486DX4 processor");
24839    end if;
24841    --  x486DX4 Overdrive
24842    if Signature.Processor_Type = 2#01#   and
24843      Signature.Family          = 2#0100# and
24844      Signature.Model           = 2#1000# then
24845       Type_Found := True;
24846       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
24847    end if;
24849    --  Pentium (60, 66)
24850    if Signature.Processor_Type = 2#00#   and
24851      Signature.Family          = 2#0101# and
24852      Signature.Model           = 2#0001# then
24853       Type_Found := True;
24854       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
24855    end if;
24857    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
24858    if Signature.Processor_Type = 2#00#   and
24859      Signature.Family          = 2#0101# and
24860      Signature.Model           = 2#0010# then
24861       Type_Found := True;
24862       Ada.Text_IO.Put_Line
24863         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
24864    end if;
24866    --  Pentium OverDrive (60, 66)
24867    if Signature.Processor_Type = 2#01#   and
24868      Signature.Family          = 2#0101# and
24869      Signature.Model           = 2#0001# then
24870       Type_Found := True;
24871       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
24872    end if;
24874    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
24875    if Signature.Processor_Type = 2#01#   and
24876      Signature.Family          = 2#0101# and
24877      Signature.Model           = 2#0010# then
24878       Type_Found := True;
24879       Ada.Text_IO.Put_Line
24880         ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
24881    end if;
24883    --  Pentium OverDrive processor for x486 processor-based systems
24884    if Signature.Processor_Type = 2#01#   and
24885      Signature.Family          = 2#0101# and
24886      Signature.Model           = 2#0011# then
24887       Type_Found := True;
24888       Ada.Text_IO.Put_Line
24889         ("Pentium OverDrive processor for x486 processor-based systems");
24890    end if;
24892    --  Pentium processor with MMX technology (166, 200)
24893    if Signature.Processor_Type = 2#00#   and
24894      Signature.Family          = 2#0101# and
24895      Signature.Model           = 2#0100# then
24896       Type_Found := True;
24897       Ada.Text_IO.Put_Line
24898         ("Pentium processor with MMX technology (166, 200)");
24899    end if;
24901    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
24902    if Signature.Processor_Type = 2#01#   and
24903      Signature.Family          = 2#0101# and
24904      Signature.Model           = 2#0100# then
24905       Type_Found := True;
24906       Ada.Text_IO.Put_Line
24907         ("Pentium OverDrive processor with MMX " &
24908          "technology for Pentium processor (75, 90, 100, 120, 133)");
24909    end if;
24911    --  Pentium Pro processor
24912    if Signature.Processor_Type = 2#00#   and
24913      Signature.Family          = 2#0110# and
24914      Signature.Model           = 2#0001# then
24915       Type_Found := True;
24916       Ada.Text_IO.Put_Line ("Pentium Pro processor");
24917    end if;
24919    --  Pentium II processor, model 3
24920    if Signature.Processor_Type = 2#00#   and
24921      Signature.Family          = 2#0110# and
24922      Signature.Model           = 2#0011# then
24923       Type_Found := True;
24924       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
24925    end if;
24927    --  Pentium II processor, model 5 or Celeron processor
24928    if Signature.Processor_Type = 2#00#   and
24929      Signature.Family          = 2#0110# and
24930      Signature.Model           = 2#0101# then
24931       Type_Found := True;
24932       Ada.Text_IO.Put_Line
24933         ("Pentium II processor, model 5 or Celeron processor");
24934    end if;
24936    --  Pentium Pro OverDrive processor
24937    if Signature.Processor_Type = 2#01#   and
24938      Signature.Family          = 2#0110# and
24939      Signature.Model           = 2#0011# then
24940       Type_Found := True;
24941       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
24942    end if;
24944    --  If no type recognized, we have an unknown. Display what
24945    --  we _do_ know
24946    if Type_Found = False then
24947       Ada.Text_IO.Put_Line ("Unknown processor");
24948    end if;
24950    -----------------------------------------
24951    --  Display processor stepping level.  --
24952    -----------------------------------------
24954    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
24956    ---------------------------------
24957    --  Display vendor ID string.  --
24958    ---------------------------------
24960    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
24962    ------------------------------------
24963    --  Get the processors features.  --
24964    ------------------------------------
24966    Features := Intel_CPU.Features;
24968    -----------------------------
24969    --  Check for a FPU unit.  --
24970    -----------------------------
24972    if Features.FPU = True then
24973       Ada.Text_IO.Put_Line ("Floating-Point unit available");
24974    else
24975       Ada.Text_IO.Put_Line ("no Floating-Point unit");
24976    end if;  --  check for FPU
24978    --------------------------------
24979    --  List processor features.  --
24980    --------------------------------
24982    Ada.Text_IO.Put_Line ("Supported features: ");
24984    --  Virtual Mode Extension
24985    if Features.VME = True then
24986       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
24987    end if;
24989    --  Debugging Extension
24990    if Features.DE = True then
24991       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
24992    end if;
24994    --  Page Size Extension
24995    if Features.PSE = True then
24996       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
24997    end if;
24999    --  Time Stamp Counter
25000    if Features.TSC = True then
25001       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
25002    end if;
25004    --  Model Specific Registers
25005    if Features.MSR = True then
25006       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
25007    end if;
25009    --  Physical Address Extension
25010    if Features.PAE = True then
25011       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
25012    end if;
25014    --  Machine Check Extension
25015    if Features.MCE = True then
25016       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
25017    end if;
25019    --  CMPXCHG8 instruction supported
25020    if Features.CX8 = True then
25021       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
25022    end if;
25024    --  on-chip APIC hardware support
25025    if Features.APIC = True then
25026       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
25027    end if;
25029    --  Fast System Call
25030    if Features.SEP = True then
25031       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
25032    end if;
25034    --  Memory Type Range Registers
25035    if Features.MTRR = True then
25036       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
25037    end if;
25039    --  Page Global Enable
25040    if Features.PGE = True then
25041       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
25042    end if;
25044    --  Machine Check Architecture
25045    if Features.MCA = True then
25046       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
25047    end if;
25049    --  Conditional Move Instruction Supported
25050    if Features.CMOV = True then
25051       Ada.Text_IO.Put_Line
25052         ("    CMOV   - Conditional Move Instruction Supported");
25053    end if;
25055    --  Page Attribute Table
25056    if Features.PAT = True then
25057       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
25058    end if;
25060    --  36-bit Page Size Extension
25061    if Features.PSE_36 = True then
25062       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
25063    end if;
25065    --  MMX technology supported
25066    if Features.MMX = True then
25067       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
25068    end if;
25070    --  Fast FP Save and Restore
25071    if Features.FXSR = True then
25072       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
25073    end if;
25075    ---------------------
25076    --  Program done.  --
25077    ---------------------
25079    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
25081 exception
25083    when others =>
25084       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
25085       raise;
25087 end Check_CPU;
25088 @end smallexample
25090 @c ---------------------------------------------------------------------------
25091 @node Intel_CPU Package Specification
25092 @subsection @code{Intel_CPU} Package Specification
25093 @cindex Intel_CPU package specification
25095 @smallexample @c adanocomment
25096 -------------------------------------------------------------------------
25097 --                                                                     --
25098 --  file: intel_cpu.ads                                                --
25099 --                                                                     --
25100 --           *********************************************             --
25101 --           * WARNING: for 32-bit Intel processors only *             --
25102 --           *********************************************             --
25103 --                                                                     --
25104 --  This package contains a number of subprograms that are useful in   --
25105 --  determining the Intel x86 CPU (and the features it supports) on    --
25106 --  which the program is running.                                      --
25107 --                                                                     --
25108 --  The package is based upon the information given in the Intel       --
25109 --  Application Note AP-485: "Intel Processor Identification and the   --
25110 --  CPUID Instruction" as of April 1998. This application note can be  --
25111 --  found on www.intel.com.                                            --
25112 --                                                                     --
25113 --  It currently deals with 32-bit processors only, will not detect    --
25114 --  features added after april 1998, and does not guarantee proper     --
25115 --  results on Intel-compatible processors.                            --
25116 --                                                                     --
25117 --  Cache info and x386 fpu type detection are not supported.          --
25118 --                                                                     --
25119 --  This package does not use any privileged instructions, so should   --
25120 --  work on any OS running on a 32-bit Intel processor.                --
25121 --                                                                     --
25122 -------------------------------------------------------------------------
25124 with Interfaces;             use Interfaces;
25125 --  for using unsigned types
25127 with System.Machine_Code;    use System.Machine_Code;
25128 --  for using inline assembler code
25130 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
25131 --  for inserting control characters
25133 package Intel_CPU is
25135    ----------------------
25136    --  Processor bits  --
25137    ----------------------
25139    subtype Num_Bits is Natural range 0 .. 31;
25140    --  the number of processor bits (32)
25142    --------------------------
25143    --  Processor register  --
25144    --------------------------
25146    --  define a processor register type for easy access to
25147    --  the individual bits
25149    type Processor_Register is array (Num_Bits) of Boolean;
25150    pragma Pack (Processor_Register);
25151    for Processor_Register'Size use 32;
25153    -------------------------
25154    --  Unsigned register  --
25155    -------------------------
25157    --  define a processor register type for easy access to
25158    --  the individual bytes
25160    type Unsigned_Register is
25161       record
25162          L1 : Unsigned_8;
25163          H1 : Unsigned_8;
25164          L2 : Unsigned_8;
25165          H2 : Unsigned_8;
25166       end record;
25168    for Unsigned_Register use
25169       record
25170          L1 at 0 range  0 ..  7;
25171          H1 at 0 range  8 .. 15;
25172          L2 at 0 range 16 .. 23;
25173          H2 at 0 range 24 .. 31;
25174       end record;
25176    for Unsigned_Register'Size use 32;
25178    ---------------------------------
25179    --  Intel processor vendor ID  --
25180    ---------------------------------
25182    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
25183    --  indicates an Intel manufactured processor
25185    ------------------------------------
25186    --  Processor signature register  --
25187    ------------------------------------
25189    --  a register type to hold the processor signature
25191    type Processor_Signature is
25192       record
25193          Stepping       : Natural range 0 .. 15;
25194          Model          : Natural range 0 .. 15;
25195          Family         : Natural range 0 .. 15;
25196          Processor_Type : Natural range 0 .. 3;
25197          Reserved       : Natural range 0 .. 262143;
25198       end record;
25200    for Processor_Signature use
25201       record
25202          Stepping       at 0 range  0 ..  3;
25203          Model          at 0 range  4 ..  7;
25204          Family         at 0 range  8 .. 11;
25205          Processor_Type at 0 range 12 .. 13;
25206          Reserved       at 0 range 14 .. 31;
25207       end record;
25209    for Processor_Signature'Size use 32;
25211    -----------------------------------
25212    --  Processor features register  --
25213    -----------------------------------
25215    --  a processor register to hold the processor feature flags
25217    type Processor_Features is
25218       record
25219          FPU    : Boolean;                --  floating point unit on chip
25220          VME    : Boolean;                --  virtual mode extension
25221          DE     : Boolean;                --  debugging extension
25222          PSE    : Boolean;                --  page size extension
25223          TSC    : Boolean;                --  time stamp counter
25224          MSR    : Boolean;                --  model specific registers
25225          PAE    : Boolean;                --  physical address extension
25226          MCE    : Boolean;                --  machine check extension
25227          CX8    : Boolean;                --  cmpxchg8 instruction
25228          APIC   : Boolean;                --  on-chip apic hardware
25229          Res_1  : Boolean;                --  reserved for extensions
25230          SEP    : Boolean;                --  fast system call
25231          MTRR   : Boolean;                --  memory type range registers
25232          PGE    : Boolean;                --  page global enable
25233          MCA    : Boolean;                --  machine check architecture
25234          CMOV   : Boolean;                --  conditional move supported
25235          PAT    : Boolean;                --  page attribute table
25236          PSE_36 : Boolean;                --  36-bit page size extension
25237          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
25238          MMX    : Boolean;                --  MMX technology supported
25239          FXSR   : Boolean;                --  fast FP save and restore
25240          Res_3  : Natural range 0 .. 127; --  reserved for extensions
25241       end record;
25243    for Processor_Features use
25244       record
25245          FPU    at 0 range  0 ..  0;
25246          VME    at 0 range  1 ..  1;
25247          DE     at 0 range  2 ..  2;
25248          PSE    at 0 range  3 ..  3;
25249          TSC    at 0 range  4 ..  4;
25250          MSR    at 0 range  5 ..  5;
25251          PAE    at 0 range  6 ..  6;
25252          MCE    at 0 range  7 ..  7;
25253          CX8    at 0 range  8 ..  8;
25254          APIC   at 0 range  9 ..  9;
25255          Res_1  at 0 range 10 .. 10;
25256          SEP    at 0 range 11 .. 11;
25257          MTRR   at 0 range 12 .. 12;
25258          PGE    at 0 range 13 .. 13;
25259          MCA    at 0 range 14 .. 14;
25260          CMOV   at 0 range 15 .. 15;
25261          PAT    at 0 range 16 .. 16;
25262          PSE_36 at 0 range 17 .. 17;
25263          Res_2  at 0 range 18 .. 22;
25264          MMX    at 0 range 23 .. 23;
25265          FXSR   at 0 range 24 .. 24;
25266          Res_3  at 0 range 25 .. 31;
25267       end record;
25269    for Processor_Features'Size use 32;
25271    -------------------
25272    --  Subprograms  --
25273    -------------------
25275    function Has_FPU return Boolean;
25276    --  return True if a FPU is found
25277    --  use only if CPUID is not supported
25279    function Has_CPUID return Boolean;
25280    --  return True if the processor supports the CPUID instruction
25282    function CPUID_Level return Natural;
25283    --  return the CPUID support level (0, 1 or 2)
25284    --  can only be called if the CPUID instruction is supported
25286    function Vendor_ID return String;
25287    --  return the processor vendor identification string
25288    --  can only be called if the CPUID instruction is supported
25290    function Signature return Processor_Signature;
25291    --  return the processor signature
25292    --  can only be called if the CPUID instruction is supported
25294    function Features return Processor_Features;
25295    --  return the processors features
25296    --  can only be called if the CPUID instruction is supported
25298 private
25300    ------------------------
25301    --  EFLAGS bit names  --
25302    ------------------------
25304    ID_Flag : constant Num_Bits := 21;
25305    --  ID flag bit
25307 end Intel_CPU;
25308 @end smallexample
25310 @c ---------------------------------------------------------------------------
25311 @node Intel_CPU Package Body
25312 @subsection @code{Intel_CPU} Package Body
25313 @cindex Intel_CPU package body
25315 @smallexample @c adanocomment
25316 package body Intel_CPU is
25318    ---------------------------
25319    --  Detect FPU presence  --
25320    ---------------------------
25322    --  There is a FPU present if we can set values to the FPU Status
25323    --  and Control Words.
25325    function Has_FPU return Boolean is
25327       Register : Unsigned_16;
25328       --  processor register to store a word
25330    begin
25332       --  check if we can change the status word
25333       Asm (
25335            --  the assembler code
25336            "finit"              & LF & HT &    --  reset status word
25337            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
25338            "fnstsw %0"          & LF & HT &    --  save status word
25339            "movw %%ax, %0",                    --  store status word
25341            --  output stored in Register
25342            --  register must be a memory location
25343            Outputs => Unsigned_16'Asm_output ("=m", Register),
25345            --  tell compiler that we used eax
25346            Clobber => "eax");
25348       --  if the status word is zero, there is no FPU
25349       if Register = 0 then
25350          return False;   --  no status word
25351       end if;  --  check status word value
25353       --  check if we can get the control word
25354       Asm (
25356            --  the assembler code
25357            "fnstcw %0",   --  save the control word
25359            --  output into Register
25360            --  register must be a memory location
25361            Outputs => Unsigned_16'Asm_output ("=m", Register));
25363       --  check the relevant bits
25364       if (Register and 16#103F#) /= 16#003F# then
25365          return False;   --  no control word
25366       end if;  --  check control word value
25368       --  FPU found
25369       return True;
25371    end Has_FPU;
25373    --------------------------------
25374    --  Detect CPUID instruction  --
25375    --------------------------------
25377    --  The processor supports the CPUID instruction if it is possible
25378    --  to change the value of ID flag bit in the EFLAGS register.
25380    function Has_CPUID return Boolean is
25382       Original_Flags, Modified_Flags : Processor_Register;
25383       --  EFLAG contents before and after changing the ID flag
25385    begin
25387       --  try flipping the ID flag in the EFLAGS register
25388       Asm (
25390            --  the assembler code
25391            "pushfl"               & LF & HT &     --  push EFLAGS on stack
25392            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
25393            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
25394            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
25395            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
25396            "popfl"                & LF & HT &     --  load EFLAGS register
25397            "pushfl"               & LF & HT &     --  push EFLAGS on stack
25398            "pop %1",                              --  save EFLAGS content
25400            --  output values, may be anything
25401            --  Original_Flags is %0
25402            --  Modified_Flags is %1
25403            Outputs =>
25404               (Processor_Register'Asm_output ("=g", Original_Flags),
25405                Processor_Register'Asm_output ("=g", Modified_Flags)),
25407            --  tell compiler eax is destroyed
25408            Clobber => "eax");
25410       --  check if CPUID is supported
25411       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
25412          return True;   --  ID flag was modified
25413       else
25414          return False;  --  ID flag unchanged
25415       end if;  --  check for CPUID
25417    end Has_CPUID;
25419    -------------------------------
25420    --  Get CPUID support level  --
25421    -------------------------------
25423    function CPUID_Level return Natural is
25425       Level : Unsigned_32;
25426       --  returned support level
25428    begin
25430       --  execute CPUID, storing the results in the Level register
25431       Asm (
25433            --  the assembler code
25434            "cpuid",    --  execute CPUID
25436            --  zero is stored in eax
25437            --  returning the support level in eax
25438            Inputs => Unsigned_32'Asm_input ("a", 0),
25440            --  eax is stored in Level
25441            Outputs => Unsigned_32'Asm_output ("=a", Level),
25443            --  tell compiler ebx, ecx and edx registers are destroyed
25444            Clobber => "ebx, ecx, edx");
25446       --  return the support level
25447       return Natural (Level);
25449    end CPUID_Level;
25451    --------------------------------
25452    --  Get CPU Vendor ID String  --
25453    --------------------------------
25455    --  The vendor ID string is returned in the ebx, ecx and edx register
25456    --  after executing the CPUID instruction with eax set to zero.
25457    --  In case of a true Intel processor the string returned is
25458    --  "GenuineIntel"
25460    function Vendor_ID return String is
25462       Ebx, Ecx, Edx : Unsigned_Register;
25463       --  registers containing the vendor ID string
25465       Vendor_ID : String (1 .. 12);
25466       -- the vendor ID string
25468    begin
25470       --  execute CPUID, storing the results in the processor registers
25471       Asm (
25473            --  the assembler code
25474            "cpuid",    --  execute CPUID
25476            --  zero stored in eax
25477            --  vendor ID string returned in ebx, ecx and edx
25478            Inputs => Unsigned_32'Asm_input ("a", 0),
25480            --  ebx is stored in Ebx
25481            --  ecx is stored in Ecx
25482            --  edx is stored in Edx
25483            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
25484                        Unsigned_Register'Asm_output ("=c", Ecx),
25485                        Unsigned_Register'Asm_output ("=d", Edx)));
25487       --  now build the vendor ID string
25488       Vendor_ID( 1) := Character'Val (Ebx.L1);
25489       Vendor_ID( 2) := Character'Val (Ebx.H1);
25490       Vendor_ID( 3) := Character'Val (Ebx.L2);
25491       Vendor_ID( 4) := Character'Val (Ebx.H2);
25492       Vendor_ID( 5) := Character'Val (Edx.L1);
25493       Vendor_ID( 6) := Character'Val (Edx.H1);
25494       Vendor_ID( 7) := Character'Val (Edx.L2);
25495       Vendor_ID( 8) := Character'Val (Edx.H2);
25496       Vendor_ID( 9) := Character'Val (Ecx.L1);
25497       Vendor_ID(10) := Character'Val (Ecx.H1);
25498       Vendor_ID(11) := Character'Val (Ecx.L2);
25499       Vendor_ID(12) := Character'Val (Ecx.H2);
25501       --  return string
25502       return Vendor_ID;
25504    end Vendor_ID;
25506    -------------------------------
25507    --  Get processor signature  --
25508    -------------------------------
25510    function Signature return Processor_Signature is
25512       Result : Processor_Signature;
25513       --  processor signature returned
25515    begin
25517       --  execute CPUID, storing the results in the Result variable
25518       Asm (
25520            --  the assembler code
25521            "cpuid",    --  execute CPUID
25523            --  one is stored in eax
25524            --  processor signature returned in eax
25525            Inputs => Unsigned_32'Asm_input ("a", 1),
25527            --  eax is stored in Result
25528            Outputs => Processor_Signature'Asm_output ("=a", Result),
25530            --  tell compiler that ebx, ecx and edx are also destroyed
25531            Clobber => "ebx, ecx, edx");
25533       --  return processor signature
25534       return Result;
25536    end Signature;
25538    ------------------------------
25539    --  Get processor features  --
25540    ------------------------------
25542    function Features return Processor_Features is
25544       Result : Processor_Features;
25545       --  processor features returned
25547    begin
25549       --  execute CPUID, storing the results in the Result variable
25550       Asm (
25552            --  the assembler code
25553            "cpuid",    --  execute CPUID
25555            --  one stored in eax
25556            --  processor features returned in edx
25557            Inputs => Unsigned_32'Asm_input ("a", 1),
25559            --  edx is stored in Result
25560            Outputs => Processor_Features'Asm_output ("=d", Result),
25562            --  tell compiler that ebx and ecx are also destroyed
25563            Clobber => "ebx, ecx");
25565       --  return processor signature
25566       return Result;
25568    end Features;
25570 end Intel_CPU;
25571 @end smallexample
25572 @c END OF INLINE ASSEMBLER CHAPTER
25573 @c ===============================
25577 @c ***********************************
25578 @c * Compatibility and Porting Guide *
25579 @c ***********************************
25580 @node Compatibility and Porting Guide
25581 @appendix Compatibility and Porting Guide
25583 @noindent
25584 This chapter describes the compatibility issues that may arise between
25585 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
25586 can expedite porting
25587 applications developed in other Ada environments.
25589 @menu
25590 * Compatibility with Ada 83::
25591 * Implementation-dependent characteristics::
25592 * Compatibility with DEC Ada 83::
25593 * Compatibility with Other Ada 95 Systems::
25594 * Representation Clauses::
25595 @end menu
25597 @node Compatibility with Ada 83
25598 @section Compatibility with Ada 83
25599 @cindex Compatibility (between Ada 83 and Ada 95)
25601 @noindent
25602 Ada 95 is designed to be highly upwards compatible with Ada 83.  In
25603 particular, the design intention is that the difficulties associated
25604 with moving from Ada 83 to Ada 95 should be no greater than those
25605 that occur when moving from one Ada 83 system to another.
25607 However, there are a number of points at which there are minor
25608 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25609 full details of these issues,
25610 and should be consulted for a complete treatment.
25611 In practice the
25612 following subsections treat the most likely issues to be encountered.
25614 @menu
25615 * Legal Ada 83 programs that are illegal in Ada 95::
25616 * More deterministic semantics::
25617 * Changed semantics::
25618 * Other language compatibility issues::
25619 @end menu
25621 @node Legal Ada 83 programs that are illegal in Ada 95
25622 @subsection Legal Ada 83 programs that are illegal in Ada 95
25624 @table @asis
25625 @item Character literals
25626 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25627 @code{Wide_Character} as a new predefined character type, some uses of
25628 character literals that were legal in Ada 83 are illegal in Ada 95.
25629 For example:
25630 @smallexample @c ada
25631    for Char in 'A' .. 'Z' loop ... end loop;
25632 @end smallexample
25633 @noindent
25634 The problem is that @code{'A'} and @code{'Z'} could be from either
25635 @code{Character} or @code{Wide_Character}.  The simplest correction
25636 is to make the type explicit; e.g.:
25637 @smallexample @c ada
25638    for Char in Character range 'A' .. 'Z' loop ... end loop;
25639 @end smallexample
25641 @item New reserved words
25642 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25643 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25644 Existing Ada 83 code using any of these identifiers must be edited to
25645 use some alternative name.
25647 @item Freezing rules
25648 The rules in Ada 95 are slightly different with regard to the point at
25649 which entities are frozen, and representation pragmas and clauses are
25650 not permitted past the freeze point.  This shows up most typically in
25651 the form of an error message complaining that a representation item
25652 appears too late, and the appropriate corrective action is to move
25653 the item nearer to the declaration of the entity to which it refers.
25655 A particular case is that representation pragmas
25656 @ifset vms
25657 (including the
25658 extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure})
25659 @end ifset
25660 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25661 declaration must be introduced to which the pragma can be applied.
25663 @item Optional bodies for library packages
25664 In Ada 83, a package that did not require a package body was nevertheless
25665 allowed to have one.  This lead to certain surprises in compiling large
25666 systems (situations in which the body could be unexpectedly ignored by the
25667 binder).  In Ada 95, if a package does not require a body then it is not
25668 permitted to have a body.  To fix this problem, simply remove a redundant
25669 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25670 into the spec that makes the body required.  One approach is to add a private
25671 part to the package declaration (if necessary), and define a parameterless
25672 procedure called @code{Requires_Body}, which must then be given a dummy
25673 procedure body in the package body, which then becomes required.
25674 Another approach (assuming that this does not introduce elaboration
25675 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25676 since one effect of this pragma is to require the presence of a package body.
25678 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25679 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25680 @code{Constraint_Error}.
25681 This means that it is illegal to have separate exception handlers for
25682 the two exceptions.  The fix is simply to remove the handler for the
25683 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25684 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25686 @item Indefinite subtypes in generics
25687 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25688 as the actual for a generic formal private type, but then the instantiation
25689 would be illegal if there were any instances of declarations of variables
25690 of this type in the generic body.  In Ada 95, to avoid this clear violation
25691 of the methodological principle known as the ``contract model'',
25692 the generic declaration explicitly indicates whether
25693 or not such instantiations are permitted.  If a generic formal parameter
25694 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25695 type name, then it can be instantiated with indefinite types, but no
25696 stand-alone variables can be declared of this type.  Any attempt to declare
25697 such a variable will result in an illegality at the time the generic is
25698 declared.  If the @code{(<>)} notation is not used, then it is illegal
25699 to instantiate the generic with an indefinite type.
25700 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25701 It will show up as a compile time error, and
25702 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25703 @end table
25705 @node More deterministic semantics
25706 @subsection More deterministic semantics
25708 @table @asis
25709 @item Conversions
25710 Conversions from real types to integer types round away from 0.  In Ada 83
25711 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
25712 implementation freedom was intended to support unbiased rounding in
25713 statistical applications, but in practice it interfered with portability.
25714 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25715 is required.  Numeric code may be affected by this change in semantics.
25716 Note, though, that this issue is no worse than already existed in Ada 83
25717 when porting code from one vendor to another.
25719 @item Tasking
25720 The Real-Time Annex introduces a set of policies that define the behavior of
25721 features that were implementation dependent in Ada 83, such as the order in
25722 which open select branches are executed.
25723 @end table
25725 @node Changed semantics
25726 @subsection Changed semantics
25728 @noindent
25729 The worst kind of incompatibility is one where a program that is legal in
25730 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25731 possible in Ada 83.  Fortunately this is extremely rare, but the one
25732 situation that you should be alert to is the change in the predefined type
25733 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25735 @table @asis
25736 @item range of @code{Character}
25737 The range of @code{Standard.Character} is now the full 256 characters
25738 of Latin-1, whereas in most Ada 83 implementations it was restricted
25739 to 128 characters. Although some of the effects of
25740 this change will be manifest in compile-time rejection of legal
25741 Ada 83 programs it is possible for a working Ada 83 program to have
25742 a different effect in Ada 95, one that was not permitted in Ada 83.
25743 As an example, the expression
25744 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25745 delivers @code{255} as its value.
25746 In general, you should look at the logic of any
25747 character-processing Ada 83 program and see whether it needs to be adapted
25748 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
25749 character handling package that may be relevant if code needs to be adapted
25750 to account for the additional Latin-1 elements.
25751 The desirable fix is to
25752 modify the program to accommodate the full character set, but in some cases
25753 it may be convenient to define a subtype or derived type of Character that
25754 covers only the restricted range.
25755 @cindex Latin-1
25756 @end table
25758 @node Other language compatibility issues
25759 @subsection Other language compatibility issues
25760 @table @asis
25761 @item @option{-gnat83 switch}
25762 All implementations of GNAT provide a switch that causes GNAT to operate
25763 in Ada 83 mode.  In this mode, some but not all compatibility problems
25764 of the type described above are handled automatically.  For example, the
25765 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
25766 However,
25767 in practice, it is usually advisable to make the necessary modifications
25768 to the program to remove the need for using this switch.
25769 See @ref{Compiling Ada 83 Programs}.
25771 @item Support for removed Ada 83 pragmas and attributes
25772 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
25773 generally because they have been replaced by other mechanisms.  Ada 95
25774 compilers are allowed, but not required, to implement these missing
25775 elements.  In contrast with some other Ada 95 compilers, GNAT implements all
25776 such pragmas and attributes, eliminating this compatibility concern.  These
25777 include @code{pragma Interface} and the floating point type attributes
25778 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25779 @end table
25782 @node Implementation-dependent characteristics
25783 @section Implementation-dependent characteristics
25784 @noindent
25785 Although the Ada language defines the semantics of each construct as
25786 precisely as practical, in some situations (for example for reasons of
25787 efficiency, or where the effect is heavily dependent on the host or target
25788 platform) the implementation is allowed some freedom.  In porting Ada 83
25789 code to GNAT, you need to be aware of whether / how the existing code
25790 exercised such implementation dependencies.  Such characteristics fall into
25791 several categories, and GNAT offers specific support in assisting the
25792 transition from certain Ada 83 compilers.
25794 @menu
25795 * Implementation-defined pragmas::
25796 * Implementation-defined attributes::
25797 * Libraries::
25798 * Elaboration order::
25799 * Target-specific aspects::
25800 @end menu
25803 @node Implementation-defined pragmas
25804 @subsection Implementation-defined pragmas
25806 @noindent
25807 Ada compilers are allowed to supplement the language-defined pragmas, and
25808 these are a potential source of non-portability.  All GNAT-defined pragmas
25809 are described in the GNAT Reference Manual, and these include several that
25810 are specifically intended to correspond to other vendors' Ada 83 pragmas.
25811 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25813 compatibility with DEC Ada 83, GNAT supplies the pragmas
25814 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25815 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25816 and @code{Volatile}.
25817 Other relevant pragmas include @code{External} and @code{Link_With}.
25818 Some vendor-specific
25819 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25820 recognized, thus
25821 avoiding compiler rejection of units that contain such pragmas; they are not
25822 relevant in a GNAT context and hence are not otherwise implemented.
25824 @node Implementation-defined attributes
25825 @subsection Implementation-defined attributes
25827 Analogous to pragmas, the set of attributes may be extended by an
25828 implementation.  All GNAT-defined attributes are described in the
25829 @cite{GNAT Reference Manual}, and these include several that are specifically
25830 intended
25831 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
25832 the attribute @code{VADS_Size} may be useful.  For compatibility with DEC
25833 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25834 @code{Type_Class}.
25836 @node Libraries
25837 @subsection Libraries
25838 @noindent
25839 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
25840 code uses vendor-specific libraries then there are several ways to manage
25841 this in Ada 95:
25842 @enumerate
25843 @item
25844 If the source code for the libraries (specifications and bodies) are
25845 available, then the libraries can be migrated in the same way as the
25846 application.
25847 @item
25848 If the source code for the specifications but not the bodies are
25849 available, then you can reimplement the bodies.
25850 @item
25851 Some new Ada 95 features obviate the need for library support.  For
25852 example most Ada 83 vendors supplied a package for unsigned integers.  The
25853 Ada 95 modular type feature is the preferred way to handle this need, so
25854 instead of migrating or reimplementing the unsigned integer package it may
25855 be preferable to retrofit the application using modular types.
25856 @end enumerate
25858 @node Elaboration order
25859 @subsection Elaboration order
25860 @noindent
25861 The implementation can choose any elaboration order consistent with the unit
25862 dependency relationship.  This freedom means that some orders can result in
25863 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25864 to invoke a subprogram its body has been elaborated, or to instantiate a
25865 generic before the generic body has been elaborated.  By default GNAT
25866 attempts to choose a safe order (one that will not encounter access before
25867 elaboration problems) by implicitly inserting Elaborate_All pragmas where
25868 needed.  However, this can lead to the creation of elaboration circularities
25869 and a resulting rejection of the program by gnatbind.  This issue is
25870 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25871 In brief, there are several
25872 ways to deal with this situation:
25874 @itemize @bullet
25875 @item
25876 Modify the program to eliminate the circularities, e.g. by moving
25877 elaboration-time code into explicitly-invoked procedures
25878 @item
25879 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25880 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25881 @code{Elaborate_All}
25882 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25883 (by selectively suppressing elaboration checks via pragma
25884 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25885 @end itemize
25887 @node Target-specific aspects
25888 @subsection Target-specific aspects
25889 @noindent
25890 Low-level applications need to deal with machine addresses, data
25891 representations, interfacing with assembler code, and similar issues.  If
25892 such an Ada 83 application is being ported to different target hardware (for
25893 example where the byte endianness has changed) then you will need to
25894 carefully examine the program logic; the porting effort will heavily depend
25895 on the robustness of the original design.  Moreover, Ada 95 is sometimes
25896 incompatible with typical Ada 83 compiler practices regarding implicit
25897 packing, the meaning of the Size attribute, and the size of access values.
25898 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25901 @node Compatibility with Other Ada 95 Systems
25902 @section Compatibility with Other Ada 95 Systems
25904 @noindent
25905 Providing that programs avoid the use of implementation dependent and
25906 implementation defined features of Ada 95, as documented in the Ada 95
25907 reference manual, there should be a high degree of portability between
25908 GNAT and other Ada 95 systems.  The following are specific items which
25909 have proved troublesome in moving GNAT programs to other Ada 95
25910 compilers, but do not affect porting code to GNAT@.
25912 @table @asis
25913 @item Ada 83 Pragmas and Attributes
25914 Ada 95 compilers are allowed, but not required, to implement the missing
25915 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25916 GNAT implements all such pragmas and attributes, eliminating this as
25917 a compatibility concern, but some other Ada 95 compilers reject these
25918 pragmas and attributes.
25920 @item Special-needs Annexes
25921 GNAT implements the full set of special needs annexes.  At the
25922 current time, it is the only Ada 95 compiler to do so.  This means that
25923 programs making use of these features may not be portable to other Ada
25924 95 compilation systems.
25926 @item Representation Clauses
25927 Some other Ada 95 compilers implement only the minimal set of
25928 representation clauses required by the Ada 95 reference manual.  GNAT goes
25929 far beyond this minimal set, as described in the next section.
25930 @end table
25932 @node Representation Clauses
25933 @section Representation Clauses
25935 @noindent
25936 The Ada 83 reference manual was quite vague in describing both the minimal
25937 required implementation of representation clauses, and also their precise
25938 effects.  The Ada 95 reference manual is much more explicit, but the minimal
25939 set of capabilities required in Ada 95 is quite limited.
25941 GNAT implements the full required set of capabilities described in the
25942 Ada 95 reference manual, but also goes much beyond this, and in particular
25943 an effort has been made to be compatible with existing Ada 83 usage to the
25944 greatest extent possible.
25946 A few cases exist in which Ada 83 compiler behavior is incompatible with
25947 requirements in the Ada 95 reference manual.  These are instances of
25948 intentional or accidental dependence on specific implementation dependent
25949 characteristics of these Ada 83 compilers.  The following is a list of
25950 the cases most likely to arise in existing legacy Ada 83 code.
25952 @table @asis
25953 @item Implicit Packing
25954 Some Ada 83 compilers allowed a Size specification to cause implicit
25955 packing of an array or record.  This could cause expensive implicit
25956 conversions for change of representation in the presence of derived
25957 types, and the Ada design intends to avoid this possibility.
25958 Subsequent AI's were issued to make it clear that such implicit
25959 change of representation in response to a Size clause is inadvisable,
25960 and this recommendation is represented explicitly in the Ada 95 RM
25961 as implementation advice that is followed by GNAT@.
25962 The problem will show up as an error
25963 message rejecting the size clause.  The fix is simply to provide
25964 the explicit pragma @code{Pack}, or for more fine tuned control, provide
25965 a Component_Size clause.
25967 @item Meaning of Size Attribute
25968 The Size attribute in Ada 95 for discrete types is defined as being the
25969 minimal number of bits required to hold values of the type.  For example,
25970 on a 32-bit machine, the size of Natural will typically be 31 and not
25971 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
25972 some 32 in this situation.  This problem will usually show up as a compile
25973 time error, but not always.  It is a good idea to check all uses of the
25974 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
25975 Object_Size can provide a useful way of duplicating the behavior of
25976 some Ada 83 compiler systems.
25978 @item Size of Access Types
25979 A common assumption in Ada 83 code is that an access type is in fact a pointer,
25980 and that therefore it will be the same size as a System.Address value.  This
25981 assumption is true for GNAT in most cases with one exception.  For the case of
25982 a pointer to an unconstrained array type (where the bounds may vary from one
25983 value of the access type to another), the default is to use a ``fat pointer'',
25984 which is represented as two separate pointers, one to the bounds, and one to
25985 the array.  This representation has a number of advantages, including improved
25986 efficiency.  However, it may cause some difficulties in porting existing Ada 83
25987 code which makes the assumption that, for example, pointers fit in 32 bits on
25988 a machine with 32-bit addressing.
25990 To get around this problem, GNAT also permits the use of ``thin pointers'' for
25991 access types in this case (where the designated type is an unconstrained array
25992 type).  These thin pointers are indeed the same size as a System.Address value.
25993 To specify a thin pointer, use a size clause for the type, for example:
25995 @smallexample @c ada
25996 type X is access all String;
25997 for X'Size use Standard'Address_Size;
25998 @end smallexample
26000 @noindent
26001 which will cause the type X to be represented using a single pointer.
26002 When using this representation, the bounds are right behind the array.
26003 This representation is slightly less efficient, and does not allow quite
26004 such flexibility in the use of foreign pointers or in using the
26005 Unrestricted_Access attribute to create pointers to non-aliased objects.
26006 But for any standard portable use of the access type it will work in
26007 a functionally correct manner and allow porting of existing code.
26008 Note that another way of forcing a thin pointer representation
26009 is to use a component size clause for the element size in an array,
26010 or a record representation clause for an access field in a record.
26011 @end table
26013 @node Compatibility with DEC Ada 83
26014 @section Compatibility with DEC Ada 83
26016 @noindent
26017 The VMS version of GNAT fully implements all the pragmas and attributes
26018 provided by DEC Ada 83, as well as providing the standard DEC Ada 83
26019 libraries, including Starlet.  In addition, data layouts and parameter
26020 passing conventions are highly compatible.  This means that porting
26021 existing DEC Ada 83 code to GNAT in VMS systems should be easier than
26022 most other porting efforts.  The following are some of the most
26023 significant differences between GNAT and DEC Ada 83.
26025 @table @asis
26026 @item Default floating-point representation
26027 In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83,
26028 it is VMS format.  GNAT does implement the necessary pragmas
26029 (Long_Float, Float_Representation) for changing this default.
26031 @item System
26032 The package System in GNAT exactly corresponds to the definition in the
26033 Ada 95 reference manual, which means that it excludes many of the
26034 DEC Ada 83 extensions.  However, a separate package Aux_DEC is provided
26035 that contains the additional definitions, and a special pragma,
26036 Extend_System allows this package to be treated transparently as an
26037 extension of package System.
26039 @item To_Address
26040 The definitions provided by Aux_DEC are exactly compatible with those
26041 in the DEC Ada 83 version of System, with one exception.
26042 DEC Ada provides the following declarations:
26044 @smallexample @c ada
26045 TO_ADDRESS (INTEGER)
26046 TO_ADDRESS (UNSIGNED_LONGWORD)
26047 TO_ADDRESS (universal_integer)
26048 @end smallexample
26050 @noindent
26051 The version of TO_ADDRESS taking a universal integer argument is in fact
26052 an extension to Ada 83 not strictly compatible with the reference manual.
26053 In GNAT, we are constrained to be exactly compatible with the standard,
26054 and this means we cannot provide this capability.  In DEC Ada 83, the
26055 point of this definition is to deal with a call like:
26057 @smallexample @c ada
26058 TO_ADDRESS (16#12777#);
26059 @end smallexample
26061 @noindent
26062 Normally, according to the Ada 83 standard, one would expect this to be
26063 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26064 of TO_ADDRESS@.  However, in DEC Ada 83, there is no ambiguity, since the
26065 definition using universal_integer takes precedence.
26067 In GNAT, since the version with universal_integer cannot be supplied, it is
26068 not possible to be 100% compatible.  Since there are many programs using
26069 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26070 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26071 declarations provided in the GNAT version of AUX_Dec are:
26073 @smallexample @c ada
26074 function To_Address (X : Integer) return Address;
26075 pragma Pure_Function (To_Address);
26077 function To_Address_Long (X : Unsigned_Longword)
26078  return Address;
26079 pragma Pure_Function (To_Address_Long);
26080 @end smallexample
26082 @noindent
26083 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26084 change the name to TO_ADDRESS_LONG@.
26086 @item Task_Id values
26087 The Task_Id values assigned will be different in the two systems, and GNAT
26088 does not provide a specified value for the Task_Id of the environment task,
26089 which in GNAT is treated like any other declared task.
26090 @end table
26092 For full details on these and other less significant compatibility issues,
26093 see appendix E of the Digital publication entitled @cite{DEC Ada, Technical
26094 Overview and Comparison on DIGITAL Platforms}.
26096 For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and
26097 attributes are recognized, although only a subset of them can sensibly
26098 be implemented.  The description of pragmas in this reference manual
26099 indicates whether or not they are applicable to non-VMS systems.
26103 @ifset unw
26104 @node Microsoft Windows Topics
26105 @appendix Microsoft Windows Topics
26106 @cindex Windows NT
26107 @cindex Windows 95
26108 @cindex Windows 98
26110 @noindent
26111 This chapter describes topics that are specific to the Microsoft Windows
26112 platforms (NT, 2000, and XP Professional).
26114 @menu
26115 * Using GNAT on Windows::
26116 * Using a network installation of GNAT::
26117 * CONSOLE and WINDOWS subsystems::
26118 * Temporary Files::
26119 * Mixed-Language Programming on Windows::
26120 * Windows Calling Conventions::
26121 * Introduction to Dynamic Link Libraries (DLLs)::
26122 * Using DLLs with GNAT::
26123 * Building DLLs with GNAT::
26124 * Building DLLs with GNAT Project files::
26125 * Building DLLs with gnatdll::
26126 * GNAT and Windows Resources::
26127 * Debugging a DLL::
26128 * GNAT and COM/DCOM Objects::
26129 @end menu
26131 @node Using GNAT on Windows
26132 @section Using GNAT on Windows
26134 @noindent
26135 One of the strengths of the GNAT technology is that its tool set
26136 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
26137 @code{gdb} debugger, etc.) is used in the same way regardless of the
26138 platform.
26140 On Windows this tool set is complemented by a number of Microsoft-specific
26141 tools that have been provided to facilitate interoperability with Windows
26142 when this is required. With these tools:
26144 @itemize @bullet
26146 @item
26147 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26148 subsystems.
26150 @item
26151 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26152 relocatable and non-relocatable DLLs are supported).
26154 @item
26155 You can build Ada DLLs for use in other applications. These applications
26156 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26157 relocatable and non-relocatable Ada DLLs are supported.
26159 @item
26160 You can include Windows resources in your Ada application.
26162 @item
26163 You can use or create COM/DCOM objects.
26164 @end itemize
26166 @noindent
26167 Immediately below are listed all known general GNAT-for-Windows restrictions.
26168 Other restrictions about specific features like Windows Resources and DLLs
26169 are listed in separate sections below.
26171 @itemize @bullet
26173 @item
26174 It is not possible to use @code{GetLastError} and @code{SetLastError}
26175 when tasking, protected records, or exceptions are used. In these
26176 cases, in order to implement Ada semantics, the GNAT run-time system
26177 calls certain Win32 routines that set the last error variable to 0 upon
26178 success. It should be possible to use @code{GetLastError} and
26179 @code{SetLastError} when tasking, protected record, and exception
26180 features are not used, but it is not guaranteed to work.
26182 @item
26183 It is not possible to link against Microsoft libraries except for
26184 import libraries. The library must be built to be compatible with
26185 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
26186 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
26187 not be compatible with the GNAT runtime. Even if the library is
26188 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
26190 @item
26191 When the compilation environment is located on FAT32 drives, users may
26192 experience recompilations of the source files that have not changed if
26193 Daylight Saving Time (DST) state has changed since the last time files
26194 were compiled. NTFS drives do not have this problem.
26196 @item
26197 No components of the GNAT toolset use any entries in the Windows
26198 registry. The only entries that can be created are file associations and
26199 PATH settings, provided the user has chosen to create them at installation
26200 time, as well as some minimal book-keeping information needed to correctly
26201 uninstall or integrate different GNAT products.
26202 @end itemize
26204 @node Using a network installation of GNAT
26205 @section Using a network installation of GNAT
26207 @noindent
26208 Make sure the system on which GNAT is installed is accessible from the
26209 current machine, i.e. the install location is shared over the network.
26210 Shared resources are accessed on Windows by means of UNC paths, which
26211 have the format @code{\\server\sharename\path}
26213 In order to use such a network installation, simply add the UNC path of the
26214 @file{bin} directory of your GNAT installation in front of your PATH. For
26215 example, if GNAT is installed in @file{\GNAT} directory of a share location
26216 called @file{c-drive} on a machine @file{LOKI}, the following command will
26217 make it available:
26219 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26221 Be aware that every compilation using the network installation results in the
26222 transfer of large amounts of data across the network and will likely cause
26223 serious performance penalty.
26225 @node CONSOLE and WINDOWS subsystems
26226 @section CONSOLE and WINDOWS subsystems
26227 @cindex CONSOLE Subsystem
26228 @cindex WINDOWS Subsystem
26229 @cindex -mwindows
26231 @noindent
26232 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26233 (which is the default subsystem) will always create a console when
26234 launching the application. This is not something desirable when the
26235 application has a Windows GUI. To get rid of this console the
26236 application must be using the @code{WINDOWS} subsystem. To do so
26237 the @option{-mwindows} linker option must be specified.
26239 @smallexample
26240 $ gnatmake winprog -largs -mwindows
26241 @end smallexample
26243 @node Temporary Files
26244 @section Temporary Files
26245 @cindex Temporary files
26247 @noindent
26248 It is possible to control where temporary files gets created by setting
26249 the TMP environment variable. The file will be created:
26251 @itemize
26252 @item Under the directory pointed to by the TMP environment variable if
26253 this directory exists.
26255 @item Under c:\temp, if the TMP environment variable is not set (or not
26256 pointing to a directory) and if this directory exists.
26258 @item Under the current working directory otherwise.
26259 @end itemize
26261 @noindent
26262 This allows you to determine exactly where the temporary
26263 file will be created. This is particularly useful in networked
26264 environments where you may not have write access to some
26265 directories.
26267 @node Mixed-Language Programming on Windows
26268 @section Mixed-Language Programming on Windows
26270 @noindent
26271 Developing pure Ada applications on Windows is no different than on
26272 other GNAT-supported platforms. However, when developing or porting an
26273 application that contains a mix of Ada and C/C++, the choice of your
26274 Windows C/C++ development environment conditions your overall
26275 interoperability strategy.
26277 If you use @code{gcc} to compile the non-Ada part of your application,
26278 there are no Windows-specific restrictions that affect the overall
26279 interoperability with your Ada code. If you plan to use
26280 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
26281 the following limitations:
26283 @itemize @bullet
26284 @item
26285 You cannot link your Ada code with an object or library generated with
26286 Microsoft tools if these use the @code{.tls} section (Thread Local
26287 Storage section) since the GNAT linker does not yet support this section.
26289 @item
26290 You cannot link your Ada code with an object or library generated with
26291 Microsoft tools if these use I/O routines other than those provided in
26292 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
26293 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
26294 libraries can cause a conflict with @code{msvcrt.dll} services. For
26295 instance Visual C++ I/O stream routines conflict with those in
26296 @code{msvcrt.dll}.
26297 @end itemize
26299 @noindent
26300 If you do want to use the Microsoft tools for your non-Ada code and hit one
26301 of the above limitations, you have two choices:
26303 @enumerate
26304 @item
26305 Encapsulate your non Ada code in a DLL to be linked with your Ada
26306 application. In this case, use the Microsoft or whatever environment to
26307 build the DLL and use GNAT to build your executable
26308 (@pxref{Using DLLs with GNAT}).
26310 @item
26311 Or you can encapsulate your Ada code in a DLL to be linked with the
26312 other part of your application. In this case, use GNAT to build the DLL
26313 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
26314 environment to build your executable.
26315 @end enumerate
26317 @node Windows Calling Conventions
26318 @section Windows Calling Conventions
26319 @findex Stdcall
26320 @findex APIENTRY
26322 @menu
26323 * C Calling Convention::
26324 * Stdcall Calling Convention::
26325 * DLL Calling Convention::
26326 @end menu
26328 @noindent
26329 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26330 (callee), there are several ways to push @code{G}'s parameters on the
26331 stack and there are several possible scenarios to clean up the stack
26332 upon @code{G}'s return. A calling convention is an agreed upon software
26333 protocol whereby the responsibilities between the caller (@code{F}) and
26334 the callee (@code{G}) are clearly defined. Several calling conventions
26335 are available for Windows:
26337 @itemize @bullet
26338 @item
26339 @code{C} (Microsoft defined)
26341 @item
26342 @code{Stdcall} (Microsoft defined)
26344 @item
26345 @code{DLL} (GNAT specific)
26346 @end itemize
26348 @node C Calling Convention
26349 @subsection @code{C} Calling Convention
26351 @noindent
26352 This is the default calling convention used when interfacing to C/C++
26353 routines compiled with either @code{gcc} or Microsoft Visual C++.
26355 In the @code{C} calling convention subprogram parameters are pushed on the
26356 stack by the caller from right to left. The caller itself is in charge of
26357 cleaning up the stack after the call. In addition, the name of a routine
26358 with @code{C} calling convention is mangled by adding a leading underscore.
26360 The name to use on the Ada side when importing (or exporting) a routine
26361 with @code{C} calling convention is the name of the routine. For
26362 instance the C function:
26364 @smallexample
26365 int get_val (long);
26366 @end smallexample
26368 @noindent
26369 should be imported from Ada as follows:
26371 @smallexample @c ada
26372 @group
26373 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26374 pragma Import (C, Get_Val, External_Name => "get_val");
26375 @end group
26376 @end smallexample
26378 @noindent
26379 Note that in this particular case the @code{External_Name} parameter could
26380 have been omitted since, when missing, this parameter is taken to be the
26381 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26382 is missing, as in the above example, this parameter is set to be the
26383 @code{External_Name} with a leading underscore.
26385 When importing a variable defined in C, you should always use the @code{C}
26386 calling convention unless the object containing the variable is part of a
26387 DLL (in which case you should use the @code{DLL} calling convention,
26388 @pxref{DLL Calling Convention}).
26390 @node Stdcall Calling Convention
26391 @subsection @code{Stdcall} Calling Convention
26393 @noindent
26394 This convention, which was the calling convention used for Pascal
26395 programs, is used by Microsoft for all the routines in the Win32 API for
26396 efficiency reasons. It must be used to import any routine for which this
26397 convention was specified.
26399 In the @code{Stdcall} calling convention subprogram parameters are pushed
26400 on the stack by the caller from right to left. The callee (and not the
26401 caller) is in charge of cleaning the stack on routine exit. In addition,
26402 the name of a routine with @code{Stdcall} calling convention is mangled by
26403 adding a leading underscore (as for the @code{C} calling convention) and a
26404 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
26405 bytes) of the parameters passed to the routine.
26407 The name to use on the Ada side when importing a C routine with a
26408 @code{Stdcall} calling convention is the name of the C routine. The leading
26409 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
26410 the compiler. For instance the Win32 function:
26412 @smallexample
26413 @b{APIENTRY} int get_val (long);
26414 @end smallexample
26416 @noindent
26417 should be imported from Ada as follows:
26419 @smallexample @c ada
26420 @group
26421 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26422 pragma Import (Stdcall, Get_Val);
26423 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26424 @end group
26425 @end smallexample
26427 @noindent
26428 As for the @code{C} calling convention, when the @code{External_Name}
26429 parameter is missing, it is taken to be the name of the Ada entity in lower
26430 case. If instead of writing the above import pragma you write:
26432 @smallexample @c ada
26433 @group
26434 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26435 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26436 @end group
26437 @end smallexample
26439 @noindent
26440 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26441 of specifying the @code{External_Name} parameter you specify the
26442 @code{Link_Name} as in the following example:
26444 @smallexample @c ada
26445 @group
26446 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26447 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26448 @end group
26449 @end smallexample
26451 @noindent
26452 then the imported routine is @code{retrieve_val@@4}, that is, there is no
26453 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
26454 added at the end of the @code{Link_Name} by the compiler.
26456 @noindent
26457 Note, that in some special cases a DLL's entry point name lacks a trailing
26458 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
26459 The @code{gnatdll} tool, which creates the import library for the DLL, is able
26460 to handle those cases (see the description of the switches in
26461 @pxref{Using gnatdll} section).
26463 @node DLL Calling Convention
26464 @subsection @code{DLL} Calling Convention
26466 @noindent
26467 This convention, which is GNAT-specific, must be used when you want to
26468 import in Ada a variables defined in a DLL. For functions and procedures
26469 this convention is equivalent to the @code{Stdcall} convention. As an
26470 example, if a DLL contains a variable defined as:
26472 @smallexample
26473 int my_var;
26474 @end smallexample
26476 @noindent
26477 then, to access this variable from Ada you should write:
26479 @smallexample @c ada
26480 @group
26481 My_Var : Interfaces.C.int;
26482 pragma Import (DLL, My_Var);
26483 @end group
26484 @end smallexample
26486 The remarks concerning the @code{External_Name} and @code{Link_Name}
26487 parameters given in the previous sections equally apply to the @code{DLL}
26488 calling convention.
26490 @node Introduction to Dynamic Link Libraries (DLLs)
26491 @section Introduction to Dynamic Link Libraries (DLLs)
26492 @findex DLL
26494 @noindent
26495 A Dynamically Linked Library (DLL) is a library that can be shared by
26496 several applications running under Windows. A DLL can contain any number of
26497 routines and variables.
26499 One advantage of DLLs is that you can change and enhance them without
26500 forcing all the applications that depend on them to be relinked or
26501 recompiled. However, you should be aware than all calls to DLL routines are
26502 slower since, as you will understand below, such calls are indirect.
26504 To illustrate the remainder of this section, suppose that an application
26505 wants to use the services of a DLL @file{API.dll}. To use the services
26506 provided by @file{API.dll} you must statically link against the DLL or
26507 an import library which contains a jump table with an entry for each
26508 routine and variable exported by the DLL. In the Microsoft world this
26509 import library is called @file{API.lib}. When using GNAT this import
26510 library is called either @file{libAPI.a} or @file{libapi.a} (names are
26511 case insensitive).
26513 After you have linked your application with the DLL or the import library
26514 and you run your application, here is what happens:
26516 @enumerate
26517 @item
26518 Your application is loaded into memory.
26520 @item
26521 The DLL @file{API.dll} is mapped into the address space of your
26522 application. This means that:
26524 @itemize @bullet
26525 @item
26526 The DLL will use the stack of the calling thread.
26528 @item
26529 The DLL will use the virtual address space of the calling process.
26531 @item
26532 The DLL will allocate memory from the virtual address space of the calling
26533 process.
26535 @item
26536 Handles (pointers) can be safely exchanged between routines in the DLL
26537 routines and routines in the application using the DLL.
26538 @end itemize
26540 @item
26541 The entries in the jump table (from the import library @file{libAPI.a}
26542 or @file{API.lib} or automatically created when linking against a DLL)
26543 which is part of your application are initialized with the addresses
26544 of the routines and variables in @file{API.dll}.
26546 @item
26547 If present in @file{API.dll}, routines @code{DllMain} or
26548 @code{DllMainCRTStartup} are invoked. These routines typically contain
26549 the initialization code needed for the well-being of the routines and
26550 variables exported by the DLL.
26551 @end enumerate
26553 @noindent
26554 There is an additional point which is worth mentioning. In the Windows
26555 world there are two kind of DLLs: relocatable and non-relocatable
26556 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
26557 in the target application address space. If the addresses of two
26558 non-relocatable DLLs overlap and these happen to be used by the same
26559 application, a conflict will occur and the application will run
26560 incorrectly. Hence, when possible, it is always preferable to use and
26561 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
26562 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
26563 User's Guide) removes the debugging symbols from the DLL but the DLL can
26564 still be relocated.
26566 As a side note, an interesting difference between Microsoft DLLs and
26567 Unix shared libraries, is the fact that on most Unix systems all public
26568 routines are exported by default in a Unix shared library, while under
26569 Windows it is possible (but not required) to list exported routines in
26570 a definition file (@pxref{The Definition File}).
26572 @node Using DLLs with GNAT
26573 @section Using DLLs with GNAT
26575 @menu
26576 * Creating an Ada Spec for the DLL Services::
26577 * Creating an Import Library::
26578 @end menu
26580 @noindent
26581 To use the services of a DLL, say @file{API.dll}, in your Ada application
26582 you must have:
26584 @enumerate
26585 @item
26586 The Ada spec for the routines and/or variables you want to access in
26587 @file{API.dll}. If not available this Ada spec must be built from the C/C++
26588 header files provided with the DLL.
26590 @item
26591 The import library (@file{libAPI.a} or @file{API.lib}). As previously
26592 mentioned an import library is a statically linked library containing the
26593 import table which will be filled at load time to point to the actual
26594 @file{API.dll} routines. Sometimes you don't have an import library for the
26595 DLL you want to use. The following sections will explain how to build
26596 one. Note that this is optional.
26598 @item
26599 The actual DLL, @file{API.dll}.
26600 @end enumerate
26602 @noindent
26603 Once you have all the above, to compile an Ada application that uses the
26604 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
26605 you simply issue the command
26607 @smallexample
26608 $ gnatmake my_ada_app -largs -lAPI
26609 @end smallexample
26611 @noindent
26612 The argument @option{-largs -lAPI} at the end of the @code{gnatmake} command
26613 tells the GNAT linker to look first for a library named @file{API.lib}
26614 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
26615 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
26616 contains the following pragma
26618 @smallexample @c ada
26619 pragma Linker_Options ("-lAPI");
26620 @end smallexample
26622 @noindent
26623 you do not have to add @option{-largs -lAPI} at the end of the @code{gnatmake}
26624 command.
26626 If any one of the items above is missing you will have to create it
26627 yourself. The following sections explain how to do so using as an
26628 example a fictitious DLL called @file{API.dll}.
26630 @node Creating an Ada Spec for the DLL Services
26631 @subsection Creating an Ada Spec for the DLL Services
26633 @noindent
26634 A DLL typically comes with a C/C++ header file which provides the
26635 definitions of the routines and variables exported by the DLL. The Ada
26636 equivalent of this header file is a package spec that contains definitions
26637 for the imported entities. If the DLL you intend to use does not come with
26638 an Ada spec you have to generate one such spec yourself. For example if
26639 the header file of @file{API.dll} is a file @file{api.h} containing the
26640 following two definitions:
26642 @smallexample
26643 @group
26644 @cartouche
26645 int some_var;
26646 int get (char *);
26647 @end cartouche
26648 @end group
26649 @end smallexample
26651 @noindent
26652 then the equivalent Ada spec could be:
26654 @smallexample @c ada
26655 @group
26656 @cartouche
26657 with Interfaces.C.Strings;
26658 package API is
26659    use Interfaces;
26661    Some_Var : C.int;
26662    function Get (Str : C.Strings.Chars_Ptr) return C.int;
26664 private
26665    pragma Import (C, Get);
26666    pragma Import (DLL, Some_Var);
26667 end API;
26668 @end cartouche
26669 @end group
26670 @end smallexample
26672 @noindent
26673 Note that a variable is @strong{always imported with a DLL convention}. A
26674 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
26675 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
26676 (@pxref{Windows Calling Conventions}).
26678 @node Creating an Import Library
26679 @subsection Creating an Import Library
26680 @cindex Import library
26682 @menu
26683 * The Definition File::
26684 * GNAT-Style Import Library::
26685 * Microsoft-Style Import Library::
26686 @end menu
26688 @noindent
26689 If a Microsoft-style import library @file{API.lib} or a GNAT-style
26690 import library @file{libAPI.a} is available with @file{API.dll} you
26691 can skip this section. You can also skip this section if
26692 @file{API.dll} is built with GNU tools as in this case it is possible
26693 to link directly against the DLL. Otherwise read on.
26695 @node The Definition File
26696 @subsubsection The Definition File
26697 @cindex Definition file
26698 @findex .def
26700 @noindent
26701 As previously mentioned, and unlike Unix systems, the list of symbols
26702 that are exported from a DLL must be provided explicitly in Windows.
26703 The main goal of a definition file is precisely that: list the symbols
26704 exported by a DLL. A definition file (usually a file with a @code{.def}
26705 suffix) has the following structure:
26707 @smallexample
26708 @group
26709 @cartouche
26710 [LIBRARY @i{name}]
26711 [DESCRIPTION @i{string}]
26712 EXPORTS
26713    @i{symbol1}
26714    @i{symbol2}
26715    ...
26716 @end cartouche
26717 @end group
26718 @end smallexample
26720 @table @code
26721 @item LIBRARY @i{name}
26722 This section, which is optional, gives the name of the DLL.
26724 @item DESCRIPTION @i{string}
26725 This section, which is optional, gives a description string that will be
26726 embedded in the import library.
26728 @item EXPORTS
26729 This section gives the list of exported symbols (procedures, functions or
26730 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
26731 section of @file{API.def} looks like:
26733 @smallexample
26734 @group
26735 @cartouche
26736 EXPORTS
26737    some_var
26738    get
26739 @end cartouche
26740 @end group
26741 @end smallexample
26742 @end table
26744 @noindent
26745 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
26746 (@pxref{Windows Calling Conventions}) for a Stdcall
26747 calling convention function in the exported symbols list.
26749 @noindent
26750 There can actually be other sections in a definition file, but these
26751 sections are not relevant to the discussion at hand.
26753 @node GNAT-Style Import Library
26754 @subsubsection GNAT-Style Import Library
26756 @noindent
26757 To create a static import library from @file{API.dll} with the GNAT tools
26758 you should proceed as follows:
26760 @enumerate
26761 @item
26762 Create the definition file @file{API.def} (@pxref{The Definition File}).
26763 For that use the @code{dll2def} tool as follows:
26765 @smallexample
26766 $ dll2def API.dll > API.def
26767 @end smallexample
26769 @noindent
26770 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
26771 to standard output the list of entry points in the DLL. Note that if
26772 some routines in the DLL have the @code{Stdcall} convention
26773 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
26774 suffix then you'll have to edit @file{api.def} to add it, and specify
26775 @code{-k} to @code{gnatdll} when creating the import library.
26777 @noindent
26778 Here are some hints to find the right @code{@@}@i{nn} suffix.
26780 @enumerate
26781 @item
26782 If you have the Microsoft import library (.lib), it is possible to get
26783 the right symbols by using Microsoft @code{dumpbin} tool (see the
26784 corresponding Microsoft documentation for further details).
26786 @smallexample
26787 $ dumpbin /exports api.lib
26788 @end smallexample
26790 @item
26791 If you have a message about a missing symbol at link time the compiler
26792 tells you what symbol is expected. You just have to go back to the
26793 definition file and add the right suffix.
26794 @end enumerate
26796 @item
26797 Build the import library @code{libAPI.a}, using @code{gnatdll}
26798 (@pxref{Using gnatdll}) as follows:
26800 @smallexample
26801 $ gnatdll -e API.def -d API.dll
26802 @end smallexample
26804 @noindent
26805 @code{gnatdll} takes as input a definition file @file{API.def} and the
26806 name of the DLL containing the services listed in the definition file
26807 @file{API.dll}. The name of the static import library generated is
26808 computed from the name of the definition file as follows: if the
26809 definition file name is @i{xyz}@code{.def}, the import library name will
26810 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
26811 @option{-e} could have been removed because the name of the definition
26812 file (before the ``@code{.def}'' suffix) is the same as the name of the
26813 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
26814 @end enumerate
26816 @node Microsoft-Style Import Library
26817 @subsubsection Microsoft-Style Import Library
26819 @noindent
26820 With GNAT you can either use a GNAT-style or Microsoft-style import
26821 library. A Microsoft import library is needed only if you plan to make an
26822 Ada DLL available to applications developed with Microsoft
26823 tools (@pxref{Mixed-Language Programming on Windows}).
26825 To create a Microsoft-style import library for @file{API.dll} you
26826 should proceed as follows:
26828 @enumerate
26829 @item
26830 Create the definition file @file{API.def} from the DLL. For this use either
26831 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
26832 tool (see the corresponding Microsoft documentation for further details).
26834 @item
26835 Build the actual import library using Microsoft's @code{lib} utility:
26837 @smallexample
26838 $ lib -machine:IX86 -def:API.def -out:API.lib
26839 @end smallexample
26841 @noindent
26842 If you use the above command the definition file @file{API.def} must
26843 contain a line giving the name of the DLL:
26845 @smallexample
26846 LIBRARY      "API"
26847 @end smallexample
26849 @noindent
26850 See the Microsoft documentation for further details about the usage of
26851 @code{lib}.
26852 @end enumerate
26854 @node Building DLLs with GNAT
26855 @section Building DLLs with GNAT
26856 @cindex DLLs, building
26858 @noindent
26859 This section explain how to build DLLs using the GNAT built-in DLL
26860 support. With the following procedure it is straight forward to build
26861 and use DLLs with GNAT.
26863 @enumerate
26865 @item building object files
26867 The first step is to build all objects files that are to be included
26868 into the DLL. This is done by using the standard @code{gnatmake} tool.
26870 @item building the DLL
26872 To build the DLL you must use @code{gcc}'s @code{-shared}
26873 option. It is quite simple to use this method:
26875 @smallexample
26876 $ gcc -shared -o api.dll obj1.o obj2.o ...
26877 @end smallexample
26879 It is important to note that in this case all symbols found in the
26880 object files are automatically exported. It is possible to restrict
26881 the set of symbols to export by passing to @code{gcc} a definition
26882 file, @pxref{The Definition File}. For example:
26884 @smallexample
26885 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
26886 @end smallexample
26888 If you use a definition file you must export the elaboration procedures
26889 for every package that required one. Elaboration procedures are named
26890 using the package name followed by "_E".
26892 @item preparing DLL to be used
26894 For the DLL to be used by client programs the bodies must be hidden
26895 from it and the .ali set with read-only attribute. This is very important
26896 otherwise GNAT will recompile all packages and will not actually use
26897 the code in the DLL. For example:
26899 @smallexample
26900 $ mkdir apilib
26901 $ copy *.ads *.ali api.dll apilib
26902 $ attrib +R apilib\*.ali
26903 @end smallexample
26905 @end enumerate
26907 At this point it is possible to use the DLL by directly linking
26908 against it. Note that you must use the GNAT shared runtime when using
26909 GNAT shared libraries. This is achieved by using @code{-shared} binder's
26910 option.
26912 @smallexample
26913 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
26914 @end smallexample
26916 @node Building DLLs with GNAT Project files
26917 @section Building DLLs with GNAT Project files
26918 @cindex DLLs, building
26920 @noindent
26921 There is nothing specific to Windows in this area. @pxref{Library Projects}.
26923 @node Building DLLs with gnatdll
26924 @section Building DLLs with gnatdll
26925 @cindex DLLs, building
26927 @menu
26928 * Limitations When Using Ada DLLs from Ada::
26929 * Exporting Ada Entities::
26930 * Ada DLLs and Elaboration::
26931 * Ada DLLs and Finalization::
26932 * Creating a Spec for Ada DLLs::
26933 * Creating the Definition File::
26934 * Using gnatdll::
26935 @end menu
26937 @noindent
26938 Note that it is prefered to use the built-in GNAT DLL support
26939 (@pxref{Building DLLs with GNAT}) or GNAT Project files
26940 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
26942 This section explains how to build DLLs containing Ada code using
26943 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
26944 remainder of this section.
26946 The steps required to build an Ada DLL that is to be used by Ada as well as
26947 non-Ada applications are as follows:
26949 @enumerate
26950 @item
26951 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
26952 @code{Stdcall} calling convention to avoid any Ada name mangling for the
26953 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
26954 skip this step if you plan to use the Ada DLL only from Ada applications.
26956 @item
26957 Your Ada code must export an initialization routine which calls the routine
26958 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
26959 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
26960 routine exported by the Ada DLL must be invoked by the clients of the DLL
26961 to initialize the DLL.
26963 @item
26964 When useful, the DLL should also export a finalization routine which calls
26965 routine @code{adafinal} generated by @code{gnatbind} to perform the
26966 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
26967 The finalization routine exported by the Ada DLL must be invoked by the
26968 clients of the DLL when the DLL services are no further needed.
26970 @item
26971 You must provide a spec for the services exported by the Ada DLL in each
26972 of the programming languages to which you plan to make the DLL available.
26974 @item
26975 You must provide a definition file listing the exported entities
26976 (@pxref{The Definition File}).
26978 @item
26979 Finally you must use @code{gnatdll} to produce the DLL and the import
26980 library (@pxref{Using gnatdll}).
26981 @end enumerate
26983 @noindent
26984 Note that a relocatable DLL stripped using the @code{strip} binutils
26985 tool will not be relocatable anymore. To build a DLL without debug
26986 information pass @code{-largs -s} to @code{gnatdll}.
26988 @node Limitations When Using Ada DLLs from Ada
26989 @subsection Limitations When Using Ada DLLs from Ada
26991 @noindent
26992 When using Ada DLLs from Ada applications there is a limitation users
26993 should be aware of. Because on Windows the GNAT run time is not in a DLL of
26994 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
26995 each Ada DLL includes the services of the GNAT run time that are necessary
26996 to the Ada code inside the DLL. As a result, when an Ada program uses an
26997 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
26998 one in the main program.
27000 It is therefore not possible to exchange GNAT run-time objects between the
27001 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27002 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
27003 types, etc.
27005 It is completely safe to exchange plain elementary, array or record types,
27006 Windows object handles, etc.
27008 @node Exporting Ada Entities
27009 @subsection Exporting Ada Entities
27010 @cindex Export table
27012 @noindent
27013 Building a DLL is a way to encapsulate a set of services usable from any
27014 application. As a result, the Ada entities exported by a DLL should be
27015 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27016 any Ada name mangling. Please note that the @code{Stdcall} convention
27017 should only be used for subprograms, not for variables. As an example here
27018 is an Ada package @code{API}, spec and body, exporting two procedures, a
27019 function, and a variable:
27021 @smallexample @c ada
27022 @group
27023 @cartouche
27024 with Interfaces.C; use Interfaces;
27025 package API is
27026    Count : C.int := 0;
27027    function Factorial (Val : C.int) return C.int;
27029    procedure Initialize_API;
27030    procedure Finalize_API;
27031    --  Initialization & Finalization routines. More in the next section.
27032 private
27033    pragma Export (C, Initialize_API);
27034    pragma Export (C, Finalize_API);
27035    pragma Export (C, Count);
27036    pragma Export (C, Factorial);
27037 end API;
27038 @end cartouche
27039 @end group
27040 @end smallexample
27042 @smallexample @c ada
27043 @group
27044 @cartouche
27045 package body API is
27046    function Factorial (Val : C.int) return C.int is
27047       Fact : C.int := 1;
27048    begin
27049       Count := Count + 1;
27050       for K in 1 .. Val loop
27051          Fact := Fact * K;
27052       end loop;
27053       return Fact;
27054    end Factorial;
27056    procedure Initialize_API is
27057       procedure Adainit;
27058       pragma Import (C, Adainit);
27059    begin
27060       Adainit;
27061    end Initialize_API;
27063    procedure Finalize_API is
27064       procedure Adafinal;
27065       pragma Import (C, Adafinal);
27066    begin
27067       Adafinal;
27068    end Finalize_API;
27069 end API;
27070 @end cartouche
27071 @end group
27072 @end smallexample
27074 @noindent
27075 If the Ada DLL you are building will only be used by Ada applications
27076 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27077 convention. As an example, the previous package could be written as
27078 follows:
27080 @smallexample @c ada
27081 @group
27082 @cartouche
27083 package API is
27084    Count : Integer := 0;
27085    function Factorial (Val : Integer) return Integer;
27087    procedure Initialize_API;
27088    procedure Finalize_API;
27089    --  Initialization and Finalization routines.
27090 end API;
27091 @end cartouche
27092 @end group
27093 @end smallexample
27095 @smallexample @c ada
27096 @group
27097 @cartouche
27098 package body API is
27099    function Factorial (Val : Integer) return Integer is
27100       Fact : Integer := 1;
27101    begin
27102       Count := Count + 1;
27103       for K in 1 .. Val loop
27104          Fact := Fact * K;
27105       end loop;
27106       return Fact;
27107    end Factorial;
27109    ...
27110    --  The remainder of this package body is unchanged.
27111 end API;
27112 @end cartouche
27113 @end group
27114 @end smallexample
27116 @noindent
27117 Note that if you do not export the Ada entities with a @code{C} or
27118 @code{Stdcall} convention you will have to provide the mangled Ada names
27119 in the definition file of the Ada DLL
27120 (@pxref{Creating the Definition File}).
27122 @node Ada DLLs and Elaboration
27123 @subsection Ada DLLs and Elaboration
27124 @cindex DLLs and elaboration
27126 @noindent
27127 The DLL that you are building contains your Ada code as well as all the
27128 routines in the Ada library that are needed by it. The first thing a
27129 user of your DLL must do is elaborate the Ada code
27130 (@pxref{Elaboration Order Handling in GNAT}).
27132 To achieve this you must export an initialization routine
27133 (@code{Initialize_API} in the previous example), which must be invoked
27134 before using any of the DLL services. This elaboration routine must call
27135 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27136 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27137 @code{Initialize_Api} for an example. Note that the GNAT binder is
27138 automatically invoked during the DLL build process by the @code{gnatdll}
27139 tool (@pxref{Using gnatdll}).
27141 When a DLL is loaded, Windows systematically invokes a routine called
27142 @code{DllMain}. It would therefore be possible to call @code{adainit}
27143 directly from @code{DllMain} without having to provide an explicit
27144 initialization routine. Unfortunately, it is not possible to call
27145 @code{adainit} from the @code{DllMain} if your program has library level
27146 tasks because access to the @code{DllMain} entry point is serialized by
27147 the system (that is, only a single thread can execute ``through'' it at a
27148 time), which means that the GNAT run time will deadlock waiting for the
27149 newly created task to complete its initialization.
27151 @node Ada DLLs and Finalization
27152 @subsection Ada DLLs and Finalization
27153 @cindex DLLs and finalization
27155 @noindent
27156 When the services of an Ada DLL are no longer needed, the client code should
27157 invoke the DLL finalization routine, if available. The DLL finalization
27158 routine is in charge of releasing all resources acquired by the DLL. In the
27159 case of the Ada code contained in the DLL, this is achieved by calling
27160 routine @code{adafinal} generated by the GNAT binder
27161 (@pxref{Binding with Non-Ada Main Programs}).
27162 See the body of @code{Finalize_Api} for an
27163 example. As already pointed out the GNAT binder is automatically invoked
27164 during the DLL build process by the @code{gnatdll} tool
27165 (@pxref{Using gnatdll}).
27167 @node Creating a Spec for Ada DLLs
27168 @subsection Creating a Spec for Ada DLLs
27170 @noindent
27171 To use the services exported by the Ada DLL from another programming
27172 language (e.g. C), you have to translate the specs of the exported Ada
27173 entities in that language. For instance in the case of @code{API.dll},
27174 the corresponding C header file could look like:
27176 @smallexample
27177 @group
27178 @cartouche
27179 extern int *_imp__count;
27180 #define count (*_imp__count)
27181 int factorial (int);
27182 @end cartouche
27183 @end group
27184 @end smallexample
27186 @noindent
27187 It is important to understand that when building an Ada DLL to be used by
27188 other Ada applications, you need two different specs for the packages
27189 contained in the DLL: one for building the DLL and the other for using
27190 the DLL. This is because the @code{DLL} calling convention is needed to
27191 use a variable defined in a DLL, but when building the DLL, the variable
27192 must have either the @code{Ada} or @code{C} calling convention. As an
27193 example consider a DLL comprising the following package @code{API}:
27195 @smallexample @c ada
27196 @group
27197 @cartouche
27198 package API is
27199    Count : Integer := 0;
27200    ...
27201    --  Remainder of the package omitted.
27202 end API;
27203 @end cartouche
27204 @end group
27205 @end smallexample
27207 @noindent
27208 After producing a DLL containing package @code{API}, the spec that
27209 must be used to import @code{API.Count} from Ada code outside of the
27210 DLL is:
27212 @smallexample @c ada
27213 @group
27214 @cartouche
27215 package API is
27216    Count : Integer;
27217    pragma Import (DLL, Count);
27218 end API;
27219 @end cartouche
27220 @end group
27221 @end smallexample
27223 @node Creating the Definition File
27224 @subsection Creating the Definition File
27226 @noindent
27227 The definition file is the last file needed to build the DLL. It lists
27228 the exported symbols. As an example, the definition file for a DLL
27229 containing only package @code{API} (where all the entities are exported
27230 with a @code{C} calling convention) is:
27232 @smallexample
27233 @group
27234 @cartouche
27235 EXPORTS
27236     count
27237     factorial
27238     finalize_api
27239     initialize_api
27240 @end cartouche
27241 @end group
27242 @end smallexample
27244 @noindent
27245 If the @code{C} calling convention is missing from package @code{API},
27246 then the definition file contains the mangled Ada names of the above
27247 entities, which in this case are:
27249 @smallexample
27250 @group
27251 @cartouche
27252 EXPORTS
27253     api__count
27254     api__factorial
27255     api__finalize_api
27256     api__initialize_api
27257 @end cartouche
27258 @end group
27259 @end smallexample
27261 @node Using gnatdll
27262 @subsection Using @code{gnatdll}
27263 @findex gnatdll
27265 @menu
27266 * gnatdll Example::
27267 * gnatdll behind the Scenes::
27268 * Using dlltool::
27269 @end menu
27271 @noindent
27272 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
27273 and non-Ada sources that make up your DLL have been compiled.
27274 @code{gnatdll} is actually in charge of two distinct tasks: build the
27275 static import library for the DLL and the actual DLL. The form of the
27276 @code{gnatdll} command is
27278 @smallexample
27279 @cartouche
27280 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
27281 @end cartouche
27282 @end smallexample
27284 @noindent
27285 where @i{list-of-files} is a list of ALI and object files. The object
27286 file list must be the exact list of objects corresponding to the non-Ada
27287 sources whose services are to be included in the DLL. The ALI file list
27288 must be the exact list of ALI files for the corresponding Ada sources
27289 whose services are to be included in the DLL. If @i{list-of-files} is
27290 missing, only the static import library is generated.
27292 @noindent
27293 You may specify any of the following switches to @code{gnatdll}:
27295 @table @code
27296 @item -a[@var{address}]
27297 @cindex @option{-a} (@code{gnatdll})
27298 Build a non-relocatable DLL at @var{address}. If @var{address} is not
27299 specified the default address @var{0x11000000} will be used. By default,
27300 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
27301 advise the reader to build relocatable DLL.
27303 @item -b @var{address}
27304 @cindex @option{-b} (@code{gnatdll})
27305 Set the relocatable DLL base address. By default the address is
27306 @var{0x11000000}.
27308 @item -bargs @var{opts}
27309 @cindex @option{-bargs} (@code{gnatdll})
27310 Binder options. Pass @var{opts} to the binder.
27312 @item -d @var{dllfile}
27313 @cindex @option{-d} (@code{gnatdll})
27314 @var{dllfile} is the name of the DLL. This switch must be present for
27315 @code{gnatdll} to do anything. The name of the generated import library is
27316 obtained algorithmically from @var{dllfile} as shown in the following
27317 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
27318 @code{libxyz.a}. The name of the definition file to use (if not specified
27319 by option @option{-e}) is obtained algorithmically from @var{dllfile}
27320 as shown in the following example:
27321 if @var{dllfile} is @code{xyz.dll}, the definition
27322 file used is @code{xyz.def}.
27324 @item -e @var{deffile}
27325 @cindex @option{-e} (@code{gnatdll})
27326 @var{deffile} is the name of the definition file.
27328 @item -g
27329 @cindex @option{-g} (@code{gnatdll})
27330 Generate debugging information. This information is stored in the object
27331 file and copied from there to the final DLL file by the linker,
27332 where it can be read by the debugger. You must use the
27333 @option{-g} switch if you plan on using the debugger or the symbolic
27334 stack traceback.
27336 @item -h
27337 @cindex @option{-h} (@code{gnatdll})
27338 Help mode. Displays @code{gnatdll} switch usage information.
27340 @item -Idir
27341 @cindex @option{-I} (@code{gnatdll})
27342 Direct @code{gnatdll} to search the @var{dir} directory for source and
27343 object files needed to build the DLL.
27344 (@pxref{Search Paths and the Run-Time Library (RTL)}).
27346 @item -k
27347 @cindex @option{-k} (@code{gnatdll})
27348 Removes the @code{@@}@i{nn} suffix from the import library's exported
27349 names, but keeps them for the link names. You must specify this
27350 option if you want to use a @code{Stdcall} function in a DLL for which
27351 the @code{@@}@i{nn} suffix has been removed. This is the case for most
27352 of the Windows NT DLL for example. This option has no effect when
27353 @option{-n} option is specified.
27355 @item -l @var{file}
27356 @cindex @option{-l} (@code{gnatdll})
27357 The list of ALI and object files used to build the DLL are listed in
27358 @var{file}, instead of being given in the command line. Each line in
27359 @var{file} contains the name of an ALI or object file.
27361 @item -n
27362 @cindex @option{-n} (@code{gnatdll})
27363 No Import. Do not create the import library.
27365 @item -q
27366 @cindex @option{-q} (@code{gnatdll})
27367 Quiet mode. Do not display unnecessary messages.
27369 @item -v
27370 @cindex @option{-v} (@code{gnatdll})
27371 Verbose mode. Display extra information.
27373 @item -largs @var{opts}
27374 @cindex @option{-largs} (@code{gnatdll})
27375 Linker options. Pass @var{opts} to the linker.
27376 @end table
27378 @node gnatdll Example
27379 @subsubsection @code{gnatdll} Example
27381 @noindent
27382 As an example the command to build a relocatable DLL from @file{api.adb}
27383 once @file{api.adb} has been compiled and @file{api.def} created is
27385 @smallexample
27386 $ gnatdll -d api.dll api.ali
27387 @end smallexample
27389 @noindent
27390 The above command creates two files: @file{libapi.a} (the import
27391 library) and @file{api.dll} (the actual DLL). If you want to create
27392 only the DLL, just type:
27394 @smallexample
27395 $ gnatdll -d api.dll -n api.ali
27396 @end smallexample
27398 @noindent
27399 Alternatively if you want to create just the import library, type:
27401 @smallexample
27402 $ gnatdll -d api.dll
27403 @end smallexample
27405 @node gnatdll behind the Scenes
27406 @subsubsection @code{gnatdll} behind the Scenes
27408 @noindent
27409 This section details the steps involved in creating a DLL. @code{gnatdll}
27410 does these steps for you. Unless you are interested in understanding what
27411 goes on behind the scenes, you should skip this section.
27413 We use the previous example of a DLL containing the Ada package @code{API},
27414 to illustrate the steps necessary to build a DLL. The starting point is a
27415 set of objects that will make up the DLL and the corresponding ALI
27416 files. In the case of this example this means that @file{api.o} and
27417 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27418 the following:
27420 @enumerate
27421 @item
27422 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27423 the information necessary to generate relocation information for the
27424 DLL.
27426 @smallexample
27427 @group
27428 $ gnatbind -n api
27429 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27430 @end group
27431 @end smallexample
27433 @noindent
27434 In addition to the base file, the @code{gnatlink} command generates an
27435 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27436 asks @code{gnatlink} to generate the routines @code{DllMain} and
27437 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27438 is loaded into memory.
27440 @item
27441 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27442 export table (@file{api.exp}). The export table contains the relocation
27443 information in a form which can be used during the final link to ensure
27444 that the Windows loader is able to place the DLL anywhere in memory.
27446 @smallexample
27447 @group
27448 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27449           --output-exp api.exp
27450 @end group
27451 @end smallexample
27453 @item
27454 @code{gnatdll} builds the base file using the new export table. Note that
27455 @code{gnatbind} must be called once again since the binder generated file
27456 has been deleted during the previous call to @code{gnatlink}.
27458 @smallexample
27459 @group
27460 $ gnatbind -n api
27461 $ gnatlink api -o api.jnk api.exp -mdll
27462       -Wl,--base-file,api.base
27463 @end group
27464 @end smallexample
27466 @item
27467 @code{gnatdll} builds the new export table using the new base file and
27468 generates the DLL import library @file{libAPI.a}.
27470 @smallexample
27471 @group
27472 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27473           --output-exp api.exp --output-lib libAPI.a
27474 @end group
27475 @end smallexample
27477 @item
27478 Finally @code{gnatdll} builds the relocatable DLL using the final export
27479 table.
27481 @smallexample
27482 @group
27483 $ gnatbind -n api
27484 $ gnatlink api api.exp -o api.dll -mdll
27485 @end group
27486 @end smallexample
27487 @end enumerate
27489 @node Using dlltool
27490 @subsubsection Using @code{dlltool}
27492 @noindent
27493 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27494 DLLs and static import libraries. This section summarizes the most
27495 common @code{dlltool} switches. The form of the @code{dlltool} command
27498 @smallexample
27499 $ dlltool [@var{switches}]
27500 @end smallexample
27502 @noindent
27503 @code{dlltool} switches include:
27505 @table @option
27506 @item --base-file @var{basefile}
27507 @cindex @option{--base-file} (@command{dlltool})
27508 Read the base file @var{basefile} generated by the linker. This switch
27509 is used to create a relocatable DLL.
27511 @item --def @var{deffile}
27512 @cindex @option{--def} (@command{dlltool})
27513 Read the definition file.
27515 @item --dllname @var{name}
27516 @cindex @option{--dllname} (@command{dlltool})
27517 Gives the name of the DLL. This switch is used to embed the name of the
27518 DLL in the static import library generated by @code{dlltool} with switch
27519 @option{--output-lib}.
27521 @item -k
27522 @cindex @option{-k} (@command{dlltool})
27523 Kill @code{@@}@i{nn} from exported names
27524 (@pxref{Windows Calling Conventions}
27525 for a discussion about @code{Stdcall}-style symbols.
27527 @item --help
27528 @cindex @option{--help} (@command{dlltool})
27529 Prints the @code{dlltool} switches with a concise description.
27531 @item --output-exp @var{exportfile}
27532 @cindex @option{--output-exp} (@command{dlltool})
27533 Generate an export file @var{exportfile}. The export file contains the
27534 export table (list of symbols in the DLL) and is used to create the DLL.
27536 @item --output-lib @i{libfile}
27537 @cindex @option{--output-lib} (@command{dlltool})
27538 Generate a static import library @var{libfile}.
27540 @item -v
27541 @cindex @option{-v} (@command{dlltool})
27542 Verbose mode.
27544 @item --as @i{assembler-name}
27545 @cindex @option{--as} (@command{dlltool})
27546 Use @i{assembler-name} as the assembler. The default is @code{as}.
27547 @end table
27549 @node GNAT and Windows Resources
27550 @section GNAT and Windows Resources
27551 @cindex Resources, windows
27553 @menu
27554 * Building Resources::
27555 * Compiling Resources::
27556 * Using Resources::
27557 @end menu
27559 @noindent
27560 Resources are an easy way to add Windows specific objects to your
27561 application. The objects that can be added as resources include:
27563 @itemize @bullet
27564 @item
27565 menus
27567 @item
27568 accelerators
27570 @item
27571 dialog boxes
27573 @item
27574 string tables
27576 @item
27577 bitmaps
27579 @item
27580 cursors
27582 @item
27583 icons
27585 @item
27586 fonts
27587 @end itemize
27589 @noindent
27590 This section explains how to build, compile and use resources.
27592 @node Building Resources
27593 @subsection Building Resources
27594 @cindex Resources, building
27596 @noindent
27597 A resource file is an ASCII file. By convention resource files have an
27598 @file{.rc} extension.
27599 The easiest way to build a resource file is to use Microsoft tools
27600 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
27601 @code{dlgedit.exe} to build dialogs.
27602 It is always possible to build an @file{.rc} file yourself by writing a
27603 resource script.
27605 It is not our objective to explain how to write a resource file. A
27606 complete description of the resource script language can be found in the
27607 Microsoft documentation.
27609 @node Compiling Resources
27610 @subsection Compiling Resources
27611 @findex rc
27612 @findex windres
27613 @cindex Resources, compiling
27615 @noindent
27616 This section describes how to build a GNAT-compatible (COFF) object file
27617 containing the resources. This is done using the Resource Compiler
27618 @code{windres} as follows:
27620 @smallexample
27621 $ windres -i myres.rc -o myres.o
27622 @end smallexample
27624 @noindent
27625 By default @code{windres} will run @code{gcc} to preprocess the @file{.rc}
27626 file. You can specify an alternate preprocessor (usually named
27627 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
27628 parameter. A list of all possible options may be obtained by entering
27629 the command @code{windres} @option{--help}.
27631 It is also possible to use the Microsoft resource compiler @code{rc.exe}
27632 to produce a @file{.res} file (binary resource file). See the
27633 corresponding Microsoft documentation for further details. In this case
27634 you need to use @code{windres} to translate the @file{.res} file to a
27635 GNAT-compatible object file as follows:
27637 @smallexample
27638 $ windres -i myres.res -o myres.o
27639 @end smallexample
27641 @node Using Resources
27642 @subsection Using Resources
27643 @cindex Resources, using
27645 @noindent
27646 To include the resource file in your program just add the
27647 GNAT-compatible object file for the resource(s) to the linker
27648 arguments. With @code{gnatmake} this is done by using the @option{-largs}
27649 option:
27651 @smallexample
27652 $ gnatmake myprog -largs myres.o
27653 @end smallexample
27655 @node Debugging a DLL
27656 @section Debugging a DLL
27657 @cindex DLL debugging
27659 @menu
27660 * Program and DLL Both Built with GCC/GNAT::
27661 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
27662 @end menu
27664 @noindent
27665 Debugging a DLL is similar to debugging a standard program. But
27666 we have to deal with two different executable parts: the DLL and the
27667 program that uses it. We have the following four possibilities:
27669 @enumerate 1
27670 @item
27671 The program and the DLL are built with @code{GCC/GNAT}.
27672 @item
27673 The program is built with foreign tools and the DLL is built with
27674 @code{GCC/GNAT}.
27675 @item
27676 The program is built with @code{GCC/GNAT} and the DLL is built with
27677 foreign tools.
27678 @item
27679 @end enumerate
27681 @noindent
27682 In this section we address only cases one and two above.
27683 There is no point in trying to debug
27684 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
27685 information in it. To do so you must use a debugger compatible with the
27686 tools suite used to build the DLL.
27688 @node Program and DLL Both Built with GCC/GNAT
27689 @subsection Program and DLL Both Built with GCC/GNAT
27691 @noindent
27692 This is the simplest case. Both the DLL and the program have @code{GDB}
27693 compatible debugging information. It is then possible to break anywhere in
27694 the process. Let's suppose here that the main procedure is named
27695 @code{ada_main} and that in the DLL there is an entry point named
27696 @code{ada_dll}.
27698 @noindent
27699 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
27700 program must have been built with the debugging information (see GNAT -g
27701 switch). Here are the step-by-step instructions for debugging it:
27703 @enumerate 1
27704 @item Launch @code{GDB} on the main program.
27706 @smallexample
27707 $ gdb -nw ada_main
27708 @end smallexample
27710 @item Break on the main procedure and run the program.
27712 @smallexample
27713 (gdb) break ada_main
27714 (gdb) run
27715 @end smallexample
27717 @noindent
27718 This step is required to be able to set a breakpoint inside the DLL. As long
27719 as the program is not run, the DLL is not loaded. This has the
27720 consequence that the DLL debugging information is also not loaded, so it is not
27721 possible to set a breakpoint in the DLL.
27723 @item Set a breakpoint inside the DLL
27725 @smallexample
27726 (gdb) break ada_dll
27727 (gdb) run
27728 @end smallexample
27730 @end enumerate
27732 @noindent
27733 At this stage a breakpoint is set inside the DLL. From there on
27734 you can use the standard approach to debug the whole program
27735 (@pxref{Running and Debugging Ada Programs}).
27737 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
27738 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
27740 @menu
27741 * Debugging the DLL Directly::
27742 * Attaching to a Running Process::
27743 @end menu
27745 @noindent
27746 In this case things are slightly more complex because it is not possible to
27747 start the main program and then break at the beginning to load the DLL and the
27748 associated DLL debugging information. It is not possible to break at the
27749 beginning of the program because there is no @code{GDB} debugging information,
27750 and therefore there is no direct way of getting initial control. This
27751 section addresses this issue by describing some methods that can be used
27752 to break somewhere in the DLL to debug it.
27754 @noindent
27755 First suppose that the main procedure is named @code{main} (this is for
27756 example some C code built with Microsoft Visual C) and that there is a
27757 DLL named @code{test.dll} containing an Ada entry point named
27758 @code{ada_dll}.
27760 @noindent
27761 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
27762 been built with debugging information (see GNAT -g option).
27764 @node Debugging the DLL Directly
27765 @subsubsection Debugging the DLL Directly
27767 @enumerate 1
27768 @item
27769 Launch the debugger on the DLL.
27771 @smallexample
27772 $ gdb -nw test.dll
27773 @end smallexample
27775 @item Set a breakpoint on a DLL subroutine.
27777 @smallexample
27778 (gdb) break ada_dll
27779 @end smallexample
27781 @item
27782 Specify the executable file to @code{GDB}.
27784 @smallexample
27785 (gdb) exec-file main.exe
27786 @end smallexample
27788 @item
27789 Run the program.
27791 @smallexample
27792 (gdb) run
27793 @end smallexample
27795 @noindent
27796 This will run the program until it reaches the breakpoint that has been
27797 set. From that point you can use the standard way to debug a program
27798 as described in (@pxref{Running and Debugging Ada Programs}).
27800 @end enumerate
27802 @noindent
27803 It is also possible to debug the DLL by attaching to a running process.
27805 @node Attaching to a Running Process
27806 @subsubsection Attaching to a Running Process
27807 @cindex DLL debugging, attach to process
27809 @noindent
27810 With @code{GDB} it is always possible to debug a running process by
27811 attaching to it. It is possible to debug a DLL this way. The limitation
27812 of this approach is that the DLL must run long enough to perform the
27813 attach operation. It may be useful for instance to insert a time wasting
27814 loop in the code of the DLL to meet this criterion.
27816 @enumerate 1
27818 @item Launch the main program @file{main.exe}.
27820 @smallexample
27821 $ main
27822 @end smallexample
27824 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
27825 that the process PID for @file{main.exe} is 208.
27827 @item Launch gdb.
27829 @smallexample
27830 $ gdb -nw
27831 @end smallexample
27833 @item Attach to the running process to be debugged.
27835 @smallexample
27836 (gdb) attach 208
27837 @end smallexample
27839 @item Load the process debugging information.
27841 @smallexample
27842 (gdb) symbol-file main.exe
27843 @end smallexample
27845 @item Break somewhere in the DLL.
27847 @smallexample
27848 (gdb) break ada_dll
27849 @end smallexample
27851 @item Continue process execution.
27853 @smallexample
27854 (gdb) continue
27855 @end smallexample
27857 @end enumerate
27859 @noindent
27860 This last step will resume the process execution, and stop at
27861 the breakpoint we have set. From there you can use the standard
27862 approach to debug a program as described in
27863 (@pxref{Running and Debugging Ada Programs}).
27865 @node GNAT and COM/DCOM Objects
27866 @section GNAT and COM/DCOM Objects
27867 @findex COM
27868 @findex DCOM
27870 @noindent
27871 This section is temporarily left blank.
27873 @end ifset
27876 @c **********************************
27877 @c * GNU Free Documentation License *
27878 @c **********************************
27879 @include fdl.texi
27880 @c GNU Free Documentation License
27882 @node Index,,GNU Free Documentation License, Top
27883 @unnumbered Index
27885 @printindex cp
27887 @contents
27888 @c Put table of contents at end, otherwise it precedes the "title page" in
27889 @c the .txt version
27890 @c Edit the pdf file to move the contents to the beginning, after the title
27891 @c page
27893 @bye