OSDN Git Service

2005-03-17 Vasiliy Fofanov <fofanov@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c          Copyright (C) 1992-2005 Ada Core Technologies, Inc.               o
11 @c                                                                            o
12 @c  GNAT is free software;  you can  redistribute it  and/or modify it under  o
13 @c  terms of the  GNU General Public License as published  by the Free Soft-  o
14 @c  ware  Foundation;  either version 2,  or (at your option) any later ver-  o
15 @c  sion.  GNAT is distributed in the hope that it will be useful, but WITH-  o
16 @c  OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY  o
17 @c  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License  o
18 @c  for  more details.  You should have  received  a copy of the GNU General  o
19 @c  Public License  distributed with GNAT;  see file COPYING.  If not, write  o
20 @c  to  the Free Software Foundation,  59 Temple Place - Suite 330,  Boston,  o
21 @c  MA 02111-1307, USA.                                                       o
22 @c                                                                            o
23 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
24
25 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
26 @c
27 @c                           GNAT_UGN Style Guide
28 @c
29 @c  1. Always put a @noindent on the line before the first paragraph
30 @c     after any of these commands:
31 @c
32 @c          @chapter
33 @c          @section
34 @c          @subsection
35 @c          @subsubsection
36 @c          @subsubsubsection
37 @c
38 @c          @end smallexample
39 @c          @end itemize
40 @c          @end enumerate
41 @c
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
57 @c
58 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
59 @c     command must be preceded by two empty lines
60 @c
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.
63 @c
64 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
65 @c     or "ali".
66 @c
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.
69 @c
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.
73 @c
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.
77 @c
78 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
79
80 @ifset vms
81 @setfilename gnat_ugn_vms.info
82 @end ifset
83
84 @ifset unw
85 @setfilename gnat_ugn_unw.info
86 @end ifset
87
88 @set FSFEDITION
89 @set EDITION GNAT
90
91 @ifset unw
92 @set PLATFORM
93 @set FILE gnat_ugn_unw
94 @end ifset
95
96 @ifset vms
97 @set PLATFORM OpenVMS
98 @set FILE gnat_ugn_vms
99 @end ifset
100
101 @settitle @value{EDITION} User's Guide @value{PLATFORM}
102 @dircategory GNU Ada tools
103 @direntry
104 * @value{EDITION} User's Guide (@value{FILE}) @value{PLATFORM}
105 @end direntry
106
107 @include gcc-common.texi
108
109 @setchapternewpage odd
110 @syncodeindex fn cp
111 @c %**end of header
112
113 @copying
114 Copyright @copyright{} 1995-2005, Free Software Foundation
115
116 Permission is granted to copy, distribute and/or modify this document
117 under the terms of the GNU Free Documentation License, Version 1.2
118 or any later version published by the Free Software Foundation;
119 with the Invariant Sections being ``GNU Free Documentation License'', with the
120 Front-Cover Texts being
121 ``@value{EDITION} User's Guide'',
122 and with no Back-Cover Texts.
123 A copy of the license is included in the section entitled
124 ``GNU Free Documentation License''.
125 @end copying
126
127 @titlepage
128
129 @title @value{EDITION} User's Guide
130
131 @ifset vms
132 @sp 1
133 @flushright
134 @titlefont{@i{@value{PLATFORM}}}
135 @end flushright
136 @end ifset
137
138 @sp 2
139
140 @subtitle GNAT, The GNU Ada 95 Compiler
141 @subtitle GCC version @value{version-GCC}
142
143 @author AdaCore
144
145 @page
146 @vskip 0pt plus 1filll
147
148 @insertcopying
149
150 @end titlepage
151
152 @ifnottex
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
155
156 @noindent
157 @value{EDITION} User's Guide @value{PLATFORM}
158
159 @noindent
160 GNAT, The GNU Ada 95 Compiler@*
161 GCC version @value{version-GCC}@*
162
163 @noindent
164 AdaCore@*
165
166 @menu
167 * About This Guide::
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling Using gcc::
171 * Binding Using gnatbind::
172 * Linking Using gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files Using gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions Using gnatname::
178 * GNAT Project Manager::
179 * The Cross-Referencing Tools gnatxref and gnatfind::
180 * The GNAT Pretty-Printer gnatpp::
181 * The GNAT Metric Tool gnatmetric::
182 * File Name Krunching Using gnatkr::
183 * Preprocessing Using gnatprep::
184 @ifset vms
185 * The GNAT Run-Time Library Builder gnatlbr::
186 @end ifset
187 * The GNAT Library Browser gnatls::
188 * Cleaning Up Using gnatclean::
189 @ifclear vms
190 * GNAT and Libraries::
191 * Using the GNU make Utility::
192 @end ifclear
193 * Memory Management Issues::
194 * Creating Sample Bodies Using gnatstub::
195 * Other Utility Programs::
196 * Running and Debugging Ada Programs::
197 @ifset vms
198 * Compatibility with DEC Ada::
199 @end ifset
200 * Platform-Specific Information for the Run-Time Libraries::
201 * Example of Binder Output File::
202 * Elaboration Order Handling in GNAT::
203 * Inline Assembler::
204 * Compatibility and Porting Guide::
205 @ifset unw
206 * Microsoft Windows Topics::
207 @end ifset
208 * GNU Free Documentation License::
209 * Index::
210
211  --- The Detailed Node Listing ---
212
213 About This Guide
214
215 * What This Guide Contains::
216 * What You Should Know before Reading This Guide::
217 * Related Information::
218 * Conventions::
219
220 Getting Started with GNAT
221
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
233
234 The GNAT Compilation Model
235
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
252
253 Foreign Language Representation
254
255 * Latin-1::
256 * Other 8-Bit Codes::
257 * Wide Character Encodings::
258
259 Compiling Ada Programs With gcc
260
261 * Compiling Programs::
262 * Switches for gcc::
263 * Search Paths and the Run-Time Library (RTL)::
264 * Order of Compilation Issues::
265 * Examples::
266
267 Switches for gcc
268
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 Different Versions of Ada::
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
290
291 Binding Ada Programs With gnatbind
292
293 * Running gnatbind::
294 * Switches for gnatbind::
295 * Command-Line Access::
296 * Search Paths for gnatbind::
297 * Examples of gnatbind Usage::
298
299 Switches for gnatbind
300
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::
307
308 Linking Using gnatlink
309
310 * Running gnatlink::
311 * Switches for gnatlink::
312 * Setting Stack Size from gnatlink::
313 * Setting Heap Size from gnatlink::
314
315 The GNAT Make Program gnatmake
316
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::
323
324 Improving Performance
325 * Performance Considerations::
326 * Reducing the Size of Ada Executables with gnatelim::
327
328 Performance Considerations
329 * Controlling Run-Time Checks::
330 * Use of Restrictions::
331 * Optimization Levels::
332 * Debugging Optimized Code::
333 * Inlining of Subprograms::
334 * Optimization and Strict Aliasing::
335 @ifset vms
336 * Coverage Analysis::
337 @end ifset
338
339 Reducing the Size of Ada Executables with gnatelim
340 * About gnatelim::
341 * Running gnatelim::
342 * Correcting the List of Eliminate Pragmas::
343 * Making Your Executables Smaller::
344 * Summary of the gnatelim Usage Cycle::
345
346 Renaming Files Using gnatchop
347
348 * Handling Files with Multiple Units::
349 * Operating gnatchop in Compilation Mode::
350 * Command Line for gnatchop::
351 * Switches for gnatchop::
352 * Examples of gnatchop Usage::
353
354 Configuration Pragmas
355
356 * Handling of Configuration Pragmas::
357 * The Configuration Pragmas Files::
358
359 Handling Arbitrary File Naming Conventions Using gnatname
360
361 * Arbitrary File Naming Conventions::
362 * Running gnatname::
363 * Switches for gnatname::
364 * Examples of gnatname Usage::
365
366 GNAT Project Manager
367
368 * Introduction::
369 * Examples of Project Files::
370 * Project File Syntax::
371 * Objects and Sources in Project Files::
372 * Importing Projects::
373 * Project Extension::
374 * Project Hierarchy Extension::
375 * External References in Project Files::
376 * Packages in Project Files::
377 * Variables from Imported Projects::
378 * Naming Schemes::
379 * Library Projects::
380 * Stand-alone Library Projects::
381 * Switches Related to Project Files::
382 * Tools Supporting Project Files::
383 * An Extended Example::
384 * Project File Complete Syntax::
385
386 The Cross-Referencing Tools gnatxref and gnatfind
387
388 * gnatxref Switches::
389 * gnatfind Switches::
390 * Project Files for gnatxref and gnatfind::
391 * Regular Expressions in gnatfind and gnatxref::
392 * Examples of gnatxref Usage::
393 * Examples of gnatfind Usage::
394
395 The GNAT Pretty-Printer gnatpp
396
397 * Switches for gnatpp::
398 * Formatting Rules::
399
400 The GNAT Metrics Tool gnatmetric
401
402 * Switches for gnatmetric::
403
404 File Name Krunching Using gnatkr
405
406 * About gnatkr::
407 * Using gnatkr::
408 * Krunching Method::
409 * Examples of gnatkr Usage::
410
411 Preprocessing Using gnatprep
412
413 * Using gnatprep::
414 * Switches for gnatprep::
415 * Form of Definitions File::
416 * Form of Input Text for gnatprep::
417
418 @ifset vms
419 The GNAT Run-Time Library Builder gnatlbr
420
421 * Running gnatlbr::
422 * Switches for gnatlbr::
423 * Examples of gnatlbr Usage::
424 @end ifset
425
426 The GNAT Library Browser gnatls
427
428 * Running gnatls::
429 * Switches for gnatls::
430 * Examples of gnatls Usage::
431
432 Cleaning Up Using gnatclean
433
434 * Running gnatclean::
435 * Switches for gnatclean::
436 * Examples of gnatclean Usage::
437
438 @ifclear vms
439
440 GNAT and Libraries
441
442 * Introduction to Libraries in GNAT::
443 * General Ada Libraries::
444 * Stand-alone Ada Libraries::
445 * Rebuilding the GNAT Run-Time Library::
446
447 Using the GNU make Utility
448
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
454
455 Memory Management Issues
456
457 * Some Useful Memory Pools::
458 * The GNAT Debug Pool Facility::
459 @ifclear vms
460 * The gnatmem Tool::
461 @end ifclear
462
463 Some Useful Memory Pools
464
465 The GNAT Debug Pool Facility
466
467 @ifclear vms
468 The gnatmem Tool
469
470 * Running gnatmem::
471 * Switches for gnatmem::
472 * Example of gnatmem Usage::
473 @end ifclear
474
475  Sample Bodies Using gnatstub
476
477 * Running gnatstub::
478 * Switches for gnatstub::
479
480 Other Utility Programs
481
482 * Using Other Utility Programs with GNAT::
483 * The External Symbol Naming Scheme of GNAT::
484 @ifclear vms
485 * Ada Mode for Glide::
486 @end ifclear
487 * Converting Ada Files to html with gnathtml::
488
489 Running and Debugging Ada Programs
490
491 * The GNAT Debugger GDB::
492 * Running GDB::
493 * Introduction to GDB Commands::
494 * Using Ada Expressions::
495 * Calling User-Defined Subprograms::
496 * Using the Next Command in a Function::
497 * Ada Exceptions::
498 * Ada Tasks::
499 * Debugging Generic Units::
500 * GNAT Abnormal Termination or Failure to Terminate::
501 * Naming Conventions for GNAT Source Files::
502 * Getting Internal Debugging Information::
503 * Stack Traceback::
504
505 @ifset vms
506 * LSE::
507 @end ifset
508
509 @ifset vms
510 Compatibility with DEC Ada
511
512 * Ada 95 Compatibility::
513 * Differences in the Definition of Package System::
514 * Language-Related Features::
515 * The Package STANDARD::
516 * The Package SYSTEM::
517 * Tasking and Task-Related Features::
518 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
519 * Pragmas and Pragma-Related Features::
520 * Library of Predefined Units::
521 * Bindings::
522 * Main Program Definition::
523 * Implementation-Defined Attributes::
524 * Compiler and Run-Time Interfacing::
525 * Program Compilation and Library Management::
526 * Input-Output::
527 * Implementation Limits::
528 * Tools::
529
530 Language-Related Features
531
532 * Integer Types and Representations::
533 * Floating-Point Types and Representations::
534 * Pragmas Float_Representation and Long_Float::
535 * Fixed-Point Types and Representations::
536 * Record and Array Component Alignment::
537 * Address Clauses::
538 * Other Representation Clauses::
539
540 Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
541
542 * Assigning Task IDs::
543 * Task IDs and Delays::
544 * Task-Related Pragmas::
545 * Scheduling and Task Priority::
546 * The Task Stack::
547 * External Interrupts::
548
549 Pragmas and Pragma-Related Features
550
551 * Restrictions on the Pragma INLINE::
552 * Restrictions on the Pragma INTERFACE::
553 * Restrictions on the Pragma SYSTEM_NAME::
554
555 Library of Predefined Units
556
557 * Changes to DECLIB::
558
559 Bindings
560
561 * Shared Libraries and Options Files::
562 * Interfaces to C::
563 @end ifset
564
565 Platform-Specific Information for the Run-Time Libraries
566
567 * Summary of Run-Time Configurations::
568 * Specifying a Run-Time Library::
569 * Choosing the Scheduling Policy::
570 * Solaris-Specific Considerations::
571 * IRIX-Specific Considerations::
572 * Linux-Specific Considerations::
573 * AIX-Specific Considerations::
574
575 Example of Binder Output File
576
577 Elaboration Order Handling in GNAT
578
579 * Elaboration Code in Ada 95::
580 * Checking the Elaboration Order in Ada 95::
581 * Controlling the Elaboration Order in Ada 95::
582 * Controlling Elaboration in GNAT - Internal Calls::
583 * Controlling Elaboration in GNAT - External Calls::
584 * Default Behavior in GNAT - Ensuring Safety::
585 * Treatment of Pragma Elaborate::
586 * Elaboration Issues for Library Tasks::
587 * Mixing Elaboration Models::
588 * What to Do If the Default Elaboration Behavior Fails::
589 * Elaboration for Access-to-Subprogram Values::
590 * Summary of Procedures for Elaboration Control::
591 * Other Elaboration Order Considerations::
592
593 Inline Assembler
594
595 * Basic Assembler Syntax::
596 * A Simple Example of Inline Assembler::
597 * Output Variables in Inline Assembler::
598 * Input Variables in Inline Assembler::
599 * Inlining Inline Assembler Code::
600 * Other Asm Functionality::
601
602 Compatibility and Porting Guide
603
604 * Compatibility with Ada 83::
605 * Implementation-dependent characteristics::
606 * Compatibility with DEC Ada 83::
607 * Compatibility with Other Ada 95 Systems::
608 * Representation Clauses::
609 @ifset vms
610 * Transitioning from Alpha to Integrity OpenVMS::
611 @end ifset
612
613 @ifset unw
614 Microsoft Windows Topics
615
616 * Using GNAT on Windows::
617 * CONSOLE and WINDOWS subsystems::
618 * Temporary Files::
619 * Mixed-Language Programming on Windows::
620 * Windows Calling Conventions::
621 * Introduction to Dynamic Link Libraries (DLLs)::
622 * Using DLLs with GNAT::
623 * Building DLLs with GNAT::
624 * GNAT and Windows Resources::
625 * Debugging a DLL::
626 * GNAT and COM/DCOM Objects::
627 @end ifset
628
629 * Index::
630 @end menu
631 @end ifnottex
632
633 @node About This Guide
634 @unnumbered About This Guide
635
636 @noindent
637 @ifset vms
638 This guide describes the use of @value{EDITION},
639 a full language compiler for the Ada
640 95 programming language, implemented on HP's Alpha and
641 Integrity (ia64) OpenVMS platforms.
642 @end ifset
643 @ifclear vms
644 This guide describes the use of @value{EDITION},
645 a compiler and software development
646 toolset for the full Ada 95 programming language.
647 @end ifclear
648 It describes the features of the compiler and tools, and details
649 how to use them to build Ada 95 applications.
650
651 @ifset PROEDITION
652 For ease of exposition, ``GNAT Pro'' will be referred to simply as
653 ``GNAT'' in the remainder of this document.
654 @end ifset
655
656 @menu
657 * What This Guide Contains::
658 * What You Should Know before Reading This Guide::
659 * Related Information::
660 * Conventions::
661 @end menu
662
663 @node What This Guide Contains
664 @unnumberedsec What This Guide Contains
665
666 @noindent
667 This guide contains the following chapters:
668 @itemize @bullet
669
670 @item
671 @ref{Getting Started with GNAT}, describes how to get started compiling
672 and running Ada programs with the GNAT Ada programming environment.
673 @item
674 @ref{The GNAT Compilation Model}, describes the compilation model used
675 by GNAT.
676
677 @item
678 @ref{Compiling Using gcc}, describes how to compile
679 Ada programs with @command{gcc}, the Ada compiler.
680
681 @item
682 @ref{Binding Using gnatbind}, describes how to
683 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
684 utility.
685
686 @item
687 @ref{Linking Using gnatlink},
688 describes @command{gnatlink}, a
689 program that provides for linking using the GNAT run-time library to
690 construct a program. @command{gnatlink} can also incorporate foreign language
691 object units into the executable.
692
693 @item
694 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
695 utility that automatically determines the set of sources
696 needed by an Ada compilation unit, and executes the necessary compilations
697 binding and link.
698
699 @item
700 @ref{Improving Performance}, shows various techniques for making your
701 Ada program run faster or take less space.
702 It discusses the effect of the compiler's optimization switch and
703 also describes the @command{gnatelim} tool.
704
705 @item
706 @ref{Renaming Files Using gnatchop}, describes
707 @code{gnatchop}, a utility that allows you to preprocess a file that
708 contains Ada source code, and split it into one or more new files, one
709 for each compilation unit.
710
711 @item
712 @ref{Configuration Pragmas}, describes the configuration pragmas
713 handled by GNAT.
714
715 @item
716 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
717 shows how to override the default GNAT file naming conventions,
718 either for an individual unit or globally.
719
720 @item
721 @ref{GNAT Project Manager}, describes how to use project files
722 to organize large projects.
723
724 @item
725 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
726 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
727 way to navigate through sources.
728
729 @item
730 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
731 version of an Ada source file with control over casing, indentation,
732 comment placement, and other elements of program presentation style.
733
734 @item
735 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
736 metrics for an Ada source file, such as the number of types and subprograms,
737 and assorted complexity measures.
738
739 @item
740 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
741 file name krunching utility, used to handle shortened
742 file names on operating systems with a limit on the length of names.
743
744 @item
745 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
746 preprocessor utility that allows a single source file to be used to
747 generate multiple or parameterized source files, by means of macro
748 substitution.
749
750 @ifset vms
751 @item
752 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
753 a tool for rebuilding the GNAT run time with user-supplied
754 configuration pragmas.
755 @end ifset
756
757 @item
758 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
759 utility that displays information about compiled units, including dependences
760 on the corresponding sources files, and consistency of compilations.
761
762 @item
763 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
764 to delete files that are produced by the compiler, binder and linker.
765
766 @ifclear vms
767 @item
768 @ref{GNAT and Libraries}, describes the process of creating and using
769 Libraries with GNAT. It also describes how to recompile the GNAT run-time
770 library.
771
772 @item
773 @ref{Using the GNU make Utility}, describes some techniques for using
774 the GNAT toolset in Makefiles.
775 @end ifclear
776
777 @item
778 @ref{Memory Management Issues}, describes some useful predefined storage pools
779 and in particular the GNAT Debug Pool facility, which helps detect incorrect
780 memory references.
781 @ifclear vms
782 It also describes @command{gnatmem}, a utility that monitors dynamic
783 allocation and deallocation and helps detect ``memory leaks''.
784 @end ifclear
785
786 @item
787 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
788 a utility that generates empty but compilable bodies for library units.
789
790 @item
791 @ref{Other Utility Programs}, discusses several other GNAT utilities,
792 including @code{gnathtml}.
793
794 @item
795 @ref{Running and Debugging Ada Programs}, describes how to run and debug
796 Ada programs.
797
798 @ifset vms
799 @item
800 @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
801 DEC Ada 83 @footnote{``DEC Ada'' refers to the legacy product originally
802 developed by Digital Equipment Corporation and currently supported by HP.}
803 for OpenVMS Alpha.
804 @end ifset
805
806 @item
807 @ref{Platform-Specific Information for the Run-Time Libraries},
808 describes the various run-time
809 libraries supported by GNAT on various platforms and explains how to
810 choose a particular library.
811
812 @item
813 @ref{Example of Binder Output File}, shows the source code for the binder
814 output file for a sample program.
815
816 @item
817 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
818 you deal with elaboration order issues.
819
820 @item
821 @ref{Inline Assembler}, shows how to use the inline assembly facility
822 in an Ada program.
823
824 @item
825 @ref{Compatibility and Porting Guide}, includes sections on compatibility
826 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
827 in porting code from other environments.
828
829 @ifset unw
830 @item
831 @ref{Microsoft Windows Topics}, presents information relevant to the
832 Microsoft Windows platform.
833 @end ifset
834 @end itemize
835
836 @c *************************************************
837 @node What You Should Know before Reading This Guide
838 @c *************************************************
839 @unnumberedsec What You Should Know before Reading This Guide
840
841 @cindex Ada 95 Language Reference Manual
842 @noindent
843 This user's guide assumes that you are familiar with Ada 95 language, as
844 described in the International Standard ANSI/ISO/IEC-8652:1995, January
845 1995.
846
847 @node Related Information
848 @unnumberedsec Related Information
849
850 @noindent
851 For further information about related tools, refer to the following
852 documents:
853
854 @itemize @bullet
855 @item
856 @cite{GNAT Reference Manual}, which contains all reference
857 material for the GNAT implementation of Ada 95.
858
859 @ifset unw
860 @item
861 @cite{Using the GNAT Programming System}, which describes the GPS
862 integrated development environment.
863
864 @item
865 @cite{GNAT Programming System Tutorial}, which introduces the
866 main GPS features through examples.
867 @end ifset
868
869 @item
870 @cite{Ada 95 Language Reference Manual}, which contains all reference
871 material for the Ada 95 programming language.
872
873 @item
874 @cite{Debugging with GDB}
875 @ifset vms
876 , located in the GNU:[DOCS] directory,
877 @end ifset
878 contains all details on the use of the GNU source-level debugger.
879
880 @item
881 @cite{GNU Emacs Manual}
882 @ifset vms
883 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
884 @end ifset
885 contains full information on the extensible editor and programming
886 environment Emacs.
887
888 @end itemize
889
890 @c **************
891 @node Conventions
892 @unnumberedsec Conventions
893 @cindex Conventions
894 @cindex Typographical conventions
895
896 @noindent
897 Following are examples of the typographical and graphic conventions used
898 in this guide:
899
900 @itemize @bullet
901 @item
902 @code{Functions}, @code{utility program names}, @code{standard names},
903 and @code{classes}.
904
905 @item
906 @samp{Option flags}
907
908 @item
909 @file{File Names}, @file{button names}, and @file{field names}.
910
911 @item
912 @var{Variables}.
913
914 @item
915 @emph{Emphasis}.
916
917 @item
918 [optional information or parameters]
919
920 @item
921 Examples are described by text
922 @smallexample
923 and then shown this way.
924 @end smallexample
925 @end itemize
926
927 @noindent
928 Commands that are entered by the user are preceded in this manual by the
929 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
930 uses this sequence as a prompt, then the commands will appear exactly as
931 you see them in the manual. If your system uses some other prompt, then
932 the command will appear with the @code{$} replaced by whatever prompt
933 character you are using.
934
935 @ifset unw
936 Full file names are shown with the ``@code{/}'' character
937 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
938 If you are using GNAT on a Windows platform, please note that
939 the ``@code{\}'' character should be used instead.
940 @end ifset
941
942 @c ****************************
943 @node Getting Started with GNAT
944 @chapter Getting Started with GNAT
945
946 @noindent
947 This chapter describes some simple ways of using GNAT to build
948 executable Ada programs.
949 @ifset unw
950 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
951 show how to use the command line environment.
952 @ref{Introduction to Glide and GVD}, provides a brief
953 introduction to the visually-oriented IDE for GNAT.
954 Supplementing Glide on some platforms is GPS, the
955 GNAT Programming System, which offers a richer graphical
956 ``look and feel'', enhanced configurability, support for
957 development in other programming language, comprehensive
958 browsing features, and many other capabilities.
959 For information on GPS please refer to
960 @cite{Using the GNAT Programming System}.
961 @end ifset
962
963 @menu
964 * Running GNAT::
965 * Running a Simple Ada Program::
966 * Running a Program with Multiple Units::
967 * Using the gnatmake Utility::
968 @ifset vms
969 * Editing with Emacs::
970 @end ifset
971 @ifclear vms
972 * Introduction to GPS::
973 * Introduction to Glide and GVD::
974 @end ifclear
975 @end menu
976
977 @node Running GNAT
978 @section Running GNAT
979
980 @noindent
981 Three steps are needed to create an executable file from an Ada source
982 file:
983
984 @enumerate
985 @item
986 The source file(s) must be compiled.
987 @item
988 The file(s) must be bound using the GNAT binder.
989 @item
990 All appropriate object files must be linked to produce an executable.
991 @end enumerate
992
993 @noindent
994 All three steps are most commonly handled by using the @command{gnatmake}
995 utility program that, given the name of the main program, automatically
996 performs the necessary compilation, binding and linking steps.
997
998 @node Running a Simple Ada Program
999 @section Running a Simple Ada Program
1000
1001 @noindent
1002 Any text editor may be used to prepare an Ada program.
1003 @ifclear vms
1004 If @code{Glide} is
1005 used, the optional Ada mode may be helpful in laying out the program.
1006 @end ifclear
1007 The
1008 program text is a normal text file. We will suppose in our initial
1009 example that you have used your editor to prepare the following
1010 standard format text file:
1011
1012 @smallexample @c ada
1013 @cartouche
1014 with Ada.Text_IO; use Ada.Text_IO;
1015 procedure Hello is
1016 begin
1017    Put_Line ("Hello WORLD!");
1018 end Hello;
1019 @end cartouche
1020 @end smallexample
1021
1022 @noindent
1023 This file should be named @file{hello.adb}.
1024 With the normal default file naming conventions, GNAT requires
1025 that each file
1026 contain a single compilation unit whose file name is the
1027 unit name,
1028 with periods replaced by hyphens; the
1029 extension is @file{ads} for a
1030 spec and @file{adb} for a body.
1031 You can override this default file naming convention by use of the
1032 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1033 Alternatively, if you want to rename your files according to this default
1034 convention, which is probably more convenient if you will be using GNAT
1035 for all your compilations, then the @code{gnatchop} utility
1036 can be used to generate correctly-named source files
1037 (@pxref{Renaming Files Using gnatchop}).
1038
1039 You can compile the program using the following command (@code{$} is used
1040 as the command prompt in the examples in this document):
1041
1042 @smallexample
1043 $ gcc -c hello.adb
1044 @end smallexample
1045
1046 @noindent
1047 @command{gcc} is the command used to run the compiler. This compiler is
1048 capable of compiling programs in several languages, including Ada 95 and
1049 C. It assumes that you have given it an Ada program if the file extension is
1050 either @file{.ads} or @file{.adb}, and it will then call
1051 the GNAT compiler to compile the specified file.
1052
1053 @ifclear vms
1054 The @option{-c} switch is required. It tells @command{gcc} to only do a
1055 compilation. (For C programs, @command{gcc} can also do linking, but this
1056 capability is not used directly for Ada programs, so the @option{-c}
1057 switch must always be present.)
1058 @end ifclear
1059
1060 This compile command generates a file
1061 @file{hello.o}, which is the object
1062 file corresponding to your Ada program. It also generates
1063 an ``Ada Library Information'' file @file{hello.ali},
1064 which contains additional information used to check
1065 that an Ada program is consistent.
1066 To build an executable file,
1067 use @code{gnatbind} to bind the program
1068 and @command{gnatlink} to link it. The
1069 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1070 @file{ALI} file, but the default extension of @file{.ali} can
1071 be omitted. This means that in the most common case, the argument
1072 is simply the name of the main program:
1073
1074 @smallexample
1075 $ gnatbind hello
1076 $ gnatlink hello
1077 @end smallexample
1078
1079 @noindent
1080 A simpler method of carrying out these steps is to use
1081 @command{gnatmake},
1082 a master program that invokes all the required
1083 compilation, binding and linking tools in the correct order. In particular,
1084 @command{gnatmake} automatically recompiles any sources that have been
1085 modified since they were last compiled, or sources that depend
1086 on such modified sources, so that ``version skew'' is avoided.
1087 @cindex Version skew (avoided by @command{gnatmake})
1088
1089 @smallexample
1090 $ gnatmake hello.adb
1091 @end smallexample
1092
1093 @noindent
1094 The result is an executable program called @file{hello}, which can be
1095 run by entering:
1096
1097 @c The following should be removed (BMB 2001-01-23)
1098 @c @smallexample
1099 @c $ ^./hello^$ RUN HELLO^
1100 @c @end smallexample
1101
1102 @smallexample
1103 $ hello
1104 @end smallexample
1105
1106 @noindent
1107 assuming that the current directory is on the search path
1108 for executable programs.
1109
1110 @noindent
1111 and, if all has gone well, you will see
1112
1113 @smallexample
1114 Hello WORLD!
1115 @end smallexample
1116
1117 @noindent
1118 appear in response to this command.
1119
1120 @c ****************************************
1121 @node Running a Program with Multiple Units
1122 @section Running a Program with Multiple Units
1123
1124 @noindent
1125 Consider a slightly more complicated example that has three files: a
1126 main program, and the spec and body of a package:
1127
1128 @smallexample @c ada
1129 @cartouche
1130 @group
1131 package Greetings is
1132    procedure Hello;
1133    procedure Goodbye;
1134 end Greetings;
1135
1136 with Ada.Text_IO; use Ada.Text_IO;
1137 package body Greetings is
1138    procedure Hello is
1139    begin
1140       Put_Line ("Hello WORLD!");
1141    end Hello;
1142
1143    procedure Goodbye is
1144    begin
1145       Put_Line ("Goodbye WORLD!");
1146    end Goodbye;
1147 end Greetings;
1148 @end group
1149
1150 @group
1151 with Greetings;
1152 procedure Gmain is
1153 begin
1154    Greetings.Hello;
1155    Greetings.Goodbye;
1156 end Gmain;
1157 @end group
1158 @end cartouche
1159 @end smallexample
1160
1161 @noindent
1162 Following the one-unit-per-file rule, place this program in the
1163 following three separate files:
1164
1165 @table @file
1166 @item greetings.ads
1167 spec of package @code{Greetings}
1168
1169 @item greetings.adb
1170 body of package @code{Greetings}
1171
1172 @item gmain.adb
1173 body of main program
1174 @end table
1175
1176 @noindent
1177 To build an executable version of
1178 this program, we could use four separate steps to compile, bind, and link
1179 the program, as follows:
1180
1181 @smallexample
1182 $ gcc -c gmain.adb
1183 $ gcc -c greetings.adb
1184 $ gnatbind gmain
1185 $ gnatlink gmain
1186 @end smallexample
1187
1188 @noindent
1189 Note that there is no required order of compilation when using GNAT.
1190 In particular it is perfectly fine to compile the main program first.
1191 Also, it is not necessary to compile package specs in the case where
1192 there is an accompanying body; you only need to compile the body. If you want
1193 to submit these files to the compiler for semantic checking and not code
1194 generation, then use the
1195 @option{-gnatc} switch:
1196
1197 @smallexample
1198 $ gcc -c greetings.ads -gnatc
1199 @end smallexample
1200
1201 @noindent
1202 Although the compilation can be done in separate steps as in the
1203 above example, in practice it is almost always more convenient
1204 to use the @command{gnatmake} tool. All you need to know in this case
1205 is the name of the main program's source file. The effect of the above four
1206 commands can be achieved with a single one:
1207
1208 @smallexample
1209 $ gnatmake gmain.adb
1210 @end smallexample
1211
1212 @noindent
1213 In the next section we discuss the advantages of using @command{gnatmake} in
1214 more detail.
1215
1216 @c *****************************
1217 @node Using the gnatmake Utility
1218 @section Using the @command{gnatmake} Utility
1219
1220 @noindent
1221 If you work on a program by compiling single components at a time using
1222 @command{gcc}, you typically keep track of the units you modify. In order to
1223 build a consistent system, you compile not only these units, but also any
1224 units that depend on the units you have modified.
1225 For example, in the preceding case,
1226 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1227 you edit @file{greetings.ads}, you must recompile both
1228 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1229 units that depend on @file{greetings.ads}.
1230
1231 @code{gnatbind} will warn you if you forget one of these compilation
1232 steps, so that it is impossible to generate an inconsistent program as a
1233 result of forgetting to do a compilation. Nevertheless it is tedious and
1234 error-prone to keep track of dependencies among units.
1235 One approach to handle the dependency-bookkeeping is to use a
1236 makefile. However, makefiles present maintenance problems of their own:
1237 if the dependencies change as you change the program, you must make
1238 sure that the makefile is kept up-to-date manually, which is also an
1239 error-prone process.
1240
1241 The @command{gnatmake} utility takes care of these details automatically.
1242 Invoke it using either one of the following forms:
1243
1244 @smallexample
1245 $ gnatmake gmain.adb
1246 $ gnatmake ^gmain^GMAIN^
1247 @end smallexample
1248
1249 @noindent
1250 The argument is the name of the file containing the main program;
1251 you may omit the extension. @command{gnatmake}
1252 examines the environment, automatically recompiles any files that need
1253 recompiling, and binds and links the resulting set of object files,
1254 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1255 In a large program, it
1256 can be extremely helpful to use @command{gnatmake}, because working out by hand
1257 what needs to be recompiled can be difficult.
1258
1259 Note that @command{gnatmake}
1260 takes into account all the Ada 95 rules that
1261 establish dependencies among units. These include dependencies that result
1262 from inlining subprogram bodies, and from
1263 generic instantiation. Unlike some other
1264 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1265 found by the compiler on a previous compilation, which may possibly
1266 be wrong when sources change. @command{gnatmake} determines the exact set of
1267 dependencies from scratch each time it is run.
1268
1269 @ifset vms
1270 @node Editing with Emacs
1271 @section Editing with Emacs
1272 @cindex Emacs
1273
1274 @noindent
1275 Emacs is an extensible self-documenting text editor that is available in a
1276 separate VMSINSTAL kit.
1277
1278 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1279 click on the Emacs Help menu and run the Emacs Tutorial.
1280 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1281 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1282
1283 Documentation on Emacs and other tools is available in Emacs under the
1284 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1285 use the middle mouse button to select a topic (e.g. Emacs).
1286
1287 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1288 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1289 get to the Emacs manual.
1290 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1291 prompt.
1292
1293 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1294 which is sufficiently extensible to provide for a complete programming
1295 environment and shell for the sophisticated user.
1296 @end ifset
1297
1298 @ifclear vms
1299 @node Introduction to GPS
1300 @section Introduction to GPS
1301 @cindex GPS (GNAT Programming System)
1302 @cindex GNAT Programming System (GPS)
1303 @noindent
1304 Although the command line interface (@command{gnatmake}, etc.) alone
1305 is sufficient, a graphical Interactive Development
1306 Environment can make it easier for you to compose, navigate, and debug
1307 programs.  This section describes the main features of GPS
1308 (``GNAT Programming System''), the GNAT graphical IDE.
1309 You will see how to use GPS to build and debug an executable, and
1310 you will also learn some of the basics of the GNAT ``project'' facility.
1311
1312 GPS enables you to do much more than is presented here;
1313 e.g., you can produce a call graph, interface to a third-party
1314 Version Control System, and inspect the generated assembly language
1315 for a program.
1316 Indeed, GPS also supports languages other than Ada.
1317 Such additional information, and an explanation of all of the GPS menu
1318 items. may be found in the on-line help, which includes
1319 a user's guide and a tutorial (these are also accessible from the GNAT
1320 startup menu).
1321
1322 @menu
1323 * Building a New Program with GPS::
1324 * Simple Debugging with GPS::
1325 @end menu
1326
1327 @node Building a New Program with GPS
1328 @subsection Building a New Program with GPS
1329 @noindent
1330 GPS invokes the GNAT compilation tools using information
1331 contained in a @emph{project} (also known as a @emph{project file}):
1332 a collection of properties such
1333 as source directories, identities of main subprograms, tool switches, etc.,
1334 and their associated values.
1335 See @ref{GNAT Project Manager} for details.
1336 In order to run GPS, you will need to either create a new project
1337 or else open an existing one.
1338
1339 This section will explain how you can use GPS to create a project,
1340 to associate Ada source files with a project, and to build and run
1341 programs.
1342
1343 @enumerate
1344 @item @emph{Creating a project}
1345
1346 Invoke GPS, either from the command line or the platform's IDE.
1347 After it starts, GPS will display a ``Welcome'' screen with three
1348 radio buttons:
1349
1350 @itemize @bullet
1351 @item
1352 @code{Start with default project in directory}
1353
1354 @item
1355 @code{Create new project with wizard}
1356
1357 @item
1358 @code{Open existing project}
1359 @end itemize
1360
1361 @noindent
1362 Select @code{Create new project with wizard} and press @code{OK}.
1363 A new window will appear.  In the text box labeled with
1364 @code{Enter the name of the project to create}, type @file{sample}
1365 as the project name.
1366 In the next box, browse to choose the directory in which you
1367 would like to create the project file.
1368 After selecting an appropriate directory, press @code{Forward}.
1369
1370 A window will appear with the title
1371 @code{Version Control System Configuration}.
1372 Simply press @code{Forward}.
1373
1374 A window will appear with the title
1375 @code{Please select the source directories for this project}.
1376 The directory that you specified for the project file will be selected
1377 by default as the one to use for sources; simply press @code{Forward}.
1378
1379 A window will appear with the title
1380 @code{Please select the build directory for this project}.
1381 The directory that you specified for the project file will be selected
1382 by default for object files and executables;
1383 simply press @code{Forward}.
1384
1385 A window will appear with the title
1386 @code{Please select the main units for this project}.
1387 You will supply this information later, after creating the source file.
1388 Simply press @code{Forward} for now.
1389
1390 A window will appear with the title
1391 @code{Please select the switches to build the project}.
1392 Press @code{Apply}.  This will create a project file named
1393 @file{sample.prj} in the directory that you had specified.
1394
1395 @item @emph{Creating and saving the source file}
1396
1397 After you create the new project, a GPS window will appear, which is
1398 partitioned into two main sections:
1399
1400 @itemize @bullet
1401 @item
1402 A @emph{Workspace area}, initially greyed out, which you will use for
1403 creating and editing source files
1404
1405 @item
1406 Directly below, a @emph{Messages area}, which initially displays a
1407 ``Welcome'' message.
1408 (If the Messages area is not visible, drag its border upward to expand it.)
1409 @end itemize
1410
1411 @noindent
1412 Select @code{File} on the menu bar, and then the @code{New} command.
1413 The Workspace area will become white, and you can now
1414 enter the source program explicitly.
1415 Type the following text
1416
1417 @smallexample @c ada
1418 @group
1419 with Ada.Text_IO; use Ada.Text_IO;
1420 procedure Hello is
1421 begin
1422   Put_Line("Hello from GPS!");
1423 end Hello;
1424 @end group
1425 @end smallexample
1426
1427 @noindent
1428 Select @code{File}, then @code{Save As}, and enter the source file name
1429 @file{hello.adb}.
1430 The file will be saved in the same directory you specified as the
1431 location of the default project file.
1432
1433 @item @emph{Updating the project file}
1434
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}.
1443
1444 @item @emph{Building and running the program}
1445
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.
1453
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}.
1458
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
1465
1466 @node Simple Debugging with GPS
1467 @subsection Simple Debugging with GPS
1468 @noindent
1469 This section illustrates basic debugging techniques (setting breakpoints,
1470 examining/modifying variables, single stepping).
1471
1472 @enumerate
1473 @item @emph{Opening a project}
1474
1475 Start GPS and select @code{Open existing project}; browse to
1476 specify the project file @file{sample.prj} that you had created in the
1477 earlier example.
1478
1479 @item @emph{Creating a source file}
1480
1481 Select @code{File}, then @code{New}, and type in the following program:
1482
1483 @smallexample @c ada
1484 @group
1485 with Ada.Text_IO; use Ada.Text_IO;
1486 procedure Example is
1487    Line : String (1..80);
1488    N    : Natural;
1489 begin
1490    Put_Line("Type a line of text at each prompt; an empty line to exit");
1491    loop
1492       Put(": ");
1493       Get_Line (Line, N);
1494       Put_Line (Line (1..N) );
1495       exit when N=0;
1496    end loop;
1497 end Example;
1498 @end group
1499 @end smallexample
1500
1501 @noindent
1502 Select @code{File}, then @code{Save as}, and enter the file name
1503 @file{example.adb}.
1504
1505 @item @emph{Updating the project file}
1506
1507 Add @code{Example} as a new main unit for the project:
1508 @enumerate a
1509 @item
1510 Select @code{Project}, then @code{Edit Project Properties}.
1511
1512 @item
1513 Select the @code{Main files} tab, click @code{Add}, then
1514 select the file @file{example.adb} from the list, and
1515 click @code{Open}.
1516 You will see the file name appear in the list of main units
1517
1518 @item
1519 Click @code{OK}
1520 @end enumerate
1521
1522 @item @emph{Building/running the executable}
1523
1524 To build the executable
1525 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1526
1527 Run the program to see its effect (in the Messages area).
1528 Each line that you enter is displayed; an empty line will
1529 cause the loop to exit and the program to terminate.
1530
1531 @item @emph{Debugging the program}
1532
1533 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1534 which are required for debugging, are on by default when you create
1535 a new project.
1536 Thus unless you intentionally remove these settings, you will be able
1537 to debug any program that you develop using GPS.
1538
1539 @enumerate a
1540 @item @emph{Initializing}
1541
1542 Select @code{Debug}, then @code{Initialize}, then @file{example}
1543
1544 @item @emph{Setting a breakpoint}
1545
1546 After performing the initialization step, you will observe a small
1547 icon to the right of each line number.
1548 This serves as a toggle for breakpoints; clicking the icon will
1549 set a breakpoint at the corresponding line (the icon will change to
1550 a red circle with an ``x''), and clicking it again
1551 will remove the breakpoint / reset the icon.
1552
1553 For purposes of this example, set a breakpoint at line 10 (the
1554 statement @code{Put_Line@ (Line@ (1..N));}
1555
1556 @item @emph{Starting program execution}
1557
1558 Select @code{Debug}, then @code{Run}.  When the
1559 @code{Program Arguments} window appears, click @code{OK}.
1560 A console window will appear; enter some line of text,
1561 e.g. @code{abcde}, at the prompt.
1562 The program will pause execution when it gets to the
1563 breakpoint, and the corresponding line is highlighted.
1564
1565 @item @emph{Examining a variable}
1566
1567 Move the mouse over one of the occurrences of the variable @code{N}.
1568 You will see the value (5) displayed, in ``tool tip'' fashion.
1569 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1570 You will see information about @code{N} appear in the @code{Debugger Data}
1571 pane, showing the value as 5.
1572
1573 @item @emph{Assigning a new value to a variable}
1574
1575 Right click on the @code{N} in the @code{Debugger Data} pane, and
1576 select @code{Set value of N}.
1577 When the input window appears, enter the value @code{4} and click
1578 @code{OK}.
1579 This value does not automatically appear in the @code{Debugger Data}
1580 pane; to see it, right click again on the @code{N} in the
1581 @code{Debugger Data} pane and select @code{Update value}.
1582 The new value, 4, will appear in red.
1583
1584 @item @emph{Single stepping}
1585
1586 Select @code{Debug}, then @code{Next}.
1587 This will cause the next statement to be executed, in this case the
1588 call of @code{Put_Line} with the string slice.
1589 Notice in the console window that the displayed string is simply
1590 @code{abcd} and not @code{abcde} which you had entered.
1591 This is because the upper bound of the slice is now 4 rather than 5.
1592
1593 @item @emph{Removing a breakpoint}
1594
1595 Toggle the breakpoint icon at line 10.
1596
1597 @item @emph{Resuming execution from a breakpoint}
1598
1599 Select @code{Debug}, then @code{Continue}.
1600 The program will reach the next iteration of the loop, and
1601 wait for input after displaying the prompt.
1602 This time, just hit the @kbd{Enter} key.
1603 The value of @code{N} will be 0, and the program will terminate.
1604 The console window will disappear.
1605 @end enumerate
1606 @end enumerate
1607
1608 @node Introduction to Glide and GVD
1609 @section Introduction to Glide and GVD
1610 @cindex Glide
1611 @cindex GVD
1612 @noindent
1613 This section describes the main features of Glide,
1614 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1615 the GNU Visual Debugger.
1616 These tools may be present in addition to, or in place of, GPS on some
1617 platforms.
1618 Additional information on Glide and GVD may be found
1619 in the on-line help for these tools.
1620
1621 @menu
1622 * Building a New Program with Glide::
1623 * Simple Debugging with GVD::
1624 * Other Glide Features::
1625 @end menu
1626
1627 @node Building a New Program with Glide
1628 @subsection Building a New Program with Glide
1629 @noindent
1630 The simplest way to invoke Glide is to enter @command{glide}
1631 at the command prompt.  It will generally be useful to issue this
1632 as a background command, thus allowing you to continue using
1633 your command window for other purposes while Glide is running:
1634
1635 @smallexample
1636 $ glide&
1637 @end smallexample
1638
1639 @noindent
1640 Glide will start up with an initial screen displaying the top-level menu items
1641 as well as some other information.  The menu selections are as follows
1642 @itemize @bullet
1643 @item @code{Buffers}
1644 @item @code{Files}
1645 @item @code{Tools}
1646 @item @code{Edit}
1647 @item @code{Search}
1648 @item @code{Mule}
1649 @item @code{Glide}
1650 @item @code{Help}
1651 @end itemize
1652
1653 @noindent
1654 For this introductory example, you will need to create a new Ada source file.
1655 First, select the @code{Files} menu.  This will pop open a menu with around
1656 a dozen or so items.  To create a file, select the @code{Open file...} choice.
1657 Depending on the platform, you may see a pop-up window where you can browse
1658 to an appropriate directory and then enter the file name, or else simply
1659 see a line at the bottom of the Glide window where you can likewise enter
1660 the file name.  Note that in Glide, when you attempt to open a non-existent
1661 file, the effect is to create a file with that name.  For this example enter
1662 @file{hello.adb} as the name of the file.
1663
1664 A new buffer will now appear, occupying the entire Glide window,
1665 with the file name at the top.  The menu selections are slightly different
1666 from the ones you saw on the opening screen; there is an @code{Entities} item,
1667 and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses
1668 the file extension to identify the source language, so @file{adb} indicates
1669 an Ada source file.
1670
1671 You will enter some of the source program lines explicitly,
1672 and use the syntax-oriented template mechanism to enter other lines.
1673 First, type the following text:
1674 @smallexample
1675 with Ada.Text_IO; use Ada.Text_IO;
1676 procedure Hello is
1677 begin
1678 @end smallexample
1679
1680 @noindent
1681 Observe that Glide uses different colors to distinguish reserved words from
1682 identifiers.  Also, after the @code{procedure Hello is} line, the cursor is
1683 automatically indented in anticipation of declarations.  When you enter
1684 @code{begin}, Glide recognizes that there are no declarations and thus places
1685 @code{begin} flush left.  But after the @code{begin} line the cursor is again
1686 indented, where the statement(s) will be placed.
1687
1688 The main part of the program will be a @code{for} loop.  Instead of entering
1689 the text explicitly, however, use a statement template.  Select the @code{Ada}
1690 item on the top menu bar, move the mouse to the @code{Statements} item,
1691 and you will see a large selection of alternatives.  Choose @code{for loop}.
1692 You will be prompted (at the bottom of the buffer) for a loop name;
1693 simply press the @key{Enter} key since a loop name is not needed.
1694 You should see the beginning of a @code{for} loop appear in the source
1695 program window.  You will now be prompted for the name of the loop variable;
1696 enter a line with the identifier @code{ind} (lower case).  Note that,
1697 by default, Glide capitalizes the name (you can override such behavior
1698 if you wish, although this is outside the scope of this introduction).
1699 Next, Glide prompts you for the loop range; enter a line containing
1700 @code{1..5} and you will see this also appear in the source program,
1701 together with the remaining elements of the @code{for} loop syntax.
1702
1703 Next enter the statement (with an intentional error, a missing semicolon)
1704 that will form the body of the loop:
1705 @smallexample
1706 Put_Line("Hello, World" & Integer'Image(I))
1707 @end smallexample
1708
1709 @noindent
1710 Finally, type @code{end Hello;} as the last line in the program.
1711 Now save the file: choose the @code{File} menu item, and then the
1712 @code{Save buffer} selection.  You will see a message at the bottom
1713 of the buffer confirming that the file has been saved.
1714
1715 You are now ready to attempt to build the program.  Select the @code{Ada}
1716 item from the top menu bar.  Although we could choose simply to compile
1717 the file, we will instead attempt to do a build (which invokes
1718 @command{gnatmake}) since, if the compile is successful, we want to build
1719 an executable.  Thus select @code{Ada build}.  This will fail because of the
1720 compilation error, and you will notice that the Glide window has been split:
1721 the top window contains the source file, and the bottom window contains the
1722 output from the GNAT tools. Glide allows you to navigate from a compilation
1723 error to the source file position corresponding to the error: click the
1724 middle mouse button (or simultaneously press the left and right buttons,
1725 on a two-button mouse) on the diagnostic line in the tool window.  The
1726 focus will shift to the source window, and the cursor will be positioned
1727 on the character at which the error was detected.
1728
1729 Correct the error: type in a semicolon to terminate the statement.
1730 Although you can again save the file explicitly, you can also simply invoke
1731 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1732 This time the build will succeed; the tool output window shows you the
1733 options that are supplied by default.  The GNAT tools' output (e.g.
1734 object and ALI files, executable) will go in the directory from which
1735 Glide was launched.
1736
1737 To execute the program, choose @code{Ada} and then @code{Run}.
1738 You should see the program's output displayed in the bottom window:
1739
1740 @smallexample
1741 Hello, world 1
1742 Hello, world 2
1743 Hello, world 3
1744 Hello, world 4
1745 Hello, world 5
1746 @end smallexample
1747
1748 @node Simple Debugging with GVD
1749 @subsection Simple Debugging with GVD
1750
1751 @noindent
1752 This section describes how to set breakpoints, examine/modify variables,
1753 and step through execution.
1754
1755 In order to enable debugging, you need to pass the @option{-g} switch
1756 to both the compiler and to @command{gnatlink}.  If you are using
1757 the command line, passing @option{-g} to @command{gnatmake} will have
1758 this effect.  You can then launch GVD, e.g. on the @code{hello} program,
1759 by issuing the command:
1760
1761 @smallexample
1762 $ gvd hello
1763 @end smallexample
1764
1765 @noindent
1766 If you are using Glide, then @option{-g} is passed to the relevant tools
1767 by default when you do a build.  Start the debugger by selecting the
1768 @code{Ada} menu item, and then @code{Debug}.
1769
1770 GVD comes up in a multi-part window.  One pane shows the names of files
1771 comprising your executable; another pane shows the source code of the current
1772 unit (initially your main subprogram), another pane shows the debugger output
1773 and user interactions, and the fourth pane (the data canvas at the top
1774 of the window) displays data objects that you have selected.
1775
1776 To the left of the source file pane, you will notice green dots adjacent
1777 to some lines.  These are lines for which object code exists and where
1778 breakpoints can thus be set.  You set/reset a breakpoint by clicking
1779 the green dot.  When a breakpoint is set, the dot is replaced by an @code{X}
1780 in a red circle.  Clicking the circle toggles the breakpoint off,
1781 and the red circle is replaced by the green dot.
1782
1783 For this example, set a breakpoint at the statement where @code{Put_Line}
1784 is invoked.
1785
1786 Start program execution by selecting the @code{Run} button on the top menu bar.
1787 (The @code{Start} button will also start your program, but it will
1788 cause program execution to break at the entry to your main subprogram.)
1789 Evidence of reaching the breakpoint will appear: the source file line will be
1790 highlighted, and the debugger interactions pane will display
1791 a relevant message.
1792
1793 You can examine the values of variables in several ways.  Move the mouse
1794 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1795 the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind}
1796 and select @code{Display Ind}; a box showing the variable's name and value
1797 will appear in the data canvas.
1798
1799 Although a loop index is a constant with respect to Ada semantics,
1800 you can change its value in the debugger.  Right-click in the box
1801 for @code{Ind}, and select the @code{Set Value of Ind} item.
1802 Enter @code{2} as the new value, and press @command{OK}.
1803 The box for @code{Ind} shows the update.
1804
1805 Press the @code{Step} button on the top menu bar; this will step through
1806 one line of program text (the invocation of @code{Put_Line}), and you can
1807 observe the effect of having modified @code{Ind} since the value displayed
1808 is @code{2}.
1809
1810 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1811 button.  You will see the remaining output lines displayed in the debugger
1812 interaction window, along with a message confirming normal program
1813 termination.
1814
1815 @node Other Glide Features
1816 @subsection Other Glide Features
1817
1818 @noindent
1819 You may have observed that some of the menu selections contain abbreviations;
1820 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1821 These are @emph{shortcut keys} that you can use instead of selecting
1822 menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1823 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1824 of selecting @code{Files} and then @code{Open file...}.
1825
1826 To abort a Glide command, type @key{Ctrl-g}.
1827
1828 If you want Glide to start with an existing source file, you can either
1829 launch Glide as above and then open the file via @code{Files} @result{}
1830 @code{Open file...}, or else simply pass the name of the source file
1831 on the command line:
1832
1833 @smallexample
1834 $ glide hello.adb&
1835 @end smallexample
1836
1837 @noindent
1838 While you are using Glide, a number of @emph{buffers} exist.
1839 You create some explicitly; e.g., when you open/create a file.
1840 Others arise as an effect of the commands that you issue; e.g., the buffer
1841 containing the output of the tools invoked during a build.  If a buffer
1842 is hidden, you can bring it into a visible window by first opening
1843 the @code{Buffers} menu and then selecting the desired entry.
1844
1845 If a buffer occupies only part of the Glide screen and you want to expand it
1846 to fill the entire screen, then click in the buffer and then select
1847 @code{Files} @result{} @code{One Window}.
1848
1849 If a window is occupied by one buffer and you want to split the window
1850 to bring up a second buffer, perform the following steps:
1851 @itemize @bullet
1852 @item Select @code{Files} @result{} @code{Split Window};
1853 this will produce two windows each of which holds the original buffer
1854 (these are not copies, but rather different views of the same buffer contents)
1855
1856 @item With the focus in one of the windows,
1857 select the desired buffer from the @code{Buffers} menu
1858 @end itemize
1859
1860 @noindent
1861 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1862 @end ifclear
1863
1864 @node The GNAT Compilation Model
1865 @chapter The GNAT Compilation Model
1866 @cindex GNAT compilation model
1867 @cindex Compilation model
1868
1869 @menu
1870 * Source Representation::
1871 * Foreign Language Representation::
1872 * File Naming Rules::
1873 * Using Other File Names::
1874 * Alternative File Naming Schemes::
1875 * Generating Object Files::
1876 * Source Dependencies::
1877 * The Ada Library Information Files::
1878 * Binding an Ada Program::
1879 * Mixed Language Programming::
1880 * Building Mixed Ada & C++ Programs::
1881 * Comparison between GNAT and C/C++ Compilation Models::
1882 * Comparison between GNAT and Conventional Ada Library Models::
1883 @ifset vms
1884 * Placement of temporary files::
1885 @end ifset
1886 @end menu
1887
1888 @noindent
1889 This chapter describes the compilation model used by GNAT. Although
1890 similar to that used by other languages, such as C and C++, this model
1891 is substantially different from the traditional Ada compilation models,
1892 which are based on a library. The model is initially described without
1893 reference to the library-based model. If you have not previously used an
1894 Ada compiler, you need only read the first part of this chapter. The
1895 last section describes and discusses the differences between the GNAT
1896 model and the traditional Ada compiler models. If you have used other
1897 Ada compilers, this section will help you to understand those
1898 differences, and the advantages of the GNAT model.
1899
1900 @node Source Representation
1901 @section Source Representation
1902 @cindex Latin-1
1903
1904 @noindent
1905 Ada source programs are represented in standard text files, using
1906 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1907 7-bit ASCII set, plus additional characters used for
1908 representing foreign languages (@pxref{Foreign Language Representation}
1909 for support of non-USA character sets). The format effector characters
1910 are represented using their standard ASCII encodings, as follows:
1911
1912 @table @code
1913 @item VT
1914 @findex VT
1915 Vertical tab, @code{16#0B#}
1916
1917 @item HT
1918 @findex HT
1919 Horizontal tab, @code{16#09#}
1920
1921 @item CR
1922 @findex CR
1923 Carriage return, @code{16#0D#}
1924
1925 @item LF
1926 @findex LF
1927 Line feed, @code{16#0A#}
1928
1929 @item FF
1930 @findex FF
1931 Form feed, @code{16#0C#}
1932 @end table
1933
1934 @noindent
1935 Source files are in standard text file format. In addition, GNAT will
1936 recognize a wide variety of stream formats, in which the end of
1937 physical lines is marked by any of the following sequences:
1938 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1939 in accommodating files that are imported from other operating systems.
1940
1941 @cindex End of source file
1942 @cindex Source file, end
1943 @findex SUB
1944 The end of a source file is normally represented by the physical end of
1945 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1946 recognized as signalling the end of the source file. Again, this is
1947 provided for compatibility with other operating systems where this
1948 code is used to represent the end of file.
1949
1950 Each file contains a single Ada compilation unit, including any pragmas
1951 associated with the unit. For example, this means you must place a
1952 package declaration (a package @dfn{spec}) and the corresponding body in
1953 separate files. An Ada @dfn{compilation} (which is a sequence of
1954 compilation units) is represented using a sequence of files. Similarly,
1955 you will place each subunit or child unit in a separate file.
1956
1957 @node Foreign Language Representation
1958 @section Foreign Language Representation
1959
1960 @noindent
1961 GNAT supports the standard character sets defined in Ada 95 as well as
1962 several other non-standard character sets for use in localized versions
1963 of the compiler (@pxref{Character Set Control}).
1964 @menu
1965 * Latin-1::
1966 * Other 8-Bit Codes::
1967 * Wide Character Encodings::
1968 @end menu
1969
1970 @node Latin-1
1971 @subsection Latin-1
1972 @cindex Latin-1
1973
1974 @noindent
1975 The basic character set is Latin-1. This character set is defined by ISO
1976 standard 8859, part 1. The lower half (character codes @code{16#00#}
1977 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1978 is used to represent additional characters. These include extended letters
1979 used by European languages, such as French accents, the vowels with umlauts
1980 used in German, and the extra letter A-ring used in Swedish.
1981
1982 @findex Ada.Characters.Latin_1
1983 For a complete list of Latin-1 codes and their encodings, see the source
1984 file of library unit @code{Ada.Characters.Latin_1} in file
1985 @file{a-chlat1.ads}.
1986 You may use any of these extended characters freely in character or
1987 string literals. In addition, the extended characters that represent
1988 letters can be used in identifiers.
1989
1990 @node Other 8-Bit Codes
1991 @subsection Other 8-Bit Codes
1992
1993 @noindent
1994 GNAT also supports several other 8-bit coding schemes:
1995
1996 @table @asis
1997 @item ISO 8859-2 (Latin-2)
1998 @cindex Latin-2
1999 @cindex ISO 8859-2
2000 Latin-2 letters allowed in identifiers, with uppercase and lowercase
2001 equivalence.
2002
2003 @item ISO 8859-3 (Latin-3)
2004 @cindex Latin-3
2005 @cindex ISO 8859-3
2006 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2007 equivalence.
2008
2009 @item ISO 8859-4 (Latin-4)
2010 @cindex Latin-4
2011 @cindex ISO 8859-4
2012 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2013 equivalence.
2014
2015 @item ISO 8859-5 (Cyrillic)
2016 @cindex ISO 8859-5
2017 @cindex Cyrillic
2018 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2019 lowercase equivalence.
2020
2021 @item ISO 8859-15 (Latin-9)
2022 @cindex ISO 8859-15
2023 @cindex Latin-9
2024 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2025 lowercase equivalence
2026
2027 @item IBM PC (code page 437)
2028 @cindex code page 437
2029 This code page is the normal default for PCs in the U.S. It corresponds
2030 to the original IBM PC character set. This set has some, but not all, of
2031 the extended Latin-1 letters, but these letters do not have the same
2032 encoding as Latin-1. In this mode, these letters are allowed in
2033 identifiers with uppercase and lowercase equivalence.
2034
2035 @item IBM PC (code page 850)
2036 @cindex code page 850
2037 This code page is a modification of 437 extended to include all the
2038 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2039 mode, all these letters are allowed in identifiers with uppercase and
2040 lowercase equivalence.
2041
2042 @item Full Upper 8-bit
2043 Any character in the range 80-FF allowed in identifiers, and all are
2044 considered distinct. In other words, there are no uppercase and lowercase
2045 equivalences in this range. This is useful in conjunction with
2046 certain encoding schemes used for some foreign character sets (e.g.
2047 the typical method of representing Chinese characters on the PC).
2048
2049 @item No Upper-Half
2050 No upper-half characters in the range 80-FF are allowed in identifiers.
2051 This gives Ada 83 compatibility for identifier names.
2052 @end table
2053
2054 @noindent
2055 For precise data on the encodings permitted, and the uppercase and lowercase
2056 equivalences that are recognized, see the file @file{csets.adb} in
2057 the GNAT compiler sources. You will need to obtain a full source release
2058 of GNAT to obtain this file.
2059
2060 @node Wide Character Encodings
2061 @subsection Wide Character Encodings
2062
2063 @noindent
2064 GNAT allows wide character codes to appear in character and string
2065 literals, and also optionally in identifiers, by means of the following
2066 possible encoding schemes:
2067
2068 @table @asis
2069
2070 @item Hex Coding
2071 In this encoding, a wide character is represented by the following five
2072 character sequence:
2073
2074 @smallexample
2075 ESC a b c d
2076 @end smallexample
2077
2078 @noindent
2079 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2080 characters (using uppercase letters) of the wide character code. For
2081 example, ESC A345 is used to represent the wide character with code
2082 @code{16#A345#}.
2083 This scheme is compatible with use of the full Wide_Character set.
2084
2085 @item Upper-Half Coding
2086 @cindex Upper-Half Coding
2087 The wide character with encoding @code{16#abcd#} where the upper bit is on
2088 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2089 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2090 character, but is not required to be in the upper half. This method can
2091 be also used for shift-JIS or EUC, where the internal coding matches the
2092 external coding.
2093
2094 @item Shift JIS Coding
2095 @cindex Shift JIS Coding
2096 A wide character is represented by a two-character sequence,
2097 @code{16#ab#} and
2098 @code{16#cd#}, with the restrictions described for upper-half encoding as
2099 described above. The internal character code is the corresponding JIS
2100 character according to the standard algorithm for Shift-JIS
2101 conversion. Only characters defined in the JIS code set table can be
2102 used with this encoding method.
2103
2104 @item EUC Coding
2105 @cindex EUC Coding
2106 A wide character is represented by a two-character sequence
2107 @code{16#ab#} and
2108 @code{16#cd#}, with both characters being in the upper half. The internal
2109 character code is the corresponding JIS character according to the EUC
2110 encoding algorithm. Only characters defined in the JIS code set table
2111 can be used with this encoding method.
2112
2113 @item UTF-8 Coding
2114 A wide character is represented using
2115 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2116 10646-1/Am.2. Depending on the character value, the representation
2117 is a one, two, or three byte sequence:
2118 @smallexample
2119 @iftex
2120 @leftskip=.7cm
2121 @end iftex
2122 16#0000#-16#007f#: 2#0xxxxxxx#
2123 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2124 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2125
2126 @end smallexample
2127
2128 @noindent
2129 where the xxx bits correspond to the left-padded bits of the
2130 16-bit character value. Note that all lower half ASCII characters
2131 are represented as ASCII bytes and all upper half characters and
2132 other wide characters are represented as sequences of upper-half
2133 (The full UTF-8 scheme allows for encoding 31-bit characters as
2134 6-byte sequences, but in this implementation, all UTF-8 sequences
2135 of four or more bytes length will be treated as illegal).
2136 @item Brackets Coding
2137 In this encoding, a wide character is represented by the following eight
2138 character sequence:
2139
2140 @smallexample
2141 [ " a b c d " ]
2142 @end smallexample
2143
2144 @noindent
2145 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2146 characters (using uppercase letters) of the wide character code. For
2147 example, [``A345''] is used to represent the wide character with code
2148 @code{16#A345#}. It is also possible (though not required) to use the
2149 Brackets coding for upper half characters. For example, the code
2150 @code{16#A3#} can be represented as @code{[``A3'']}.
2151
2152 This scheme is compatible with use of the full Wide_Character set,
2153 and is also the method used for wide character encoding in the standard
2154 ACVC (Ada Compiler Validation Capability) test suite distributions.
2155
2156 @end table
2157
2158 @noindent
2159 Note: Some of these coding schemes do not permit the full use of the
2160 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2161 use of the upper half of the Latin-1 set.
2162
2163 @node File Naming Rules
2164 @section File Naming Rules
2165
2166 @noindent
2167 The default file name is determined by the name of the unit that the
2168 file contains. The name is formed by taking the full expanded name of
2169 the unit and replacing the separating dots with hyphens and using
2170 ^lowercase^uppercase^ for all letters.
2171
2172 An exception arises if the file name generated by the above rules starts
2173 with one of the characters
2174 @ifset vms
2175 A,G,I, or S,
2176 @end ifset
2177 @ifclear vms
2178 a,g,i, or s,
2179 @end ifclear
2180 and the second character is a
2181 minus. In this case, the character ^tilde^dollar sign^ is used in place
2182 of the minus. The reason for this special rule is to avoid clashes with
2183 the standard names for child units of the packages System, Ada,
2184 Interfaces, and GNAT, which use the prefixes
2185 @ifset vms
2186 S- A- I- and G-
2187 @end ifset
2188 @ifclear vms
2189 s- a- i- and g-
2190 @end ifclear
2191 respectively.
2192
2193 The file extension is @file{.ads} for a spec and
2194 @file{.adb} for a body. The following list shows some
2195 examples of these rules.
2196
2197 @table @file
2198 @item main.ads
2199 Main (spec)
2200 @item main.adb
2201 Main (body)
2202 @item arith_functions.ads
2203 Arith_Functions (package spec)
2204 @item arith_functions.adb
2205 Arith_Functions (package body)
2206 @item func-spec.ads
2207 Func.Spec (child package spec)
2208 @item func-spec.adb
2209 Func.Spec (child package body)
2210 @item main-sub.adb
2211 Sub (subunit of Main)
2212 @item ^a~bad.adb^A$BAD.ADB^
2213 A.Bad (child package body)
2214 @end table
2215
2216 @noindent
2217 Following these rules can result in excessively long
2218 file names if corresponding
2219 unit names are long (for example, if child units or subunits are
2220 heavily nested). An option is available to shorten such long file names
2221 (called file name ``krunching''). This may be particularly useful when
2222 programs being developed with GNAT are to be used on operating systems
2223 with limited file name lengths. @xref{Using gnatkr}.
2224
2225 Of course, no file shortening algorithm can guarantee uniqueness over
2226 all possible unit names; if file name krunching is used, it is your
2227 responsibility to ensure no name clashes occur. Alternatively you
2228 can specify the exact file names that you want used, as described
2229 in the next section. Finally, if your Ada programs are migrating from a
2230 compiler with a different naming convention, you can use the gnatchop
2231 utility to produce source files that follow the GNAT naming conventions.
2232 (For details @pxref{Renaming Files Using gnatchop}.)
2233
2234 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2235 systems, case is not significant. So for example on @code{Windows XP}
2236 if the canonical name is @code{main-sub.adb}, you can use the file name
2237 @code{Main-Sub.adb} instead. However, case is significant for other
2238 operating systems, so for example, if you want to use other than
2239 canonically cased file names on a Unix system, you need to follow
2240 the procedures described in the next section.
2241
2242 @node Using Other File Names
2243 @section Using Other File Names
2244 @cindex File names
2245
2246 @noindent
2247 In the previous section, we have described the default rules used by
2248 GNAT to determine the file name in which a given unit resides. It is
2249 often convenient to follow these default rules, and if you follow them,
2250 the compiler knows without being explicitly told where to find all
2251 the files it needs.
2252
2253 However, in some cases, particularly when a program is imported from
2254 another Ada compiler environment, it may be more convenient for the
2255 programmer to specify which file names contain which units. GNAT allows
2256 arbitrary file names to be used by means of the Source_File_Name pragma.
2257 The form of this pragma is as shown in the following examples:
2258 @cindex Source_File_Name pragma
2259
2260 @smallexample @c ada
2261 @cartouche
2262 pragma Source_File_Name (My_Utilities.Stacks,
2263   Spec_File_Name => "myutilst_a.ada");
2264 pragma Source_File_name (My_Utilities.Stacks,
2265   Body_File_Name => "myutilst.ada");
2266 @end cartouche
2267 @end smallexample
2268
2269 @noindent
2270 As shown in this example, the first argument for the pragma is the unit
2271 name (in this example a child unit). The second argument has the form
2272 of a named association. The identifier
2273 indicates whether the file name is for a spec or a body;
2274 the file name itself is given by a string literal.
2275
2276 The source file name pragma is a configuration pragma, which means that
2277 normally it will be placed in the @file{gnat.adc}
2278 file used to hold configuration
2279 pragmas that apply to a complete compilation environment.
2280 For more details on how the @file{gnat.adc} file is created and used
2281 see @ref{Handling of Configuration Pragmas}.
2282 @cindex @file{gnat.adc}
2283
2284 @ifclear vms
2285 GNAT allows completely arbitrary file names to be specified using the
2286 source file name pragma. However, if the file name specified has an
2287 extension other than @file{.ads} or @file{.adb} it is necessary to use
2288 a special syntax when compiling the file. The name in this case must be
2289 preceded by the special sequence @code{-x} followed by a space and the name
2290 of the language, here @code{ada}, as in:
2291
2292 @smallexample
2293 $ gcc -c -x ada peculiar_file_name.sim
2294 @end smallexample
2295 @end ifclear
2296
2297 @noindent
2298 @command{gnatmake} handles non-standard file names in the usual manner (the
2299 non-standard file name for the main program is simply used as the
2300 argument to gnatmake). Note that if the extension is also non-standard,
2301 then it must be included in the gnatmake command, it may not be omitted.
2302
2303 @node Alternative File Naming Schemes
2304 @section Alternative File Naming Schemes
2305 @cindex File naming schemes, alternative
2306 @cindex File names
2307
2308 In the previous section, we described the use of the @code{Source_File_Name}
2309 pragma to allow arbitrary names to be assigned to individual source files.
2310 However, this approach requires one pragma for each file, and especially in
2311 large systems can result in very long @file{gnat.adc} files, and also create
2312 a maintenance problem.
2313
2314 GNAT also provides a facility for specifying systematic file naming schemes
2315 other than the standard default naming scheme previously described. An
2316 alternative scheme for naming is specified by the use of
2317 @code{Source_File_Name} pragmas having the following format:
2318 @cindex Source_File_Name pragma
2319
2320 @smallexample @c ada
2321 pragma Source_File_Name (
2322    Spec_File_Name  => FILE_NAME_PATTERN
2323  [,Casing          => CASING_SPEC]
2324  [,Dot_Replacement => STRING_LITERAL]);
2325
2326 pragma Source_File_Name (
2327    Body_File_Name  => FILE_NAME_PATTERN
2328  [,Casing          => CASING_SPEC]
2329  [,Dot_Replacement => STRING_LITERAL]);
2330
2331 pragma Source_File_Name (
2332    Subunit_File_Name  => FILE_NAME_PATTERN
2333  [,Casing             => CASING_SPEC]
2334  [,Dot_Replacement    => STRING_LITERAL]);
2335
2336 FILE_NAME_PATTERN ::= STRING_LITERAL
2337 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2338 @end smallexample
2339
2340 @noindent
2341 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2342 It contains a single asterisk character, and the unit name is substituted
2343 systematically for this asterisk. The optional parameter
2344 @code{Casing} indicates
2345 whether the unit name is to be all upper-case letters, all lower-case letters,
2346 or mixed-case. If no
2347 @code{Casing} parameter is used, then the default is all
2348 ^lower-case^upper-case^.
2349
2350 The optional @code{Dot_Replacement} string is used to replace any periods
2351 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2352 argument is used then separating dots appear unchanged in the resulting
2353 file name.
2354 Although the above syntax indicates that the
2355 @code{Casing} argument must appear
2356 before the @code{Dot_Replacement} argument, but it
2357 is also permissible to write these arguments in the opposite order.
2358
2359 As indicated, it is possible to specify different naming schemes for
2360 bodies, specs, and subunits. Quite often the rule for subunits is the
2361 same as the rule for bodies, in which case, there is no need to give
2362 a separate @code{Subunit_File_Name} rule, and in this case the
2363 @code{Body_File_name} rule is used for subunits as well.
2364
2365 The separate rule for subunits can also be used to implement the rather
2366 unusual case of a compilation environment (e.g. a single directory) which
2367 contains a subunit and a child unit with the same unit name. Although
2368 both units cannot appear in the same partition, the Ada Reference Manual
2369 allows (but does not require) the possibility of the two units coexisting
2370 in the same environment.
2371
2372 The file name translation works in the following steps:
2373
2374 @itemize @bullet
2375
2376 @item
2377 If there is a specific @code{Source_File_Name} pragma for the given unit,
2378 then this is always used, and any general pattern rules are ignored.
2379
2380 @item
2381 If there is a pattern type @code{Source_File_Name} pragma that applies to
2382 the unit, then the resulting file name will be used if the file exists. If
2383 more than one pattern matches, the latest one will be tried first, and the
2384 first attempt resulting in a reference to a file that exists will be used.
2385
2386 @item
2387 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2388 for which the corresponding file exists, then the standard GNAT default
2389 naming rules are used.
2390
2391 @end itemize
2392
2393 @noindent
2394 As an example of the use of this mechanism, consider a commonly used scheme
2395 in which file names are all lower case, with separating periods copied
2396 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2397 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2398 two pragmas appear:
2399
2400 @smallexample @c ada
2401 pragma Source_File_Name
2402   (Spec_File_Name => "*.1.ada");
2403 pragma Source_File_Name
2404   (Body_File_Name => "*.2.ada");
2405 @end smallexample
2406
2407 @noindent
2408 The default GNAT scheme is actually implemented by providing the following
2409 default pragmas internally:
2410
2411 @smallexample @c ada
2412 pragma Source_File_Name
2413   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2414 pragma Source_File_Name
2415   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2416 @end smallexample
2417
2418 @noindent
2419 Our final example implements a scheme typically used with one of the
2420 Ada 83 compilers, where the separator character for subunits was ``__''
2421 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2422 by adding @file{.ADA}, and subunits by
2423 adding @file{.SEP}. All file names were
2424 upper case. Child units were not present of course since this was an
2425 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2426 the same double underscore separator for child units.
2427
2428 @smallexample @c ada
2429 pragma Source_File_Name
2430   (Spec_File_Name => "*_.ADA",
2431    Dot_Replacement => "__",
2432    Casing = Uppercase);
2433 pragma Source_File_Name
2434   (Body_File_Name => "*.ADA",
2435    Dot_Replacement => "__",
2436    Casing = Uppercase);
2437 pragma Source_File_Name
2438   (Subunit_File_Name => "*.SEP",
2439    Dot_Replacement => "__",
2440    Casing = Uppercase);
2441 @end smallexample
2442
2443 @node Generating Object Files
2444 @section Generating Object Files
2445
2446 @noindent
2447 An Ada program consists of a set of source files, and the first step in
2448 compiling the program is to generate the corresponding object files.
2449 These are generated by compiling a subset of these source files.
2450 The files you need to compile are the following:
2451
2452 @itemize @bullet
2453 @item
2454 If a package spec has no body, compile the package spec to produce the
2455 object file for the package.
2456
2457 @item
2458 If a package has both a spec and a body, compile the body to produce the
2459 object file for the package. The source file for the package spec need
2460 not be compiled in this case because there is only one object file, which
2461 contains the code for both the spec and body of the package.
2462
2463 @item
2464 For a subprogram, compile the subprogram body to produce the object file
2465 for the subprogram. The spec, if one is present, is as usual in a
2466 separate file, and need not be compiled.
2467
2468 @item
2469 @cindex Subunits
2470 In the case of subunits, only compile the parent unit. A single object
2471 file is generated for the entire subunit tree, which includes all the
2472 subunits.
2473
2474 @item
2475 Compile child units independently of their parent units
2476 (though, of course, the spec of all the ancestor unit must be present in order
2477 to compile a child unit).
2478
2479 @item
2480 @cindex Generics
2481 Compile generic units in the same manner as any other units. The object
2482 files in this case are small dummy files that contain at most the
2483 flag used for elaboration checking. This is because GNAT always handles generic
2484 instantiation by means of macro expansion. However, it is still necessary to
2485 compile generic units, for dependency checking and elaboration purposes.
2486 @end itemize
2487
2488 @noindent
2489 The preceding rules describe the set of files that must be compiled to
2490 generate the object files for a program. Each object file has the same
2491 name as the corresponding source file, except that the extension is
2492 @file{.o} as usual.
2493
2494 You may wish to compile other files for the purpose of checking their
2495 syntactic and semantic correctness. For example, in the case where a
2496 package has a separate spec and body, you would not normally compile the
2497 spec. However, it is convenient in practice to compile the spec to make
2498 sure it is error-free before compiling clients of this spec, because such
2499 compilations will fail if there is an error in the spec.
2500
2501 GNAT provides an option for compiling such files purely for the
2502 purposes of checking correctness; such compilations are not required as
2503 part of the process of building a program. To compile a file in this
2504 checking mode, use the @option{-gnatc} switch.
2505
2506 @node Source Dependencies
2507 @section Source Dependencies
2508
2509 @noindent
2510 A given object file clearly depends on the source file which is compiled
2511 to produce it. Here we are using @dfn{depends} in the sense of a typical
2512 @code{make} utility; in other words, an object file depends on a source
2513 file if changes to the source file require the object file to be
2514 recompiled.
2515 In addition to this basic dependency, a given object may depend on
2516 additional source files as follows:
2517
2518 @itemize @bullet
2519 @item
2520 If a file being compiled @code{with}'s a unit @var{X}, the object file
2521 depends on the file containing the spec of unit @var{X}. This includes
2522 files that are @code{with}'ed implicitly either because they are parents
2523 of @code{with}'ed child units or they are run-time units required by the
2524 language constructs used in a particular unit.
2525
2526 @item
2527 If a file being compiled instantiates a library level generic unit, the
2528 object file depends on both the spec and body files for this generic
2529 unit.
2530
2531 @item
2532 If a file being compiled instantiates a generic unit defined within a
2533 package, the object file depends on the body file for the package as
2534 well as the spec file.
2535
2536 @item
2537 @findex Inline
2538 @cindex @option{-gnatn} switch
2539 If a file being compiled contains a call to a subprogram for which
2540 pragma @code{Inline} applies and inlining is activated with the
2541 @option{-gnatn} switch, the object file depends on the file containing the
2542 body of this subprogram as well as on the file containing the spec. Note
2543 that for inlining to actually occur as a result of the use of this switch,
2544 it is necessary to compile in optimizing mode.
2545
2546 @cindex @option{-gnatN} switch
2547 The use of @option{-gnatN} activates a more extensive inlining optimization
2548 that is performed by the front end of the compiler. This inlining does
2549 not require that the code generation be optimized. Like @option{-gnatn},
2550 the use of this switch generates additional dependencies.
2551 Note that
2552 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2553 to specify both options.
2554
2555 @item
2556 If an object file O  depends on the proper body of a subunit through inlining
2557 or instantiation, it depends on the parent unit of the subunit. This means that
2558 any modification of the parent unit or one of its subunits affects the
2559 compilation of O.
2560
2561 @item
2562 The object file for a parent unit depends on all its subunit body files.
2563
2564 @item
2565 The previous two rules meant that for purposes of computing dependencies and
2566 recompilation, a body and all its subunits are treated as an indivisible whole.
2567
2568 @noindent
2569 These rules are applied transitively: if unit @code{A} @code{with}'s
2570 unit @code{B}, whose elaboration calls an inlined procedure in package
2571 @code{C}, the object file for unit @code{A} will depend on the body of
2572 @code{C}, in file @file{c.adb}.
2573
2574 The set of dependent files described by these rules includes all the
2575 files on which the unit is semantically dependent, as described in the
2576 Ada 95 Language Reference Manual. However, it is a superset of what the
2577 ARM describes, because it includes generic, inline, and subunit dependencies.
2578
2579 An object file must be recreated by recompiling the corresponding source
2580 file if any of the source files on which it depends are modified. For
2581 example, if the @code{make} utility is used to control compilation,
2582 the rule for an Ada object file must mention all the source files on
2583 which the object file depends, according to the above definition.
2584 The determination of the necessary
2585 recompilations is done automatically when one uses @command{gnatmake}.
2586 @end itemize
2587
2588 @node The Ada Library Information Files
2589 @section The Ada Library Information Files
2590 @cindex Ada Library Information files
2591 @cindex @file{ALI} files
2592
2593 @noindent
2594 Each compilation actually generates two output files. The first of these
2595 is the normal object file that has a @file{.o} extension. The second is a
2596 text file containing full dependency information. It has the same
2597 name as the source file, but an @file{.ali} extension.
2598 This file is known as the Ada Library Information (@file{ALI}) file.
2599 The following information is contained in the @file{ALI} file.
2600
2601 @itemize @bullet
2602 @item
2603 Version information (indicates which version of GNAT was used to compile
2604 the unit(s) in question)
2605
2606 @item
2607 Main program information (including priority and time slice settings,
2608 as well as the wide character encoding used during compilation).
2609
2610 @item
2611 List of arguments used in the @command{gcc} command for the compilation
2612
2613 @item
2614 Attributes of the unit, including configuration pragmas used, an indication
2615 of whether the compilation was successful, exception model used etc.
2616
2617 @item
2618 A list of relevant restrictions applying to the unit (used for consistency)
2619 checking.
2620
2621 @item
2622 Categorization information (e.g. use of pragma @code{Pure}).
2623
2624 @item
2625 Information on all @code{with}'ed units, including presence of
2626 @code{Elaborate} or @code{Elaborate_All} pragmas.
2627
2628 @item
2629 Information from any @code{Linker_Options} pragmas used in the unit
2630
2631 @item
2632 Information on the use of @code{Body_Version} or @code{Version}
2633 attributes in the unit.
2634
2635 @item
2636 Dependency information. This is a list of files, together with
2637 time stamp and checksum information. These are files on which
2638 the unit depends in the sense that recompilation is required
2639 if any of these units are modified.
2640
2641 @item
2642 Cross-reference data. Contains information on all entities referenced
2643 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2644 provide cross-reference information.
2645
2646 @end itemize
2647
2648 @noindent
2649 For a full detailed description of the format of the @file{ALI} file,
2650 see the source of the body of unit @code{Lib.Writ}, contained in file
2651 @file{lib-writ.adb} in the GNAT compiler sources.
2652
2653 @node Binding an Ada Program
2654 @section Binding an Ada Program
2655
2656 @noindent
2657 When using languages such as C and C++, once the source files have been
2658 compiled the only remaining step in building an executable program
2659 is linking the object modules together. This means that it is possible to
2660 link an inconsistent version of a program, in which two units have
2661 included different versions of the same header.
2662
2663 The rules of Ada do not permit such an inconsistent program to be built.
2664 For example, if two clients have different versions of the same package,
2665 it is illegal to build a program containing these two clients.
2666 These rules are enforced by the GNAT binder, which also determines an
2667 elaboration order consistent with the Ada rules.
2668
2669 The GNAT binder is run after all the object files for a program have
2670 been created. It is given the name of the main program unit, and from
2671 this it determines the set of units required by the program, by reading the
2672 corresponding ALI files. It generates error messages if the program is
2673 inconsistent or if no valid order of elaboration exists.
2674
2675 If no errors are detected, the binder produces a main program, in Ada by
2676 default, that contains calls to the elaboration procedures of those
2677 compilation unit that require them, followed by
2678 a call to the main program. This Ada program is compiled to generate the
2679 object file for the main program. The name of
2680 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2681 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2682 main program unit.
2683
2684 Finally, the linker is used to build the resulting executable program,
2685 using the object from the main program from the bind step as well as the
2686 object files for the Ada units of the program.
2687
2688 @node Mixed Language Programming
2689 @section Mixed Language Programming
2690 @cindex Mixed Language Programming
2691
2692 @noindent
2693 This section describes how to develop a mixed-language program,
2694 specifically one that comprises units in both Ada and C.
2695
2696 @menu
2697 * Interfacing to C::
2698 * Calling Conventions::
2699 @end menu
2700
2701 @node Interfacing to C
2702 @subsection Interfacing to C
2703 @noindent
2704 Interfacing Ada with a foreign language such as C involves using
2705 compiler directives to import and/or export entity definitions in each
2706 language---using @code{extern} statements in C, for instance, and the
2707 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.  For
2708 a full treatment of these topics, read Appendix B, section 1 of the Ada
2709 95 Language Reference Manual.
2710
2711 There are two ways to build a program using GNAT that contains some Ada
2712 sources and some foreign language sources, depending on whether or not
2713 the main subprogram is written in Ada.  Here is a source example with
2714 the main subprogram in Ada:
2715
2716 @smallexample
2717 /* file1.c */
2718 #include <stdio.h>
2719
2720 void print_num (int num)
2721 @{
2722   printf ("num is %d.\n", num);
2723   return;
2724 @}
2725
2726 /* file2.c */
2727
2728 /* num_from_Ada is declared in my_main.adb */
2729 extern int num_from_Ada;
2730
2731 int get_num (void)
2732 @{
2733   return num_from_Ada;
2734 @}
2735 @end smallexample
2736
2737 @smallexample @c ada
2738 --  my_main.adb
2739 procedure My_Main is
2740
2741    --  Declare then export an Integer entity called num_from_Ada
2742    My_Num : Integer := 10;
2743    pragma Export (C, My_Num, "num_from_Ada");
2744
2745    --  Declare an Ada function spec for Get_Num, then use
2746    --  C function get_num for the implementation.
2747    function Get_Num return Integer;
2748    pragma Import (C, Get_Num, "get_num");
2749
2750    --  Declare an Ada procedure spec for Print_Num, then use
2751    --  C function print_num for the implementation.
2752    procedure Print_Num (Num : Integer);
2753    pragma Import (C, Print_Num, "print_num");
2754
2755 begin
2756    Print_Num (Get_Num);
2757 end My_Main;
2758 @end smallexample
2759
2760 @enumerate
2761 @item
2762 To build this example, first compile the foreign language files to
2763 generate object files:
2764 @smallexample
2765 gcc -c file1.c
2766 gcc -c file2.c
2767 @end smallexample
2768
2769 @item
2770 Then, compile the Ada units to produce a set of object files and ALI
2771 files:
2772 @smallexample
2773 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2774 @end smallexample
2775
2776 @item
2777 Run the Ada binder on the Ada main program:
2778 @smallexample
2779 gnatbind my_main.ali
2780 @end smallexample
2781
2782 @item
2783 Link the Ada main program, the Ada objects and the other language
2784 objects:
2785 @smallexample
2786 gnatlink my_main.ali file1.o file2.o
2787 @end smallexample
2788 @end enumerate
2789
2790 The last three steps can be grouped in a single command:
2791 @smallexample
2792 gnatmake my_main.adb -largs file1.o file2.o
2793 @end smallexample
2794
2795 @cindex Binder output file
2796 @noindent
2797 If the main program is in a language other than Ada, then you may have
2798 more than one entry point into the Ada subsystem. You must use a special
2799 binder option to generate callable routines that initialize and
2800 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2801 Calls to the initialization and finalization routines must be inserted
2802 in the main program, or some other appropriate point in the code. The
2803 call to initialize the Ada units must occur before the first Ada
2804 subprogram is called, and the call to finalize the Ada units must occur
2805 after the last Ada subprogram returns. The binder will place the
2806 initialization and finalization subprograms into the
2807 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2808 sources.  To illustrate, we have the following example:
2809
2810 @smallexample
2811 /* main.c */
2812 extern void adainit (void);
2813 extern void adafinal (void);
2814 extern int add (int, int);
2815 extern int sub (int, int);
2816
2817 int main (int argc, char *argv[])
2818 @{
2819   int a = 21, b = 7;
2820
2821   adainit();
2822
2823   /* Should print "21 + 7 = 28" */
2824   printf ("%d + %d = %d\n", a, b, add (a, b));
2825   /* Should print "21 - 7 = 14" */
2826   printf ("%d - %d = %d\n", a, b, sub (a, b));
2827
2828   adafinal();
2829 @}
2830 @end smallexample
2831
2832 @smallexample @c ada
2833 --  unit1.ads
2834 package Unit1 is
2835    function Add (A, B : Integer) return Integer;
2836    pragma Export (C, Add, "add");
2837 end Unit1;
2838
2839 --  unit1.adb
2840 package body Unit1 is
2841    function Add (A, B : Integer) return Integer is
2842    begin
2843       return A + B;
2844    end Add;
2845 end Unit1;
2846
2847 --  unit2.ads
2848 package Unit2 is
2849    function Sub (A, B : Integer) return Integer;
2850    pragma Export (C, Sub, "sub");
2851 end Unit2;
2852
2853 --  unit2.adb
2854 package body Unit2 is
2855    function Sub (A, B : Integer) return Integer is
2856    begin
2857       return A - B;
2858    end Sub;
2859 end Unit2;
2860 @end smallexample
2861
2862 @enumerate
2863 @item
2864 The build procedure for this application is similar to the last
2865 example's.  First, compile the foreign language files to generate object
2866 files:
2867 @smallexample
2868 gcc -c main.c
2869 @end smallexample
2870
2871 @item
2872 Next, compile the Ada units to produce a set of object files and ALI
2873 files:
2874 @smallexample
2875 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2876 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2877 @end smallexample
2878
2879 @item
2880 Run the Ada binder on every generated ALI file.  Make sure to use the
2881 @option{-n} option to specify a foreign main program:
2882 @smallexample
2883 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2884 @end smallexample
2885
2886 @item
2887 Link the Ada main program, the Ada objects and the foreign language
2888 objects. You need only list the last ALI file here:
2889 @smallexample
2890 gnatlink unit2.ali main.o -o exec_file
2891 @end smallexample
2892
2893 This procedure yields a binary executable called @file{exec_file}.
2894 @end enumerate
2895
2896 @node Calling Conventions
2897 @subsection Calling Conventions
2898 @cindex Foreign Languages
2899 @cindex Calling Conventions
2900 GNAT follows standard calling sequence conventions and will thus interface
2901 to any other language that also follows these conventions. The following
2902 Convention identifiers are recognized by GNAT:
2903
2904 @table @code
2905 @cindex Interfacing to Ada
2906 @cindex Other Ada compilers
2907 @cindex Convention Ada
2908 @item Ada
2909 This indicates that the standard Ada calling sequence will be
2910 used and all Ada data items may be passed without any limitations in the
2911 case where GNAT is used to generate both the caller and callee. It is also
2912 possible to mix GNAT generated code and code generated by another Ada
2913 compiler. In this case, the data types should be restricted to simple
2914 cases, including primitive types. Whether complex data types can be passed
2915 depends on the situation. Probably it is safe to pass simple arrays, such
2916 as arrays of integers or floats. Records may or may not work, depending
2917 on whether both compilers lay them out identically. Complex structures
2918 involving variant records, access parameters, tasks, or protected types,
2919 are unlikely to be able to be passed.
2920
2921 Note that in the case of GNAT running
2922 on a platform that supports DEC Ada 83, a higher degree of compatibility
2923 can be guaranteed, and in particular records are layed out in an identical
2924 manner in the two compilers. Note also that if output from two different
2925 compilers is mixed, the program is responsible for dealing with elaboration
2926 issues. Probably the safest approach is to write the main program in the
2927 version of Ada other than GNAT, so that it takes care of its own elaboration
2928 requirements, and then call the GNAT-generated adainit procedure to ensure
2929 elaboration of the GNAT components. Consult the documentation of the other
2930 Ada compiler for further details on elaboration.
2931
2932 However, it is not possible to mix the tasking run time of GNAT and
2933 DEC Ada 83, All the tasking operations must either be entirely within
2934 GNAT compiled sections of the program, or entirely within DEC Ada 83
2935 compiled sections of the program.
2936
2937 @cindex Interfacing to Assembly
2938 @cindex Convention Assembler
2939 @item Assembler
2940 Specifies assembler as the convention. In practice this has the
2941 same effect as convention Ada (but is not equivalent in the sense of being
2942 considered the same convention).
2943
2944 @cindex Convention Asm
2945 @findex Asm
2946 @item Asm
2947 Equivalent to Assembler.
2948
2949 @cindex Interfacing to COBOL
2950 @cindex Convention COBOL
2951 @findex COBOL
2952 @item COBOL
2953 Data will be passed according to the conventions described
2954 in section B.4 of the Ada 95 Reference Manual.
2955
2956 @findex C
2957 @cindex Interfacing to C
2958 @cindex Convention C
2959 @item C
2960 Data will be passed according to the conventions described
2961 in section B.3 of the Ada 95 Reference Manual.
2962
2963 @findex C varargs function
2964 @cindex Intefacing to C varargs function
2965 @cindex varargs function intefacs
2966 @item C varargs function
2967 In C, @code{varargs} allows a function to take a variable number of
2968 arguments. There is no direct equivalent in this to Ada. One
2969 approach that can be used is to create a C wrapper for each
2970 different profile and then interface to this C wrapper. For
2971 example, to print an @code{int} value using @code{printf},
2972 create a C function @code{printfi} that takes two arguments, a
2973 pointer to a string and an int, and calls @code{printf}.
2974 Then in the Ada program, use pragma @code{Import} to
2975 interface to printfi.
2976
2977 It may work on some platforms to directly interface to
2978 a @code{varargs} function by providing a specific Ada profile
2979 for a a particular call. However, this does not work on
2980 all platforms, since there is no guarantee that the
2981 calling sequence for a two argument normal C function
2982 is the same as for calling a @code{varargs} C function with
2983 the same two arguments.
2984
2985 @cindex Convention Default
2986 @findex Default
2987 @item Default
2988 Equivalent to C.
2989
2990 @cindex Convention External
2991 @findex External
2992 @item External
2993 Equivalent to C.
2994
2995 @findex C++
2996 @cindex Interfacing to C++
2997 @cindex Convention C++
2998 @item CPP
2999 This stands for C++. For most purposes this is identical to C.
3000 See the separate description of the specialized GNAT pragmas relating to
3001 C++ interfacing for further details.
3002
3003 @findex Fortran
3004 @cindex Interfacing to Fortran
3005 @cindex Convention Fortran
3006 @item Fortran
3007 Data will be passed according to the conventions described
3008 in section B.5 of the Ada 95 Reference Manual.
3009
3010 @item Intrinsic
3011 This applies to an intrinsic operation, as defined in the Ada 95
3012 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
3013 this means that the body of the subprogram is provided by the compiler itself,
3014 usually by means of an efficient code sequence, and that the user does not
3015 supply an explicit body for it. In an application program, the pragma can
3016 only be applied to the following two sets of names, which the GNAT compiler
3017 recognizes.
3018
3019 @itemize @bullet
3020 @item
3021 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
3022 Arithmetic.  The corresponding subprogram declaration must have
3023 two formal parameters. The
3024 first one must be a signed integer type or a modular type with a binary
3025 modulus, and the second parameter must be of type Natural.
3026 The return type must be the same as the type of the first argument. The size
3027 of this type can only be 8, 16, 32, or 64.
3028 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3029 The corresponding operator declaration must have parameters and result type
3030 that have the same root numeric type (for example, all three are long_float
3031 types). This simplifies the definition of operations that use type checking
3032 to perform dimensional checks:
3033
3034 @smallexample @c ada
3035 type Distance is new Long_Float;
3036 type Time     is new Long_Float;
3037 type Velocity is new Long_Float;
3038 function "/" (D : Distance; T : Time)
3039   return Velocity;
3040 pragma Import (Intrinsic, "/");
3041 @end smallexample
3042
3043 @noindent
3044 This common idiom is often programmed with a generic definition and an
3045 explicit body. The pragma makes it simpler to introduce such declarations.
3046 It incurs no overhead in compilation time or code size, because it is
3047 implemented as a single machine instruction.
3048 @end itemize
3049 @noindent
3050
3051 @ifset unw
3052 @findex Stdcall
3053 @cindex Convention Stdcall
3054 @item Stdcall
3055 This is relevant only to NT/Win95 implementations of GNAT,
3056 and specifies that the Stdcall calling sequence will be used, as defined
3057 by the NT API.
3058
3059 @findex DLL
3060 @cindex Convention DLL
3061 @item DLL
3062 This is equivalent to Stdcall.
3063
3064 @findex Win32
3065 @cindex Convention Win32
3066 @item Win32
3067 This is equivalent to Stdcall.
3068 @end ifset
3069
3070 @findex Stubbed
3071 @cindex Convention Stubbed
3072 @item Stubbed
3073 This is a special convention that indicates that the compiler
3074 should provide a stub body that raises @code{Program_Error}.
3075 @end table
3076
3077 @noindent
3078 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3079 that can be used to parametrize conventions and allow additional synonyms
3080 to be specified. For example if you have legacy code in which the convention
3081 identifier Fortran77 was used for Fortran, you can use the configuration
3082 pragma:
3083
3084 @smallexample @c ada
3085 pragma Convention_Identifier (Fortran77, Fortran);
3086 @end smallexample
3087
3088 @noindent
3089 And from now on the identifier Fortran77 may be used as a convention
3090 identifier (for example in an @code{Import} pragma) with the same
3091 meaning as Fortran.
3092
3093 @node Building Mixed Ada & C++ Programs
3094 @section Building Mixed Ada & C++ Programs
3095
3096 @noindent
3097 A programmer inexperienced with mixed-language development may find that
3098 building an application containing both Ada and C++ code can be a
3099 challenge. As a matter of fact, interfacing with C++ has not been
3100 standardized in the Ada 95 Reference Manual due to the immaturity of --
3101 and lack of standards for -- C++ at the time. This section gives a few
3102 hints that should make this task easier. The first section addresses
3103 the differences regarding interfacing with C. The second section
3104 looks into the delicate problem of linking the complete application from
3105 its Ada and C++ parts. The last section gives some hints on how the GNAT
3106 run time can be adapted in order to allow inter-language dispatching
3107 with a new C++ compiler.
3108
3109 @menu
3110 * Interfacing to C++::
3111 * Linking a Mixed C++ & Ada Program::
3112 * A Simple Example::
3113 * Adapting the Run Time to a New C++ Compiler::
3114 @end menu
3115
3116 @node Interfacing to C++
3117 @subsection Interfacing to C++
3118
3119 @noindent
3120 GNAT supports interfacing with C++ compilers generating code that is
3121 compatible with the standard Application Binary Interface of the given
3122 platform.
3123
3124 @noindent
3125 Interfacing can be done at 3 levels: simple data, subprograms, and
3126 classes. In the first two cases, GNAT offers a specific @var{Convention
3127 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3128 the names of subprograms, and currently, GNAT does not provide any help
3129 to solve the demangling problem. This problem can be addressed in two
3130 ways:
3131 @itemize @bullet
3132 @item
3133 by modifying the C++ code in order to force a C convention using
3134 the @code{extern "C"} syntax.
3135
3136 @item
3137 by figuring out the mangled name and use it as the Link_Name argument of
3138 the pragma import.
3139 @end itemize
3140
3141 @noindent
3142 Interfacing at the class level can be achieved by using the GNAT specific
3143 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3144 Reference Manual for additional information.
3145
3146 @node Linking a Mixed C++ & Ada Program
3147 @subsection Linking a Mixed C++ & Ada Program
3148
3149 @noindent
3150 Usually the linker of the C++ development system must be used to link
3151 mixed applications because most C++ systems will resolve elaboration
3152 issues (such as calling constructors on global class instances)
3153 transparently during the link phase. GNAT has been adapted to ease the
3154 use of a foreign linker for the last phase. Three cases can be
3155 considered:
3156 @enumerate
3157
3158 @item
3159 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3160 The C++ linker can simply be called by using the C++ specific driver
3161 called @code{c++}. Note that this setup is not very common because it
3162 may involve recompiling the whole GCC tree from sources, which makes it
3163 harder to upgrade the compilation system for one language without
3164 destabilizing the other.
3165
3166 @smallexample
3167 $ c++ -c file1.C
3168 $ c++ -c file2.C
3169 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3170 @end smallexample
3171
3172 @item
3173 Using GNAT and G++ from two different GCC installations: If both
3174 compilers are on the PATH, the previous method may be used. It is
3175 important to note that environment variables such as C_INCLUDE_PATH,
3176 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3177 at the same time and may make one of the two compilers operate
3178 improperly if set during invocation of the wrong compiler.  It is also
3179 very important that the linker uses the proper @file{libgcc.a} GCC
3180 library -- that is, the one from the C++ compiler installation. The
3181 implicit link command as suggested in the gnatmake command from the
3182 former example can be replaced by an explicit link command with the
3183 full-verbosity option in order to verify which library is used:
3184 @smallexample
3185 $ gnatbind ada_unit
3186 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3187 @end smallexample
3188 If there is a problem due to interfering environment variables, it can
3189 be worked around by using an intermediate script. The following example
3190 shows the proper script to use when GNAT has not been installed at its
3191 default location and g++ has been installed at its default location:
3192
3193 @smallexample
3194 $ cat ./my_script
3195 #!/bin/sh
3196 unset BINUTILS_ROOT
3197 unset GCC_ROOT
3198 c++ $*
3199 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3200 @end smallexample
3201
3202 @item
3203 Using a non-GNU C++ compiler: The commands previously described can be
3204 used to insure that the C++ linker is used. Nonetheless, you need to add
3205 the path to libgcc explicitly, since some libraries needed by GNAT are
3206 located in this directory:
3207
3208 @smallexample
3209 $ cat ./my_script
3210 #!/bin/sh
3211 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3212 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3213 @end smallexample
3214
3215 Where CC is the name of the non-GNU C++ compiler.
3216
3217 @end enumerate
3218
3219 @node A Simple Example
3220 @subsection  A Simple Example
3221 @noindent
3222 The following example, provided as part of the GNAT examples, shows how
3223 to achieve procedural interfacing between Ada and C++ in both
3224 directions. The C++ class A has two methods. The first method is exported
3225 to Ada by the means of an extern C wrapper function. The second method
3226 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3227 a limited record with a layout comparable to the C++ class. The Ada
3228 subprogram, in turn, calls the C++ method. So, starting from the C++
3229 main program, the process passes back and forth between the two
3230 languages.
3231
3232 @noindent
3233 Here are the compilation commands:
3234 @smallexample
3235 $ gnatmake -c simple_cpp_interface
3236 $ c++ -c cpp_main.C
3237 $ c++ -c ex7.C
3238 $ gnatbind -n simple_cpp_interface
3239 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3240       -lstdc++ ex7.o cpp_main.o
3241 @end smallexample
3242
3243 @noindent
3244 Here are the corresponding sources:
3245 @smallexample
3246
3247 //cpp_main.C
3248
3249 #include "ex7.h"
3250
3251 extern "C" @{
3252   void adainit (void);
3253   void adafinal (void);
3254   void method1 (A *t);
3255 @}
3256
3257 void method1 (A *t)
3258 @{
3259   t->method1 ();
3260 @}
3261
3262 int main ()
3263 @{
3264   A obj;
3265   adainit ();
3266   obj.method2 (3030);
3267   adafinal ();
3268 @}
3269
3270 //ex7.h
3271
3272 class Origin @{
3273  public:
3274   int o_value;
3275 @};
3276 class A : public Origin @{
3277  public:
3278   void method1 (void);
3279   void method2 (int v);
3280   A();
3281   int   a_value;
3282 @};
3283
3284 //ex7.C
3285
3286 #include "ex7.h"
3287 #include <stdio.h>
3288
3289 extern "C" @{ void ada_method2 (A *t, int v);@}
3290
3291 void A::method1 (void)
3292 @{
3293   a_value = 2020;
3294   printf ("in A::method1, a_value = %d \n",a_value);
3295
3296 @}
3297
3298 void A::method2 (int v)
3299 @{
3300    ada_method2 (this, v);
3301    printf ("in A::method2, a_value = %d \n",a_value);
3302
3303 @}
3304
3305 A::A(void)
3306 @{
3307    a_value = 1010;
3308   printf ("in A::A, a_value = %d \n",a_value);
3309 @}
3310
3311 -- Ada sources
3312 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3313
3314    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3315    @b{begin}
3316       Method1 (This);
3317       This.A_Value := V;
3318    @b{end} Ada_Method2;
3319
3320 @b{end} Simple_Cpp_Interface;
3321
3322 @b{package} Simple_Cpp_Interface @b{is}
3323    @b{type} A @b{is} @b{limited}
3324       @b{record}
3325          O_Value : Integer;
3326          A_Value : Integer;
3327       @b{end} @b{record};
3328    @b{pragma} Convention (C, A);
3329
3330    @b{procedure} Method1 (This : @b{in} @b{out} A);
3331    @b{pragma} Import (C, Method1);
3332
3333    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3334    @b{pragma} Export (C, Ada_Method2);
3335
3336 @b{end} Simple_Cpp_Interface;
3337 @end smallexample
3338
3339 @node Adapting the Run Time to a New C++ Compiler
3340 @subsection Adapting the Run Time to a New C++ Compiler
3341 @noindent
3342 GNAT offers the capability to derive Ada 95 tagged types directly from
3343 preexisting C++ classes and . See ``Interfacing with C++'' in the
3344 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3345 such a goal
3346 has been made user configurable through a GNAT library unit
3347 @code{Interfaces.CPP}. The default version of this file is adapted to
3348 the GNU C++ compiler. Internal knowledge of the virtual
3349 table layout used by the new C++ compiler is needed to configure
3350 properly this unit. The Interface of this unit is known by the compiler
3351 and cannot be changed except for the value of the constants defining the
3352 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3353 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3354 of this unit for more details.
3355
3356 @node Comparison between GNAT and C/C++ Compilation Models
3357 @section Comparison between GNAT and C/C++ Compilation Models
3358
3359 @noindent
3360 The GNAT model of compilation is close to the C and C++ models. You can
3361 think of Ada specs as corresponding to header files in C. As in C, you
3362 don't need to compile specs; they are compiled when they are used. The
3363 Ada @code{with} is similar in effect to the @code{#include} of a C
3364 header.
3365
3366 One notable difference is that, in Ada, you may compile specs separately
3367 to check them for semantic and syntactic accuracy. This is not always
3368 possible with C headers because they are fragments of programs that have
3369 less specific syntactic or semantic rules.
3370
3371 The other major difference is the requirement for running the binder,
3372 which performs two important functions. First, it checks for
3373 consistency. In C or C++, the only defense against assembling
3374 inconsistent programs lies outside the compiler, in a makefile, for
3375 example. The binder satisfies the Ada requirement that it be impossible
3376 to construct an inconsistent program when the compiler is used in normal
3377 mode.
3378
3379 @cindex Elaboration order control
3380 The other important function of the binder is to deal with elaboration
3381 issues. There are also elaboration issues in C++ that are handled
3382 automatically. This automatic handling has the advantage of being
3383 simpler to use, but the C++ programmer has no control over elaboration.
3384 Where @code{gnatbind} might complain there was no valid order of
3385 elaboration, a C++ compiler would simply construct a program that
3386 malfunctioned at run time.
3387
3388 @node Comparison between GNAT and Conventional Ada Library Models
3389 @section Comparison between GNAT and Conventional Ada Library Models
3390
3391 @noindent
3392 This section is intended to be useful to Ada programmers who have
3393 previously used an Ada compiler implementing the traditional Ada library
3394 model, as described in the Ada 95 Language Reference Manual. If you
3395 have not used such a system, please go on to the next section.
3396
3397 @cindex GNAT library
3398 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
3399 source files themselves acts as the library. Compiling Ada programs does
3400 not generate any centralized information, but rather an object file and
3401 a ALI file, which are of interest only to the binder and linker.
3402 In a traditional system, the compiler reads information not only from
3403 the source file being compiled, but also from the centralized library.
3404 This means that the effect of a compilation depends on what has been
3405 previously compiled. In particular:
3406
3407 @itemize @bullet
3408 @item
3409 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3410 to the version of the unit most recently compiled into the library.
3411
3412 @item
3413 Inlining is effective only if the necessary body has already been
3414 compiled into the library.
3415
3416 @item
3417 Compiling a unit may obsolete other units in the library.
3418 @end itemize
3419
3420 @noindent
3421 In GNAT, compiling one unit never affects the compilation of any other
3422 units because the compiler reads only source files. Only changes to source
3423 files can affect the results of a compilation. In particular:
3424
3425 @itemize @bullet
3426 @item
3427 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3428 to the source version of the unit that is currently accessible to the
3429 compiler.
3430
3431 @item
3432 @cindex Inlining
3433 Inlining requires the appropriate source files for the package or
3434 subprogram bodies to be available to the compiler. Inlining is always
3435 effective, independent of the order in which units are complied.
3436
3437 @item
3438 Compiling a unit never affects any other compilations. The editing of
3439 sources may cause previous compilations to be out of date if they
3440 depended on the source file being modified.
3441 @end itemize
3442
3443 @noindent
3444 The most important result of these differences is that order of compilation
3445 is never significant in GNAT. There is no situation in which one is
3446 required to do one compilation before another. What shows up as order of
3447 compilation requirements in the traditional Ada library becomes, in
3448 GNAT, simple source dependencies; in other words, there is only a set
3449 of rules saying what source files must be present when a file is
3450 compiled.
3451
3452 @ifset vms
3453 @node Placement of temporary files
3454 @section Placement of temporary files
3455 @cindex Temporary files (user control over placement)
3456
3457 @noindent
3458 GNAT creates temporary files in the directory designated by the environment
3459 variable @env{TMPDIR}.
3460 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3461 for detailed information on how environment variables are resolved.
3462 For most users the easiest way to make use of this feature is to simply
3463 define @env{TMPDIR} as a job level logical name).
3464 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3465 for compiler temporary files, then you can include something like the
3466 following command in your @file{LOGIN.COM} file:
3467
3468 @smallexample
3469 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3470 @end smallexample
3471
3472 @noindent
3473 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3474 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3475 designated by @env{TEMP}.
3476 If none of these environment variables are defined then GNAT uses the
3477 directory designated by the logical name @code{SYS$SCRATCH:}
3478 (by default the user's home directory). If all else fails
3479 GNAT uses the current directory for temporary files.
3480 @end ifset
3481
3482 @c *************************
3483 @node Compiling Using gcc
3484 @chapter Compiling Using @command{gcc}
3485
3486 @noindent
3487 This chapter discusses how to compile Ada programs using the @command{gcc}
3488 command. It also describes the set of switches
3489 that can be used to control the behavior of the compiler.
3490 @menu
3491 * Compiling Programs::
3492 * Switches for gcc::
3493 * Search Paths and the Run-Time Library (RTL)::
3494 * Order of Compilation Issues::
3495 * Examples::
3496 @end menu
3497
3498 @node Compiling Programs
3499 @section Compiling Programs
3500
3501 @noindent
3502 The first step in creating an executable program is to compile the units
3503 of the program using the @command{gcc} command. You must compile the
3504 following files:
3505
3506 @itemize @bullet
3507 @item
3508 the body file (@file{.adb}) for a library level subprogram or generic
3509 subprogram
3510
3511 @item
3512 the spec file (@file{.ads}) for a library level package or generic
3513 package that has no body
3514
3515 @item
3516 the body file (@file{.adb}) for a library level package
3517 or generic package that has a body
3518
3519 @end itemize
3520
3521 @noindent
3522 You need @emph{not} compile the following files
3523
3524 @itemize @bullet
3525
3526 @item
3527 the spec of a library unit which has a body
3528
3529 @item
3530 subunits
3531 @end itemize
3532
3533 @noindent
3534 because they are compiled as part of compiling related units. GNAT
3535 package specs
3536 when the corresponding body is compiled, and subunits when the parent is
3537 compiled.
3538
3539 @cindex cannot generate code
3540 If you attempt to compile any of these files, you will get one of the
3541 following error messages (where fff is the name of the file you compiled):
3542
3543 @smallexample
3544 cannot generate code for file @var{fff} (package spec)
3545 to check package spec, use -gnatc
3546
3547 cannot generate code for file @var{fff} (missing subunits)
3548 to check parent unit, use -gnatc
3549
3550 cannot generate code for file @var{fff} (subprogram spec)
3551 to check subprogram spec, use -gnatc
3552
3553 cannot generate code for file @var{fff} (subunit)
3554 to check subunit, use -gnatc
3555 @end smallexample
3556
3557 @noindent
3558 As indicated by the above error messages, if you want to submit
3559 one of these files to the compiler to check for correct semantics
3560 without generating code, then use the @option{-gnatc} switch.
3561
3562 The basic command for compiling a file containing an Ada unit is
3563
3564 @smallexample
3565 $ gcc -c [@var{switches}] @file{file name}
3566 @end smallexample
3567
3568 @noindent
3569 where @var{file name} is the name of the Ada file (usually
3570 having an extension
3571 @file{.ads} for a spec or @file{.adb} for a body).
3572 @ifclear vms
3573 You specify the
3574 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3575 @end ifclear
3576 The result of a successful compilation is an object file, which has the
3577 same name as the source file but an extension of @file{.o} and an Ada
3578 Library Information (ALI) file, which also has the same name as the
3579 source file, but with @file{.ali} as the extension. GNAT creates these
3580 two output files in the current directory, but you may specify a source
3581 file in any directory using an absolute or relative path specification
3582 containing the directory information.
3583
3584 @findex gnat1
3585 @command{gcc} is actually a driver program that looks at the extensions of
3586 the file arguments and loads the appropriate compiler. For example, the
3587 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3588 These programs are in directories known to the driver program (in some
3589 configurations via environment variables you set), but need not be in
3590 your path. The @command{gcc} driver also calls the assembler and any other
3591 utilities needed to complete the generation of the required object
3592 files.
3593
3594 It is possible to supply several file names on the same @command{gcc}
3595 command. This causes @command{gcc} to call the appropriate compiler for
3596 each file. For example, the following command lists three separate
3597 files to be compiled:
3598
3599 @smallexample
3600 $ gcc -c x.adb y.adb z.c
3601 @end smallexample
3602
3603 @noindent
3604 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3605 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3606 The compiler generates three object files @file{x.o}, @file{y.o} and
3607 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3608 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3609 @ifclear vms
3610 except for
3611 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3612 @end ifclear
3613
3614 @node Switches for gcc
3615 @section Switches for @command{gcc}
3616
3617 @noindent
3618 The @command{gcc} command accepts switches that control the
3619 compilation process. These switches are fully described in this section.
3620 First we briefly list all the switches, in alphabetical order, then we
3621 describe the switches in more detail in functionally grouped sections.
3622
3623 More switches exist for GCC than those documented here, especially
3624 for specific targets. However, their use is not recommended as
3625 they may change code generation in ways that are incompatible with
3626 the Ada run-time library, or can cause inconsistencies between
3627 compilation units.
3628
3629 @menu
3630 * Output and Error Message Control::
3631 * Warning Message Control::
3632 * Debugging and Assertion Control::
3633 * Validity Checking::
3634 * Style Checking::
3635 * Run-Time Checks::
3636 * Stack Overflow Checking::
3637 * Using gcc for Syntax Checking::
3638 * Using gcc for Semantic Checking::
3639 * Compiling Different Versions of Ada::
3640 * Character Set Control::
3641 * File Naming Control::
3642 * Subprogram Inlining Control::
3643 * Auxiliary Output Control::
3644 * Debugging Control::
3645 * Exception Handling Control::
3646 * Units to Sources Mapping Files::
3647 * Integrated Preprocessing::
3648 * Code Generation Control::
3649 @ifset vms
3650 * Return Codes::
3651 @end ifset
3652 @end menu
3653
3654 @table @option
3655 @c !sort!
3656 @ifclear vms
3657 @cindex @option{-b} (@command{gcc})
3658 @item -b @var{target}
3659 Compile your program to run on @var{target}, which is the name of a
3660 system configuration. You must have a GNAT cross-compiler built if
3661 @var{target} is not the same as your host system.
3662
3663 @item -B@var{dir}
3664 @cindex @option{-B} (@command{gcc})
3665 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3666 from @var{dir} instead of the default location. Only use this switch
3667 when multiple versions of the GNAT compiler are available. See the
3668 @command{gcc} manual page for further details. You would normally use the
3669 @option{-b} or @option{-V} switch instead.
3670
3671 @item -c
3672 @cindex @option{-c} (@command{gcc})
3673 Compile. Always use this switch when compiling Ada programs.
3674
3675 Note: for some other languages when using @command{gcc}, notably in
3676 the case of C and C++, it is possible to use
3677 use @command{gcc} without a @option{-c} switch to
3678 compile and link in one step. In the case of GNAT, you
3679 cannot use this approach, because the binder must be run
3680 and @command{gcc} cannot be used to run the GNAT binder.
3681 @end ifclear
3682
3683 @item -fno-inline
3684 @cindex @option{-fno-inline} (@command{gcc})
3685 Suppresses all back-end inlining, even if other optimization or inlining
3686 switches are set.
3687 This includes suppression of inlining that results
3688 from the use of the pragma @code{Inline_Always}.
3689 See also @option{-gnatn} and @option{-gnatN}.
3690
3691 @item -fno-strict-aliasing
3692 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3693 Causes the compiler to avoid assumptions regarding non-aliasing
3694 of objects of different types. See
3695 @ref{Optimization and Strict Aliasing} for details.
3696
3697 @item -fstack-check
3698 @cindex @option{-fstack-check} (@command{gcc})
3699 Activates stack checking.
3700 See @ref{Stack Overflow Checking} for details of the use of this option.
3701
3702 @item ^-g^/DEBUG^
3703 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3704 Generate debugging information. This information is stored in the object
3705 file and copied from there to the final executable file by the linker,
3706 where it can be read by the debugger. You must use the
3707 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3708
3709 @item -gnat83
3710 @cindex @option{-gnat83} (@command{gcc})
3711 Enforce Ada 83 restrictions.
3712
3713 @item -gnat95
3714 @cindex @option{-gnat95} (@command{gcc})
3715 Enforce Ada 95 restrictions.
3716
3717 @item -gnat05
3718 @cindex @option{-gnat05} (@command{gcc})
3719 Allow full Ada 2005 features.
3720
3721 @item -gnata
3722 @cindex @option{-gnata} (@command{gcc})
3723 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3724 activated.
3725
3726 @item -gnatA
3727 @cindex @option{-gnatA} (@command{gcc})
3728 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3729 it will be ignored.
3730
3731 @item -gnatb
3732 @cindex @option{-gnatb} (@command{gcc})
3733 Generate brief messages to @file{stderr} even if verbose mode set.
3734
3735 @item -gnatc
3736 @cindex @option{-gnatc} (@command{gcc})
3737 Check syntax and semantics only (no code generation attempted).
3738
3739 @item -gnatd
3740 @cindex @option{-gnatd} (@command{gcc})
3741 Specify debug options for the compiler. The string of characters after
3742 the @option{-gnatd} specify the specific debug options. The possible
3743 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3744 compiler source file @file{debug.adb} for details of the implemented
3745 debug options. Certain debug options are relevant to applications
3746 programmers, and these are documented at appropriate points in this
3747 users guide.
3748
3749 @item -gnatD
3750 @cindex @option{-gnatD} (@command{gcc})
3751 Create expanded source files for source level debugging. This switch
3752 also suppress generation of cross-reference information
3753 (see @option{-gnatx}).
3754
3755 @item -gnatec=@var{path}
3756 @cindex @option{-gnatec} (@command{gcc})
3757 Specify a configuration pragma file
3758 @ifclear vms
3759 (the equal sign is optional)
3760 @end ifclear
3761 (@pxref{The Configuration Pragmas Files}).
3762
3763 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3764 @cindex @option{-gnateD} (@command{gcc})
3765 Defines a symbol, associated with value, for preprocessing.
3766 (@pxref{Integrated Preprocessing}).
3767
3768 @item -gnatef
3769 @cindex @option{-gnatef} (@command{gcc})
3770 Display full source path name in brief error messages.
3771
3772 @item -gnatem=@var{path}
3773 @cindex @option{-gnatem} (@command{gcc})
3774 Specify a mapping file
3775 @ifclear vms
3776 (the equal sign is optional)
3777 @end ifclear
3778 (@pxref{Units to Sources Mapping Files}).
3779
3780 @item -gnatep=@var{file}
3781 @cindex @option{-gnatep} (@command{gcc})
3782 Specify a preprocessing data file
3783 @ifclear vms
3784 (the equal sign is optional)
3785 @end ifclear
3786 (@pxref{Integrated Preprocessing}).
3787
3788 @item -gnatE
3789 @cindex @option{-gnatE} (@command{gcc})
3790 Full dynamic elaboration checks.
3791
3792 @item -gnatf
3793 @cindex @option{-gnatf} (@command{gcc})
3794 Full errors. Multiple errors per line, all undefined references, do not
3795 attempt to suppress cascaded errors.
3796
3797 @item -gnatF
3798 @cindex @option{-gnatF} (@command{gcc})
3799 Externals names are folded to all uppercase.
3800
3801 @item -gnatg
3802 @cindex @option{-gnatg} (@command{gcc})
3803 Internal GNAT implementation mode. This should not be used for
3804 applications programs, it is intended only for use by the compiler
3805 and its run-time library. For documentation, see the GNAT sources.
3806 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3807 are generated on unreferenced entities, and all warnings are treated
3808 as errors.
3809
3810 @item -gnatG
3811 @cindex @option{-gnatG} (@command{gcc})
3812 List generated expanded code in source form.
3813
3814 @item ^-gnath^/HELP^
3815 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3816 Output usage information. The output is written to @file{stdout}.
3817
3818 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3819 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3820 Identifier character set
3821 @ifclear vms
3822 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3823 @end ifclear
3824 @ifset vms
3825 For details of the possible selections for @var{c},
3826 see @ref{Character Set Control}.
3827 @end ifset
3828
3829 @item -gnatk=@var{n}
3830 @cindex @option{-gnatk} (@command{gcc})
3831 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3832
3833 @item -gnatl
3834 @cindex @option{-gnatl} (@command{gcc})
3835 Output full source listing with embedded error messages.
3836
3837 @item -gnatL
3838 @cindex @option{-gnatL} (@command{gcc})
3839 This switch is deprecated. You can use @option{--RTS=sjlj} instead to enable
3840 @code{setjmp/longjmp} exception mechanism.
3841
3842 @item -gnatm=@var{n}
3843 @cindex @option{-gnatm} (@command{gcc})
3844 Limit number of detected error or warning messages to @var{n}
3845 where @var{n} is in the range 1..999_999. The default setting if
3846 no switch is given is 9999. Compilation is terminated if this
3847 limit is exceeded.
3848
3849 @item -gnatn
3850 @cindex @option{-gnatn} (@command{gcc})
3851 Activate inlining for subprograms for which
3852 pragma @code{inline} is specified. This inlining is performed
3853 by the GCC back-end.
3854
3855 @item -gnatN
3856 @cindex @option{-gnatN} (@command{gcc})
3857 Activate front end inlining for subprograms for which
3858 pragma @code{Inline} is specified. This inlining is performed
3859 by the front end and will be visible in the
3860 @option{-gnatG} output.
3861 In some cases, this has proved more effective than the back end
3862 inlining resulting from the use of
3863 @option{-gnatn}.
3864 Note that
3865 @option{-gnatN} automatically implies
3866 @option{-gnatn} so it is not necessary
3867 to specify both options. There are a few cases that the back-end inlining
3868 catches that cannot be dealt with in the front-end.
3869
3870 @item -gnato
3871 @cindex @option{-gnato} (@command{gcc})
3872 Enable numeric overflow checking (which is not normally enabled by
3873 default). Not that division by zero is a separate check that is not
3874 controlled by this switch (division by zero checking is on by default).
3875
3876 @item -gnatp
3877 @cindex @option{-gnatp} (@command{gcc})
3878 Suppress all checks.
3879
3880 @item -gnatP
3881 @cindex @option{-gnatP} (@command{gcc})
3882 Enable polling. This is required on some systems (notably Windows NT) to
3883 obtain asynchronous abort and asynchronous transfer of control capability.
3884 See the description of pragma Polling in the GNAT Reference Manual for
3885 full details.
3886
3887 @item -gnatq
3888 @cindex @option{-gnatq} (@command{gcc})
3889 Don't quit; try semantics, even if parse errors.
3890
3891 @item -gnatQ
3892 @cindex @option{-gnatQ} (@command{gcc})
3893 Don't quit; generate @file{ALI} and tree files even if illegalities.
3894
3895 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3896 @cindex @option{-gnatR} (@command{gcc})
3897 Output representation information for declared types and objects.
3898
3899 @item -gnats
3900 @cindex @option{-gnats} (@command{gcc})
3901 Syntax check only.
3902
3903 @item -gnatS
3904 @cindex @option{-gnatS} (@command{gcc})
3905 Print package Standard.
3906
3907 @item -gnatt
3908 @cindex @option{-gnatt} (@command{gcc})
3909 Generate tree output file.
3910
3911 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3912 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
3913 All compiler tables start at @var{nnn} times usual starting size.
3914
3915 @item -gnatu
3916 @cindex @option{-gnatu} (@command{gcc})
3917 List units for this compilation.
3918
3919 @item -gnatU
3920 @cindex @option{-gnatU} (@command{gcc})
3921 Tag all error messages with the unique string ``error:''
3922
3923 @item -gnatv
3924 @cindex @option{-gnatv} (@command{gcc})
3925 Verbose mode. Full error output with source lines to @file{stdout}.
3926
3927 @item -gnatV
3928 @cindex @option{-gnatV} (@command{gcc})
3929 Control level of validity checking. See separate section describing
3930 this feature.
3931
3932 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
3933 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
3934 Warning mode where
3935 ^@var{xxx} is a string of option letters that^the list of options^ denotes
3936 the exact warnings that
3937 are enabled or disabled (@pxref{Warning Message Control}).
3938
3939 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3940 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
3941 Wide character encoding method
3942 @ifclear vms
3943 (@var{e}=n/h/u/s/e/8).
3944 @end ifclear
3945 @ifset vms
3946 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3947 @end ifset
3948
3949 @item -gnatx
3950 @cindex @option{-gnatx} (@command{gcc})
3951 Suppress generation of cross-reference information.
3952
3953 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3954 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
3955 Enable built-in style checks (@pxref{Style Checking}).
3956
3957 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3958 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
3959 Distribution stub generation and compilation
3960 @ifclear vms
3961 (@var{m}=r/c for receiver/caller stubs).
3962 @end ifclear
3963 @ifset vms
3964 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3965 to be generated and compiled).
3966 @end ifset
3967
3968 @item -gnatZ
3969 This switch is deprecated. When zero cost exception handling is not the
3970 default and this is supported, you can use @option{--RTS=zcx} instead.
3971
3972 @item ^-I^/SEARCH=^@var{dir}
3973 @cindex @option{^-I^/SEARCH^} (@command{gcc})
3974 @cindex RTL
3975 Direct GNAT to search the @var{dir} directory for source files needed by
3976 the current compilation
3977 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3978
3979 @item ^-I-^/NOCURRENT_DIRECTORY^
3980 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
3981 @cindex RTL
3982 Except for the source file named in the command line, do not look for source
3983 files in the directory containing the source file named in the command line
3984 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3985
3986 @ifclear vms
3987 @item -mbig-switch
3988 @cindex @option{-mbig-switch} (@command{gcc})
3989 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
3990 This standard gcc switch causes the compiler to use larger offsets in its
3991 jump table representation for @code{case} statements.
3992 This may result in less efficient code, but is sometimes necessary
3993 (for example on HP-UX targets)
3994 @cindex HP-UX and @option{-mbig-switch} option
3995 in order to compile large and/or nested @code{case} statements.
3996
3997 @item -o @var{file}
3998 @cindex @option{-o} (@command{gcc})
3999 This switch is used in @command{gcc} to redirect the generated object file
4000 and its associated ALI file. Beware of this switch with GNAT, because it may
4001 cause the object file and ALI file to have different names which in turn
4002 may confuse the binder and the linker.
4003 @end ifclear
4004
4005 @item -nostdinc
4006 @cindex @option{-nostdinc} (@command{gcc})
4007 Inhibit the search of the default location for the GNAT Run Time
4008 Library (RTL) source files.
4009
4010 @item -nostdlib
4011 @cindex @option{-nostdlib} (@command{gcc})
4012 Inhibit the search of the default location for the GNAT Run Time
4013 Library (RTL) ALI files.
4014
4015 @ifclear vms
4016 @item -O[@var{n}]
4017 @cindex @option{-O} (@command{gcc})
4018 @var{n} controls the optimization level.
4019
4020 @table @asis
4021 @item n = 0
4022 No optimization, the default setting if no @option{-O} appears
4023
4024 @item n = 1
4025 Normal optimization, the default if you specify @option{-O} without
4026 an operand.
4027
4028 @item n = 2
4029 Extensive optimization
4030
4031 @item n = 3
4032 Extensive optimization with automatic inlining of subprograms not
4033 specified by pragma @code{Inline}. This applies only to
4034 inlining within a unit. For details on control of inlining
4035 see @ref{Subprogram Inlining Control}.
4036 @end table
4037 @end ifclear
4038
4039 @ifset vms
4040 @item  /NOOPTIMIZE
4041 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4042 Equivalent to @option{/OPTIMIZE=NONE}.
4043 This is the default behavior in the absence of an @option{/OPTMIZE}
4044 qualifier.
4045
4046 @item /OPTIMIZE[=(keyword[,...])]
4047 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4048 Selects the level of optimization for your program. The supported
4049 keywords are as follows:
4050 @table @code
4051 @item   ALL
4052 Perform most optimizations, including those that
4053 are expensive.
4054 This is the default if the @option{/OPTMIZE} qualifier is supplied
4055 without keyword options.
4056
4057 @item   NONE
4058 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4059
4060 @item SOME
4061 Perform some optimizations, but omit ones that are costly.
4062
4063 @item   DEVELOPMENT
4064 Same as @code{SOME}.
4065
4066 @item   INLINING
4067 Full optimization, and also attempt automatic inlining of small
4068 subprograms within a unit even when pragma @code{Inline}
4069 is not specified (@pxref{Inlining of Subprograms}).
4070
4071 @item   UNROLL_LOOPS
4072 Try to unroll loops. This keyword may be specified together with
4073 any keyword above other than @code{NONE}. Loop unrolling
4074 usually, but not always, improves the performance of programs.
4075 @end table
4076 @end ifset
4077
4078 @ifclear vms
4079 @item -pass-exit-codes
4080 @cindex @option{-pass-exit-codes} (@command{gcc})
4081 Catch exit codes from the compiler and use the most meaningful as
4082 exit status.
4083 @end ifclear
4084
4085 @item --RTS=@var{rts-path}
4086 @cindex @option{--RTS} (@command{gcc})
4087 Specifies the default location of the runtime library. Same meaning as the
4088 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4089
4090 @item ^-S^/ASM^
4091 @cindex @option{^-S^/ASM^} (@command{gcc})
4092 ^Used in place of @option{-c} to^Used to^
4093 cause the assembler source file to be
4094 generated, using @file{^.s^.S^} as the extension,
4095 instead of the object file.
4096 This may be useful if you need to examine the generated assembly code.
4097
4098 @item ^-fverbose-asm^/VERBOSE_ASM^
4099 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4100 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4101 to cause the generated assembly code file to be annotated with variable
4102 names, making it significantly easier to follow.
4103
4104 @item ^-v^/VERBOSE^
4105 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4106 Show commands generated by the @command{gcc} driver. Normally used only for
4107 debugging purposes or if you need to be sure what version of the
4108 compiler you are executing.
4109
4110 @ifclear vms
4111 @item -V @var{ver}
4112 @cindex @option{-V} (@command{gcc})
4113 Execute @var{ver} version of the compiler. This is the @command{gcc}
4114 version, not the GNAT version.
4115 @end ifclear
4116
4117 @end table
4118
4119 @ifclear vms
4120 You may combine a sequence of GNAT switches into a single switch. For
4121 example, the combined switch
4122
4123 @cindex Combining GNAT switches
4124 @smallexample
4125 -gnatofi3
4126 @end smallexample
4127
4128 @noindent
4129 is equivalent to specifying the following sequence of switches:
4130
4131 @smallexample
4132 -gnato -gnatf -gnati3
4133 @end smallexample
4134 @end ifclear
4135
4136 @c NEED TO CHECK THIS FOR VMS
4137
4138 @noindent
4139 The following restrictions apply to the combination of switches
4140 in this manner:
4141
4142 @itemize @bullet
4143 @item
4144 The switch @option{-gnatc} if combined with other switches must come
4145 first in the string.
4146
4147 @item
4148 The switch @option{-gnats} if combined with other switches must come
4149 first in the string.
4150
4151 @item
4152 The switches
4153 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4154 may not be combined with any other switches.
4155
4156 @ifclear vms
4157 @item
4158 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4159 switch), then all further characters in the switch are interpreted
4160 as style modifiers (see description of @option{-gnaty}).
4161
4162 @item
4163 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4164 switch), then all further characters in the switch are interpreted
4165 as debug flags (see description of @option{-gnatd}).
4166
4167 @item
4168 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4169 switch), then all further characters in the switch are interpreted
4170 as warning mode modifiers (see description of @option{-gnatw}).
4171
4172 @item
4173 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4174 switch), then all further characters in the switch are interpreted
4175 as validity checking options (see description of @option{-gnatV}).
4176 @end ifclear
4177 @end itemize
4178
4179 @node Output and Error Message Control
4180 @subsection Output and Error Message Control
4181 @findex stderr
4182
4183 @noindent
4184 The standard default format for error messages is called ``brief format''.
4185 Brief format messages are written to @file{stderr} (the standard error
4186 file) and have the following form:
4187
4188 @smallexample
4189 e.adb:3:04: Incorrect spelling of keyword "function"
4190 e.adb:4:20: ";" should be "is"
4191 @end smallexample
4192
4193 @noindent
4194 The first integer after the file name is the line number in the file,
4195 and the second integer is the column number within the line.
4196 @code{glide} can parse the error messages
4197 and point to the referenced character.
4198 The following switches provide control over the error message
4199 format:
4200
4201 @table @option
4202 @c !sort!
4203 @item -gnatv
4204 @cindex @option{-gnatv} (@command{gcc})
4205 @findex stdout
4206 @ifclear vms
4207 The v stands for verbose.
4208 @end ifclear
4209 The effect of this setting is to write long-format error
4210 messages to @file{stdout} (the standard output file.
4211 The same program compiled with the
4212 @option{-gnatv} switch would generate:
4213
4214 @smallexample
4215 @cartouche
4216 3. funcion X (Q : Integer)
4217    |
4218 >>> Incorrect spelling of keyword "function"
4219 4. return Integer;
4220                  |
4221 >>> ";" should be "is"
4222 @end cartouche
4223 @end smallexample
4224
4225 @noindent
4226 The vertical bar indicates the location of the error, and the @samp{>>>}
4227 prefix can be used to search for error messages. When this switch is
4228 used the only source lines output are those with errors.
4229
4230 @item -gnatl
4231 @cindex @option{-gnatl} (@command{gcc})
4232 @ifclear vms
4233 The @code{l} stands for list.
4234 @end ifclear
4235 This switch causes a full listing of
4236 the file to be generated. The output might look as follows:
4237
4238 @smallexample
4239 @cartouche
4240  1. procedure E is
4241  2.    V : Integer;
4242  3.    funcion X (Q : Integer)
4243        |
4244     >>> Incorrect spelling of keyword "function"
4245  4.     return Integer;
4246                       |
4247     >>> ";" should be "is"
4248  5.    begin
4249  6.       return Q + Q;
4250  7.    end;
4251  8. begin
4252  9.    V := X + X;
4253 10.end E;
4254 @end cartouche
4255 @end smallexample
4256
4257 @noindent
4258 @findex stderr
4259 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4260 standard output is redirected, a brief summary is written to
4261 @file{stderr} (standard error) giving the number of error messages and
4262 warning messages generated.
4263
4264 @item -gnatU
4265 @cindex @option{-gnatU} (@command{gcc})
4266 This switch forces all error messages to be preceded by the unique
4267 string ``error:''. This means that error messages take a few more
4268 characters in space, but allows easy searching for and identification
4269 of error messages.
4270
4271 @item -gnatb
4272 @cindex @option{-gnatb} (@command{gcc})
4273 @ifclear vms
4274 The @code{b} stands for brief.
4275 @end ifclear
4276 This switch causes GNAT to generate the
4277 brief format error messages to @file{stderr} (the standard error
4278 file) as well as the verbose
4279 format message or full listing (which as usual is written to
4280 @file{stdout} (the standard output file).
4281
4282 @item -gnatm^^=^@var{n}
4283 @cindex @option{-gnatm} (@command{gcc})
4284 @ifclear vms
4285 The @code{m} stands for maximum.
4286 @end ifclear
4287 @var{n} is a decimal integer in the
4288 range of 1 to 999 and limits the number of error messages to be
4289 generated. For example, using @option{-gnatm2} might yield
4290
4291 @smallexample
4292 e.adb:3:04: Incorrect spelling of keyword "function"
4293 e.adb:5:35: missing ".."
4294 fatal error: maximum errors reached
4295 compilation abandoned
4296 @end smallexample
4297
4298 @item -gnatf
4299 @cindex @option{-gnatf} (@command{gcc})
4300 @cindex Error messages, suppressing
4301 @ifclear vms
4302 The @code{f} stands for full.
4303 @end ifclear
4304 Normally, the compiler suppresses error messages that are likely to be
4305 redundant. This switch causes all error
4306 messages to be generated. In particular, in the case of
4307 references to undefined variables. If a given variable is referenced
4308 several times, the normal format of messages is
4309 @smallexample
4310 e.adb:7:07: "V" is undefined (more references follow)
4311 @end smallexample
4312
4313 @noindent
4314 where the parenthetical comment warns that there are additional
4315 references to the variable @code{V}. Compiling the same program with the
4316 @option{-gnatf} switch yields
4317
4318 @smallexample
4319 e.adb:7:07: "V" is undefined
4320 e.adb:8:07: "V" is undefined
4321 e.adb:8:12: "V" is undefined
4322 e.adb:8:16: "V" is undefined
4323 e.adb:9:07: "V" is undefined
4324 e.adb:9:12: "V" is undefined
4325 @end smallexample
4326
4327 @noindent
4328 The @option{-gnatf} switch also generates additional information for
4329 some error messages.  Some examples are:
4330
4331 @itemize @bullet
4332 @item
4333 Full details on entities not available in high integrity mode
4334 @item
4335 Details on possibly non-portable unchecked conversion
4336 @item
4337 List possible interpretations for ambiguous calls
4338 @item
4339 Additional details on incorrect parameters
4340 @end itemize
4341
4342 @item -gnatq
4343 @cindex @option{-gnatq} (@command{gcc})
4344 @ifclear vms
4345 The @code{q} stands for quit (really ``don't quit'').
4346 @end ifclear
4347 In normal operation mode, the compiler first parses the program and
4348 determines if there are any syntax errors. If there are, appropriate
4349 error messages are generated and compilation is immediately terminated.
4350 This switch tells
4351 GNAT to continue with semantic analysis even if syntax errors have been
4352 found. This may enable the detection of more errors in a single run. On
4353 the other hand, the semantic analyzer is more likely to encounter some
4354 internal fatal error when given a syntactically invalid tree.
4355
4356 @item -gnatQ
4357 @cindex @option{-gnatQ} (@command{gcc})
4358 In normal operation mode, the @file{ALI} file is not generated if any
4359 illegalities are detected in the program. The use of @option{-gnatQ} forces
4360 generation of the @file{ALI} file. This file is marked as being in
4361 error, so it cannot be used for binding purposes, but it does contain
4362 reasonably complete cross-reference information, and thus may be useful
4363 for use by tools (e.g. semantic browsing tools or integrated development
4364 environments) that are driven from the @file{ALI} file. This switch
4365 implies @option{-gnatq}, since the semantic phase must be run to get a
4366 meaningful ALI file.
4367
4368 In addition, if @option{-gnatt} is also specified, then the tree file is
4369 generated even if there are illegalities. It may be useful in this case
4370 to also specify @option{-gnatq} to ensure that full semantic processing
4371 occurs. The resulting tree file can be processed by ASIS, for the purpose
4372 of providing partial information about illegal units, but if the error
4373 causes the tree to be badly malformed, then ASIS may crash during the
4374 analysis.
4375
4376 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4377 being in error, @command{gnatmake} will attempt to recompile the source when it
4378 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4379
4380 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4381 since ALI files are never generated if @option{-gnats} is set.
4382
4383 @end table
4384
4385 @node Warning Message Control
4386 @subsection Warning Message Control
4387 @cindex Warning messages
4388 @noindent
4389 In addition to error messages, which correspond to illegalities as defined
4390 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4391 situations.
4392
4393 First, the compiler considers some constructs suspicious and generates a
4394 warning message to alert you to a possible error. Second, if the
4395 compiler detects a situation that is sure to raise an exception at
4396 run time, it generates a warning message. The following shows an example
4397 of warning messages:
4398 @smallexample
4399 e.adb:4:24: warning: creation of object may raise Storage_Error
4400 e.adb:10:17: warning: static value out of range
4401 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4402 @end smallexample
4403
4404 @noindent
4405 GNAT considers a large number of situations as appropriate
4406 for the generation of warning messages. As always, warnings are not
4407 definite indications of errors. For example, if you do an out-of-range
4408 assignment with the deliberate intention of raising a
4409 @code{Constraint_Error} exception, then the warning that may be
4410 issued does not indicate an error. Some of the situations for which GNAT
4411 issues warnings (at least some of the time) are given in the following
4412 list. This list is not complete, and new warnings are often added to
4413 subsequent versions of GNAT. The list is intended to give a general idea
4414 of the kinds of warnings that are generated.
4415
4416 @itemize @bullet
4417 @item
4418 Possible infinitely recursive calls
4419
4420 @item
4421 Out-of-range values being assigned
4422
4423 @item
4424 Possible order of elaboration problems
4425
4426 @item
4427 Unreachable code
4428
4429 @item
4430 Fixed-point type declarations with a null range
4431
4432 @item
4433 Direct_IO or Sequential_IO instantiated with a type that has access values
4434
4435 @item
4436 Variables that are never assigned a value
4437
4438 @item
4439 Variables that are referenced before being initialized
4440
4441 @item
4442 Task entries with no corresponding @code{accept} statement
4443
4444 @item
4445 Duplicate accepts for the same task entry in a @code{select}
4446
4447 @item
4448 Objects that take too much storage
4449
4450 @item
4451 Unchecked conversion between types of differing sizes
4452
4453 @item
4454 Missing @code{return} statement along some execution path in a function
4455
4456 @item
4457 Incorrect (unrecognized) pragmas
4458
4459 @item
4460 Incorrect external names
4461
4462 @item
4463 Allocation from empty storage pool
4464
4465 @item
4466 Potentially blocking operation in protected type
4467
4468 @item
4469 Suspicious parenthesization of expressions
4470
4471 @item
4472 Mismatching bounds in an aggregate
4473
4474 @item
4475 Attempt to return local value by reference
4476
4477 @item
4478 Premature instantiation of a generic body
4479
4480 @item
4481 Attempt to pack aliased components
4482
4483 @item
4484 Out of bounds array subscripts
4485
4486 @item
4487 Wrong length on string assignment
4488
4489 @item
4490 Violations of style rules if style checking is enabled
4491
4492 @item
4493 Unused @code{with} clauses
4494
4495 @item
4496 @code{Bit_Order} usage that does not have any effect
4497
4498 @item
4499 @code{Standard.Duration} used to resolve universal fixed expression
4500
4501 @item
4502 Dereference of possibly null value
4503
4504 @item
4505 Declaration that is likely to cause storage error
4506
4507 @item
4508 Internal GNAT unit @code{with}'ed by application unit
4509
4510 @item
4511 Values known to be out of range at compile time
4512
4513 @item
4514 Unreferenced labels and variables
4515
4516 @item
4517 Address overlays that could clobber memory
4518
4519 @item
4520 Unexpected initialization when address clause present
4521
4522 @item
4523 Bad alignment for address clause
4524
4525 @item
4526 Useless type conversions
4527
4528 @item
4529 Redundant assignment statements and other redundant constructs
4530
4531 @item
4532 Useless exception handlers
4533
4534 @item
4535 Accidental hiding of name by child unit
4536
4537 @item
4538 Access before elaboration detected at compile time
4539
4540 @item
4541 A range in a @code{for} loop that is known to be null or might be null
4542
4543 @end itemize
4544
4545 @noindent
4546 The following switches are available to control the handling of
4547 warning messages:
4548
4549 @table @option
4550 @c !sort!
4551 @item -gnatwa
4552 @emph{Activate all optional errors.}
4553 @cindex @option{-gnatwa} (@command{gcc})
4554 This switch activates most optional warning messages, see remaining list
4555 in this section for details on optional warning messages that can be
4556 individually controlled.  The warnings that are not turned on by this
4557 switch are
4558 @option{-gnatwd} (implicit dereferencing),
4559 @option{-gnatwh} (hiding),
4560 and @option{-gnatwl} (elaboration warnings).
4561 All other optional warnings are turned on.
4562
4563 @item -gnatwA
4564 @emph{Suppress all optional errors.}
4565 @cindex @option{-gnatwA} (@command{gcc})
4566 This switch suppresses all optional warning messages, see remaining list
4567 in this section for details on optional warning messages that can be
4568 individually controlled.
4569
4570 @item -gnatwc
4571 @emph{Activate warnings on conditionals.}
4572 @cindex @option{-gnatwc} (@command{gcc})
4573 @cindex Conditionals, constant
4574 This switch activates warnings for conditional expressions used in
4575 tests that are known to be True or False at compile time. The default
4576 is that such warnings are not generated.
4577 Note that this warning does
4578 not get issued for the use of boolean variables or constants whose
4579 values are known at compile time, since this is a standard technique
4580 for conditional compilation in Ada, and this would generate too many
4581 ``false positive'' warnings.
4582 This warning can also be turned on using @option{-gnatwa}.
4583
4584 @item -gnatwC
4585 @emph{Suppress warnings on conditionals.}
4586 @cindex @option{-gnatwC} (@command{gcc})
4587 This switch suppresses warnings for conditional expressions used in
4588 tests that are known to be True or False at compile time.
4589
4590 @item -gnatwd
4591 @emph{Activate warnings on implicit dereferencing.}
4592 @cindex @option{-gnatwd} (@command{gcc})
4593 If this switch is set, then the use of a prefix of an access type
4594 in an indexed component, slice, or selected component without an
4595 explicit @code{.all} will generate a warning. With this warning
4596 enabled, access checks occur only at points where an explicit
4597 @code{.all} appears in the source code (assuming no warnings are
4598 generated as a result of this switch). The default is that such
4599 warnings are not generated.
4600 Note that @option{-gnatwa} does not affect the setting of
4601 this warning option.
4602
4603 @item -gnatwD
4604 @emph{Suppress warnings on implicit dereferencing.}
4605 @cindex @option{-gnatwD} (@command{gcc})
4606 @cindex Implicit dereferencing
4607 @cindex Dereferencing, implicit
4608 This switch suppresses warnings for implicit dereferences in
4609 indexed components, slices, and selected components.
4610
4611 @item -gnatwe
4612 @emph{Treat warnings as errors.}
4613 @cindex @option{-gnatwe} (@command{gcc})
4614 @cindex Warnings, treat as error
4615 This switch causes warning messages to be treated as errors.
4616 The warning string still appears, but the warning messages are counted
4617 as errors, and prevent the generation of an object file.
4618
4619 @item -gnatwf
4620 @emph{Activate warnings on unreferenced formals.}
4621 @cindex @option{-gnatwf} (@command{gcc})
4622 @cindex Formals, unreferenced
4623 This switch causes a warning to be generated if a formal parameter
4624 is not referenced in the body of the subprogram. This warning can
4625 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4626
4627 @item -gnatwF
4628 @emph{Suppress warnings on unreferenced formals.}
4629 @cindex @option{-gnatwF} (@command{gcc})
4630 This switch suppresses warnings for unreferenced formal
4631 parameters. Note that the
4632 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4633 effect of warning on unreferenced entities other than subprogram
4634 formals.
4635
4636 @item -gnatwg
4637 @emph{Activate warnings on unrecognized pragmas.}
4638 @cindex @option{-gnatwg} (@command{gcc})
4639 @cindex Pragmas, unrecognized
4640 This switch causes a warning to be generated if an unrecognized
4641 pragma is encountered. Apart from issuing this warning, the
4642 pragma is ignored and has no effect. This warning can
4643 also be turned on using @option{-gnatwa}. The default
4644 is that such warnings are issued (satisfying the Ada Reference
4645 Manual requirement that such warnings appear).
4646
4647 @item -gnatwG
4648 @emph{Suppress warnings on unrecognized pragmas.}
4649 @cindex @option{-gnatwG} (@command{gcc})
4650 This switch suppresses warnings for unrecognized pragmas.
4651
4652 @item -gnatwh
4653 @emph{Activate warnings on hiding.}
4654 @cindex @option{-gnatwh} (@command{gcc})
4655 @cindex Hiding of Declarations
4656 This switch activates warnings on hiding declarations.
4657 A declaration is considered hiding
4658 if it is for a non-overloadable entity, and it declares an entity with the
4659 same name as some other entity that is directly or use-visible. The default
4660 is that such warnings are not generated.
4661 Note that @option{-gnatwa} does not affect the setting of this warning option.
4662
4663 @item -gnatwH
4664 @emph{Suppress warnings on hiding.}
4665 @cindex @option{-gnatwH} (@command{gcc})
4666 This switch suppresses warnings on hiding declarations.
4667
4668 @item -gnatwi
4669 @emph{Activate warnings on implementation units.}
4670 @cindex @option{-gnatwi} (@command{gcc})
4671 This switch activates warnings for a @code{with} of an internal GNAT
4672 implementation unit, defined as any unit from the @code{Ada},
4673 @code{Interfaces}, @code{GNAT},
4674 ^^@code{DEC},^ or @code{System}
4675 hierarchies that is not
4676 documented in either the Ada Reference Manual or the GNAT
4677 Programmer's Reference Manual. Such units are intended only
4678 for internal implementation purposes and should not be @code{with}'ed
4679 by user programs. The default is that such warnings are generated
4680 This warning can also be turned on using @option{-gnatwa}.
4681
4682 @item -gnatwI
4683 @emph{Disable warnings on implementation units.}
4684 @cindex @option{-gnatwI} (@command{gcc})
4685 This switch disables warnings for a @code{with} of an internal GNAT
4686 implementation unit.
4687
4688 @item -gnatwj
4689 @emph{Activate warnings on obsolescent features (Annex J).}
4690 @cindex @option{-gnatwj} (@command{gcc})
4691 @cindex Features, obsolescent
4692 @cindex Obsolescent features
4693 If this warning option is activated, then warnings are generated for
4694 calls to subprograms marked with @code{pragma Obsolescent} and
4695 for use of features in Annex J of the Ada Reference Manual. In the
4696 case of Annex J, not all features are flagged. In particular use
4697 of the renamed packages (like @code{Text_IO}) and use of package
4698 @code{ASCII} are not flagged, since these are very common and
4699 would generate many annoying positive warnings. The default is that
4700 such warnings are not generated.
4701
4702 In addition to the above cases, warnings are also generated for
4703 GNAT features that have been provided in past versions but which
4704 have been superceded (typically by features in the new Ada standard).
4705 For example, @code{pragma Ravenscar} will be flagged since its
4706 function is replaced by @code{pragma Profile(Ravenscar)}.
4707
4708 Note that this warning option functions differently from the
4709 restriction @code{No_Obsolescent_Features} in two respects.
4710 First, the restriction applies only to annex J features.
4711 Second, the restriction does flag uses of package @code{ASCII}.
4712
4713 @item -gnatwJ
4714 @emph{Suppress warnings on obsolescent features (Annex J).}
4715 @cindex @option{-gnatwJ} (@command{gcc})
4716 This switch disables warnings on use of obsolescent features.
4717
4718 @item -gnatwk
4719 @emph{Activate warnings on variables that could be constants.}
4720 @cindex @option{-gnatwk} (@command{gcc})
4721 This switch activates warnings for variables that are initialized but
4722 never modified, and then could be declared constants.
4723
4724 @item -gnatwK
4725 @emph{Suppress warnings on variables that could be constants.}
4726 @cindex @option{-gnatwK} (@command{gcc})
4727 This switch disables warnings on variables that could be declared constants.
4728
4729 @item -gnatwl
4730 @emph{Activate warnings for missing elaboration pragmas.}
4731 @cindex @option{-gnatwl} (@command{gcc})
4732 @cindex Elaboration, warnings
4733 This switch activates warnings on missing
4734 @code{pragma Elaborate_All} statements.
4735 See the section in this guide on elaboration checking for details on
4736 when such pragma should be used. Warnings are also generated if you
4737 are using the static mode of elaboration, and a @code{pragma Elaborate}
4738 is encountered. The default is that such warnings
4739 are not generated.
4740 This warning is not automatically turned on by the use of @option{-gnatwa}.
4741
4742 @item -gnatwL
4743 @emph{Suppress warnings for missing elaboration pragmas.}
4744 @cindex @option{-gnatwL} (@command{gcc})
4745 This switch suppresses warnings on missing pragma Elaborate_All statements.
4746 See the section in this guide on elaboration checking for details on
4747 when such pragma should be used.
4748
4749 @item -gnatwm
4750 @emph{Activate warnings on modified but unreferenced variables.}
4751 @cindex @option{-gnatwm} (@command{gcc})
4752 This switch activates warnings for variables that are assigned (using
4753 an initialization value or with one or more assignment statements) but
4754 whose value is never read. The warning is suppressed for volatile
4755 variables and also for variables that are renamings of other variables
4756 or for which an address clause is given.
4757 This warning can also be turned on using @option{-gnatwa}.
4758
4759 @item -gnatwM
4760 @emph{Disable warnings on modified but unreferenced variables.}
4761 @cindex @option{-gnatwM} (@command{gcc})
4762 This switch disables warnings for variables that are assigned or
4763 initialized, but never read.
4764
4765 @item -gnatwn
4766 @emph{Set normal warnings mode.}
4767 @cindex @option{-gnatwn} (@command{gcc})
4768 This switch sets normal warning mode, in which enabled warnings are
4769 issued and treated as warnings rather than errors. This is the default
4770 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4771 an explicit @option{-gnatws} or
4772 @option{-gnatwe}. It also cancels the effect of the
4773 implicit @option{-gnatwe} that is activated by the
4774 use of @option{-gnatg}.
4775
4776 @item -gnatwo
4777 @emph{Activate warnings on address clause overlays.}
4778 @cindex @option{-gnatwo} (@command{gcc})
4779 @cindex Address Clauses, warnings
4780 This switch activates warnings for possibly unintended initialization
4781 effects of defining address clauses that cause one variable to overlap
4782 another. The default is that such warnings are generated.
4783 This warning can also be turned on using @option{-gnatwa}.
4784
4785 @item -gnatwO
4786 @emph{Suppress warnings on address clause overlays.}
4787 @cindex @option{-gnatwO} (@command{gcc})
4788 This switch suppresses warnings on possibly unintended initialization
4789 effects of defining address clauses that cause one variable to overlap
4790 another.
4791
4792 @item -gnatwp
4793 @emph{Activate warnings on ineffective pragma Inlines.}
4794 @cindex @option{-gnatwp} (@command{gcc})
4795 @cindex Inlining, warnings
4796 This switch activates warnings for failure of front end inlining
4797 (activated by @option{-gnatN}) to inline a particular call. There are
4798 many reasons for not being able to inline a call, including most
4799 commonly that the call is too complex to inline.
4800 This warning can also be turned on using @option{-gnatwa}.
4801
4802 @item -gnatwP
4803 @emph{Suppress warnings on ineffective pragma Inlines.}
4804 @cindex @option{-gnatwP} (@command{gcc})
4805 This switch suppresses warnings on ineffective pragma Inlines. If the
4806 inlining mechanism cannot inline a call, it will simply ignore the
4807 request silently.
4808
4809 @item -gnatwr
4810 @emph{Activate warnings on redundant constructs.}
4811 @cindex @option{-gnatwr} (@command{gcc})
4812 This switch activates warnings for redundant constructs. The following
4813 is the current list of constructs regarded as redundant:
4814 This warning can also be turned on using @option{-gnatwa}.
4815
4816 @itemize @bullet
4817 @item
4818 Assignment of an item to itself.
4819 @item
4820 Type conversion that converts an expression to its own type.
4821 @item
4822 Use of the attribute @code{Base} where @code{typ'Base} is the same
4823 as @code{typ}.
4824 @item
4825 Use of pragma @code{Pack} when all components are placed by a record
4826 representation clause.
4827 @item
4828 Exception handler containing only a reraise statement (raise with no
4829 operand) which has no effect.
4830 @item
4831 Use of the operator abs on an operand that is known at compile time
4832 to be non-negative
4833 @item
4834 Comparison of boolean expressions to an explicit True value.
4835 @end itemize
4836
4837 @item -gnatwR
4838 @emph{Suppress warnings on redundant constructs.}
4839 @cindex @option{-gnatwR} (@command{gcc})
4840 This switch suppresses warnings for redundant constructs.
4841
4842 @item -gnatws
4843 @emph{Suppress all warnings.}
4844 @cindex @option{-gnatws} (@command{gcc})
4845 This switch completely suppresses the
4846 output of all warning messages from the GNAT front end.
4847 Note that it does not suppress warnings from the @command{gcc} back end.
4848 To suppress these back end warnings as well, use the switch @option{-w}
4849 in addition to @option{-gnatws}.
4850
4851 @item -gnatwu
4852 @emph{Activate warnings on unused entities.}
4853 @cindex @option{-gnatwu} (@command{gcc})
4854 This switch activates warnings to be generated for entities that
4855 are declared but not referenced, and for units that are @code{with}'ed
4856 and not
4857 referenced. In the case of packages, a warning is also generated if
4858 no entities in the package are referenced. This means that if the package
4859 is referenced but the only references are in @code{use}
4860 clauses or @code{renames}
4861 declarations, a warning is still generated. A warning is also generated
4862 for a generic package that is @code{with}'ed but never instantiated.
4863 In the case where a package or subprogram body is compiled, and there
4864 is a @code{with} on the corresponding spec
4865 that is only referenced in the body,
4866 a warning is also generated, noting that the
4867 @code{with} can be moved to the body. The default is that
4868 such warnings are not generated.
4869 This switch also activates warnings on unreferenced formals
4870 (it includes the effect of @option{-gnatwf}).
4871 This warning can also be turned on using @option{-gnatwa}.
4872
4873 @item -gnatwU
4874 @emph{Suppress warnings on unused entities.}
4875 @cindex @option{-gnatwU} (@command{gcc})
4876 This switch suppresses warnings for unused entities and packages.
4877 It also turns off warnings on unreferenced formals (and thus includes
4878 the effect of @option{-gnatwF}).
4879
4880 @item -gnatwv
4881 @emph{Activate warnings on unassigned variables.}
4882 @cindex @option{-gnatwv} (@command{gcc})
4883 @cindex Unassigned variable warnings
4884 This switch activates warnings for access to variables which
4885 may not be properly initialized. The default is that
4886 such warnings are generated.
4887
4888 @item -gnatwV
4889 @emph{Suppress warnings on unassigned variables.}
4890 @cindex @option{-gnatwV} (@command{gcc})
4891 This switch suppresses warnings for access to variables which
4892 may not be properly initialized.
4893
4894 @item -gnatwx
4895 @emph{Activate warnings on Export/Import pragmas.}
4896 @cindex @option{-gnatwx} (@command{gcc})
4897 @cindex Export/Import pragma warnings
4898 This switch activates warnings on Export/Import pragmas when
4899 the compiler detects a possible conflict between the Ada and
4900 foreign language calling sequences. For example, the use of
4901 default parameters in a convention C procedure is dubious
4902 because the C compiler cannot supply the proper default, so
4903 a warning is issued. The default is that such warnings are
4904 generated.
4905
4906 @item -gnatwX
4907 @emph{Suppress warnings on Export/Import pragmas.}
4908 @cindex @option{-gnatwX} (@command{gcc})
4909 This switch suppresses warnings on Export/Import pragmas.
4910 The sense of this is that you are telling the compiler that
4911 you know what you are doing in writing the pragma, and it
4912 should not complain at you.
4913
4914 @item -gnatwz
4915 @emph{Activate warnings on unchecked conversions.}
4916 @cindex @option{-gnatwz} (@command{gcc})
4917 @cindex Unchecked_Conversion warnings
4918 This switch activates warnings for unchecked conversions
4919 where the types are known at compile time to have different
4920 sizes. The default
4921 is that such warnings are generated.
4922
4923 @item -gnatwZ
4924 @emph{Suppress warnings on unchecked conversions.}
4925 @cindex @option{-gnatwZ} (@command{gcc})
4926 This switch suppresses warnings for unchecked conversions
4927 where the types are known at compile time to have different
4928 sizes.
4929
4930 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
4931 @cindex @option{-Wuninitialized}
4932 The warnings controlled by the @option{-gnatw} switch are generated by the
4933 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
4934 can provide additional warnings. One such useful warning is provided by
4935 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
4936 conjunction with tunrning on optimization mode. This causes the flow
4937 analysis circuits of the back end optimizer to output additional
4938 warnings about uninitialized variables.
4939
4940 @item ^-w^/NO_BACK_END_WARNINGS^
4941 @cindex @option{-w}
4942 This switch suppresses warnings from the @option{^gcc^GCC^} back end. It may
4943 be used in conjunction with @option{-gnatws} to ensure that all warnings
4944 are suppressed during the entire compilation process.
4945
4946 @end table
4947
4948 @noindent
4949 @ifclear vms
4950 A string of warning parameters can be used in the same parameter. For example:
4951
4952 @smallexample
4953 -gnatwaLe
4954 @end smallexample
4955
4956 @noindent
4957 will turn on all optional warnings except for elaboration pragma warnings,
4958 and also specify that warnings should be treated as errors.
4959 @end ifclear
4960 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
4961
4962 @table @option
4963 @c !sort!
4964 @item -gnatwC
4965 @item -gnatwD
4966 @item -gnatwF
4967 @item -gnatwg
4968 @item -gnatwH
4969 @item -gnatwi
4970 @item -gnatwJ
4971 @item -gnatwK
4972 @item -gnatwL
4973 @item -gnatwM
4974 @item -gnatwn
4975 @item -gnatwo
4976 @item -gnatwP
4977 @item -gnatwR
4978 @item -gnatwU
4979 @item -gnatwv
4980 @item -gnatwz
4981 @item -gnatwx
4982
4983 @end table
4984
4985 @node Debugging and Assertion Control
4986 @subsection Debugging and Assertion Control
4987
4988 @table @option
4989 @item -gnata
4990 @cindex @option{-gnata} (@command{gcc})
4991 @findex Assert
4992 @findex Debug
4993 @cindex Assertions
4994
4995 @noindent
4996 The pragmas @code{Assert} and @code{Debug} normally have no effect and
4997 are ignored. This switch, where @samp{a} stands for assert, causes
4998 @code{Assert} and @code{Debug} pragmas to be activated.
4999
5000 The pragmas have the form:
5001
5002 @smallexample
5003 @cartouche
5004    @b{pragma} Assert (@var{Boolean-expression} [,
5005                       @var{static-string-expression}])
5006    @b{pragma} Debug (@var{procedure call})
5007 @end cartouche
5008 @end smallexample
5009
5010 @noindent
5011 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5012 If the result is @code{True}, the pragma has no effect (other than
5013 possible side effects from evaluating the expression). If the result is
5014 @code{False}, the exception @code{Assert_Failure} declared in the package
5015 @code{System.Assertions} is
5016 raised (passing @var{static-string-expression}, if present, as the
5017 message associated with the exception). If no string expression is
5018 given the default is a string giving the file name and line number
5019 of the pragma.
5020
5021 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5022 @code{pragma Debug} may appear within a declaration sequence, allowing
5023 debugging procedures to be called between declarations.
5024
5025 @ifset vms
5026 @item /DEBUG[=debug-level]
5027 @itemx  /NODEBUG
5028 Specifies how much debugging information is to be included in
5029 the resulting object file where 'debug-level' is one of the following:
5030 @table @code
5031 @item   TRACEBACK
5032 Include both debugger symbol records and traceback
5033 the object file.
5034 This is the default setting.
5035 @item   ALL
5036 Include both debugger symbol records and traceback in
5037 object file.
5038 @item   NONE
5039 Excludes both debugger symbol records and traceback
5040 the object file. Same as /NODEBUG.
5041 @item   SYMBOLS
5042 Includes only debugger symbol records in the object
5043 file. Note that this doesn't include traceback information.
5044 @end table
5045 @end ifset
5046 @end table
5047
5048 @node Validity Checking
5049 @subsection Validity Checking
5050 @findex Validity Checking
5051
5052 @noindent
5053 The Ada 95 Reference Manual has specific requirements for checking
5054 for invalid values. In particular, RM 13.9.1 requires that the
5055 evaluation of invalid values (for example from unchecked conversions),
5056 not result in erroneous execution. In GNAT, the result of such an
5057 evaluation in normal default mode is to either use the value
5058 unmodified, or to raise Constraint_Error in those cases where use
5059 of the unmodified value would cause erroneous execution. The cases
5060 where unmodified values might lead to erroneous execution are case
5061 statements (where a wild jump might result from an invalid value),
5062 and subscripts on the left hand side (where memory corruption could
5063 occur as a result of an invalid value).
5064
5065 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5066 checking mode.
5067 @ifclear vms
5068 The @code{x} argument is a string of letters that
5069 indicate validity checks that are performed or not performed in addition
5070 to the default checks described above.
5071 @end ifclear
5072 @ifset vms
5073 The options allowed for this qualifier
5074 indicate validity checks that are performed or not performed in addition
5075 to the default checks described above.
5076 @end ifset
5077
5078 @table @option
5079 @c !sort!
5080 @item -gnatVa
5081 @emph{All validity checks.}
5082 @cindex @option{-gnatVa} (@command{gcc})
5083 All validity checks are turned on.
5084 @ifclear vms
5085 That is, @option{-gnatVa} is
5086 equivalent to @option{gnatVcdfimorst}.
5087 @end ifclear
5088
5089 @item -gnatVc
5090 @emph{Validity checks for copies.}
5091 @cindex @option{-gnatVc} (@command{gcc})
5092 The right hand side of assignments, and the initializing values of
5093 object declarations are validity checked.
5094
5095 @item -gnatVd
5096 @emph{Default (RM) validity checks.}
5097 @cindex @option{-gnatVd} (@command{gcc})
5098 Some validity checks are done by default following normal Ada semantics
5099 (RM 13.9.1 (9-11)).
5100 A check is done in case statements that the expression is within the range
5101 of the subtype. If it is not, Constraint_Error is raised.
5102 For assignments to array components, a check is done that the expression used
5103 as index is within the range. If it is not, Constraint_Error is raised.
5104 Both these validity checks may be turned off using switch @option{-gnatVD}.
5105 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5106 switch @option{-gnatVd} will leave the checks turned on.
5107 Switch @option{-gnatVD} should be used only if you are sure that all such
5108 expressions have valid values. If you use this switch and invalid values
5109 are present, then the program is erroneous, and wild jumps or memory
5110 overwriting may occur.
5111
5112 @item -gnatVf
5113 @emph{Validity checks for floating-point values.}
5114 @cindex @option{-gnatVf} (@command{gcc})
5115 In the absence of this switch, validity checking occurs only for discrete
5116 values. If @option{-gnatVf} is specified, then validity checking also applies
5117 for floating-point values, and NaN's and infinities are considered invalid,
5118 as well as out of range values for constrained types. Note that this means
5119 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5120 in which floating-point values are checked depends on the setting of other
5121 options. For example,
5122 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5123 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5124 (the order does not matter) specifies that floating-point parameters of mode
5125 @code{in} should be validity checked.
5126
5127 @item -gnatVi
5128 @emph{Validity checks for @code{in} mode parameters}
5129 @cindex @option{-gnatVi} (@command{gcc})
5130 Arguments for parameters of mode @code{in} are validity checked in function
5131 and procedure calls at the point of call.
5132
5133 @item -gnatVm
5134 @emph{Validity checks for @code{in out} mode parameters.}
5135 @cindex @option{-gnatVm} (@command{gcc})
5136 Arguments for parameters of mode @code{in out} are validity checked in
5137 procedure calls at the point of call. The @code{'m'} here stands for
5138 modify, since this concerns parameters that can be modified by the call.
5139 Note that there is no specific option to test @code{out} parameters,
5140 but any reference within the subprogram will be tested in the usual
5141 manner, and if an invalid value is copied back, any reference to it
5142 will be subject to validity checking.
5143
5144 @item -gnatVn
5145 @emph{No validity checks.}
5146 @cindex @option{-gnatVn} (@command{gcc})
5147 This switch turns off all validity checking, including the default checking
5148 for case statements and left hand side subscripts. Note that the use of
5149 the switch @option{-gnatp} suppresses all run-time checks, including
5150 validity checks, and thus implies @option{-gnatVn}. When this switch
5151 is used, it cancels any other @option{-gnatV} previously issued.
5152
5153 @item -gnatVo
5154 @emph{Validity checks for operator and attribute operands.}
5155 @cindex @option{-gnatVo} (@command{gcc})
5156 Arguments for predefined operators and attributes are validity checked.
5157 This includes all operators in package @code{Standard},
5158 the shift operators defined as intrinsic in package @code{Interfaces}
5159 and operands for attributes such as @code{Pos}. Checks are also made
5160 on individual component values for composite comparisons.
5161
5162 @item -gnatVp
5163 @emph{Validity checks for parameters.}
5164 @cindex @option{-gnatVp} (@command{gcc})
5165 This controls the treatment of parameters within a subprogram (as opposed
5166 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5167 of parameters on a call. If either of these call options is used, then
5168 normally an assumption is made within a subprogram that the input arguments
5169 have been validity checking at the point of call, and do not need checking
5170 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5171 is not made, and parameters are not assumed to be valid, so their validity
5172 will be checked (or rechecked) within the subprogram.
5173
5174 @item -gnatVr
5175 @emph{Validity checks for function returns.}
5176 @cindex @option{-gnatVr} (@command{gcc})
5177 The expression in @code{return} statements in functions is validity
5178 checked.
5179
5180 @item -gnatVs
5181 @emph{Validity checks for subscripts.}
5182 @cindex @option{-gnatVs} (@command{gcc})
5183 All subscripts expressions are checked for validity, whether they appear
5184 on the right side or left side (in default mode only left side subscripts
5185 are validity checked).
5186
5187 @item -gnatVt
5188 @emph{Validity checks for tests.}
5189 @cindex @option{-gnatVt} (@command{gcc})
5190 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5191 statements are checked, as well as guard expressions in entry calls.
5192
5193 @end table
5194
5195 @noindent
5196 The @option{-gnatV} switch may be followed by
5197 ^a string of letters^a list of options^
5198 to turn on a series of validity checking options.
5199 For example,
5200 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5201 specifies that in addition to the default validity checking, copies and
5202 function return expressions are to be validity checked.
5203 In order to make it easier
5204 to specify the desired combination of effects,
5205 @ifclear vms
5206 the upper case letters @code{CDFIMORST} may
5207 be used to turn off the corresponding lower case option.
5208 @end ifclear
5209 @ifset vms
5210 the prefix @code{NO} on an option turns off the corresponding validity
5211 checking:
5212 @itemize @bullet
5213 @item @code{NOCOPIES}
5214 @item @code{NODEFAULT}
5215 @item @code{NOFLOATS}
5216 @item @code{NOIN_PARAMS}
5217 @item @code{NOMOD_PARAMS}
5218 @item @code{NOOPERANDS}
5219 @item @code{NORETURNS}
5220 @item @code{NOSUBSCRIPTS}
5221 @item @code{NOTESTS}
5222 @end itemize
5223 @end ifset
5224 Thus
5225 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5226 turns on all validity checking options except for
5227 checking of @code{@b{in out}} procedure arguments.
5228
5229 The specification of additional validity checking generates extra code (and
5230 in the case of @option{-gnatVa} the code expansion can be substantial.
5231 However, these additional checks can be very useful in detecting
5232 uninitialized variables, incorrect use of unchecked conversion, and other
5233 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5234 is useful in conjunction with the extra validity checking, since this
5235 ensures that wherever possible uninitialized variables have invalid values.
5236
5237 See also the pragma @code{Validity_Checks} which allows modification of
5238 the validity checking mode at the program source level, and also allows for
5239 temporary disabling of validity checks.
5240
5241 @node Style Checking
5242 @subsection Style Checking
5243 @findex Style checking
5244
5245 @noindent
5246 The @option{-gnaty^x^(option,option,...)^} switch
5247 @cindex @option{-gnaty} (@command{gcc})
5248 causes the compiler to
5249 enforce specified style rules. A limited set of style rules has been used
5250 in writing the GNAT sources themselves. This switch allows user programs
5251 to activate all or some of these checks. If the source program fails a
5252 specified style check, an appropriate warning message is given, preceded by
5253 the character sequence ``(style)''.
5254 @ifset vms
5255 @code{(option,option,...)} is a sequence of keywords
5256 @end ifset
5257 @ifclear vms
5258 The string @var{x} is a sequence of letters or digits
5259 @end ifclear
5260 indicating the particular style
5261 checks to be performed. The following checks are defined:
5262
5263 @table @option
5264 @c !sort!
5265 @item 1-9
5266 @emph{Specify indentation level.}
5267 If a digit from 1-9 appears
5268 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5269 then proper indentation is checked, with the digit indicating the
5270 indentation level required.
5271 The general style of required indentation is as specified by
5272 the examples in the Ada Reference Manual. Full line comments must be
5273 aligned with the @code{--} starting on a column that is a multiple of
5274 the alignment level.
5275
5276 @item ^a^ATTRIBUTE^
5277 @emph{Check attribute casing.}
5278 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5279 then attribute names, including the case of keywords such as @code{digits}
5280 used as attributes names, must be written in mixed case, that is, the
5281 initial letter and any letter following an underscore must be uppercase.
5282 All other letters must be lowercase.
5283
5284 @item ^b^BLANKS^
5285 @emph{Blanks not allowed at statement end.}
5286 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5287 trailing blanks are not allowed at the end of statements. The purpose of this
5288 rule, together with h (no horizontal tabs), is to enforce a canonical format
5289 for the use of blanks to separate source tokens.
5290
5291 @item ^c^COMMENTS^
5292 @emph{Check comments.}
5293 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5294 then comments must meet the following set of rules:
5295
5296 @itemize @bullet
5297
5298 @item
5299 The ``@code{--}'' that starts the column must either start in column one,
5300 or else at least one blank must precede this sequence.
5301
5302 @item
5303 Comments that follow other tokens on a line must have at least one blank
5304 following the ``@code{--}'' at the start of the comment.
5305
5306 @item
5307 Full line comments must have two blanks following the ``@code{--}'' that
5308 starts the comment, with the following exceptions.
5309
5310 @item
5311 A line consisting only of the ``@code{--}'' characters, possibly preceded
5312 by blanks is permitted.
5313
5314 @item
5315 A comment starting with ``@code{--x}'' where @code{x} is a special character
5316 is permitted.
5317 This allows proper processing of the output generated by specialized tools
5318 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5319 annotation
5320 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5321 special character is defined as being in one of the ASCII ranges
5322 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5323 Note that this usage is not permitted
5324 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5325
5326 @item
5327 A line consisting entirely of minus signs, possibly preceded by blanks, is
5328 permitted. This allows the construction of box comments where lines of minus
5329 signs are used to form the top and bottom of the box.
5330
5331 @item
5332 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5333 least one blank follows the initial ``@code{--}''. Together with the preceding
5334 rule, this allows the construction of box comments, as shown in the following
5335 example:
5336 @smallexample
5337 ---------------------------
5338 -- This is a box comment --
5339 -- with two text lines.  --
5340 ---------------------------
5341 @end smallexample
5342 @end itemize
5343
5344 @item ^e^END^
5345 @emph{Check end/exit labels.}
5346 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5347 optional labels on @code{end} statements ending subprograms and on
5348 @code{exit} statements exiting named loops, are required to be present.
5349
5350 @item ^f^VTABS^
5351 @emph{No form feeds or vertical tabs.}
5352 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5353 neither form feeds nor vertical tab characters are permitted
5354 in the source text.
5355
5356 @item ^h^HTABS^
5357 @emph{No horizontal tabs.}
5358 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5359 horizontal tab characters are not permitted in the source text.
5360 Together with the b (no blanks at end of line) check, this
5361 enforces a canonical form for the use of blanks to separate
5362 source tokens.
5363
5364 @item ^i^IF_THEN^
5365 @emph{Check if-then layout.}
5366 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5367 then the keyword @code{then} must appear either on the same
5368 line as corresponding @code{if}, or on a line on its own, lined
5369 up under the @code{if} with at least one non-blank line in between
5370 containing all or part of the condition to be tested.
5371
5372 @item ^k^KEYWORD^
5373 @emph{Check keyword casing.}
5374 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5375 all keywords must be in lower case (with the exception of keywords
5376 such as @code{digits} used as attribute names to which this check
5377 does not apply).
5378
5379 @item ^l^LAYOUT^
5380 @emph{Check layout.}
5381 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5382 layout of statement and declaration constructs must follow the
5383 recommendations in the Ada Reference Manual, as indicated by the
5384 form of the syntax rules. For example an @code{else} keyword must
5385 be lined up with the corresponding @code{if} keyword.
5386
5387 There are two respects in which the style rule enforced by this check
5388 option are more liberal than those in the Ada Reference Manual. First
5389 in the case of record declarations, it is permissible to put the
5390 @code{record} keyword on the same line as the @code{type} keyword, and
5391 then the @code{end} in @code{end record} must line up under @code{type}.
5392 For example, either of the following two layouts is acceptable:
5393
5394 @smallexample @c ada
5395 @cartouche
5396 type q is record
5397    a : integer;
5398    b : integer;
5399 end record;
5400
5401 type q is
5402    record
5403       a : integer;
5404       b : integer;
5405    end record;
5406 @end cartouche
5407 @end smallexample
5408
5409 @noindent
5410 Second, in the case of a block statement, a permitted alternative
5411 is to put the block label on the same line as the @code{declare} or
5412 @code{begin} keyword, and then line the @code{end} keyword up under
5413 the block label. For example both the following are permitted:
5414
5415 @smallexample @c ada
5416 @cartouche
5417 Block : declare
5418    A : Integer := 3;
5419 begin
5420    Proc (A, A);
5421 end Block;
5422
5423 Block :
5424    declare
5425       A : Integer := 3;
5426    begin
5427       Proc (A, A);
5428    end Block;
5429 @end cartouche
5430 @end smallexample
5431
5432 @noindent
5433 The same alternative format is allowed for loops. For example, both of
5434 the following are permitted:
5435
5436 @smallexample @c ada
5437 @cartouche
5438 Clear : while J < 10 loop
5439    A (J) := 0;
5440 end loop Clear;
5441
5442 Clear :
5443    while J < 10 loop
5444       A (J) := 0;
5445    end loop Clear;
5446 @end cartouche
5447 @end smallexample
5448
5449 @item ^Lnnn^MAX_NESTING=nnn^
5450 @emph{Set maximum nesting level}
5451 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5452 the range 0-999, appears in the string after @option{-gnaty} then the
5453 maximum level of nesting of constructs (including subprograms, loops,
5454 blocks, packages, and conditionals) may not exceed the given value. A
5455 value of zero disconnects this style check.
5456
5457 @item ^m^LINE_LENGTH^
5458 @emph{Check maximum line length.}
5459 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5460 then the length of source lines must not exceed 79 characters, including
5461 any trailing blanks. The value of 79 allows convenient display on an
5462 80 character wide device or window, allowing for possible special
5463 treatment of 80 character lines. Note that this count is of raw
5464 characters in the source text. This means that a tab character counts
5465 as one character in this count and a wide character sequence counts as
5466 several characters (however many are needed in the encoding).
5467
5468 @item ^Mnnn^MAX_LENGTH=nnn^
5469 @emph{Set maximum line length.}
5470 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5471 the string after @option{-gnaty} then the length of lines must not exceed the
5472 given value.
5473
5474 @item ^n^STANDARD_CASING^
5475 @emph{Check casing of entities in Standard.}
5476 If the ^letter n^word STANDARD_CASING^ appears in the string
5477 after @option{-gnaty} then any identifier from Standard must be cased
5478 to match the presentation in the Ada Reference Manual (for example,
5479 @code{Integer} and @code{ASCII.NUL}).
5480
5481 @item ^o^ORDERED_SUBPROGRAMS^
5482 @emph{Check order of subprogram bodies.}
5483 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5484 after @option{-gnaty} then all subprogram bodies in a given scope
5485 (e.g. a package body) must be in alphabetical order. The ordering
5486 rule uses normal Ada rules for comparing strings, ignoring casing
5487 of letters, except that if there is a trailing numeric suffix, then
5488 the value of this suffix is used in the ordering (e.g. Junk2 comes
5489 before Junk10).
5490
5491 @item ^p^PRAGMA^
5492 @emph{Check pragma casing.}
5493 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5494 pragma names must be written in mixed case, that is, the
5495 initial letter and any letter following an underscore must be uppercase.
5496 All other letters must be lowercase.
5497
5498 @item ^r^REFERENCES^
5499 @emph{Check references.}
5500 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5501 then all identifier references must be cased in the same way as the
5502 corresponding declaration. No specific casing style is imposed on
5503 identifiers. The only requirement is for consistency of references
5504 with declarations.
5505
5506 @item ^s^SPECS^
5507 @emph{Check separate specs.}
5508 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5509 separate declarations (``specs'') are required for subprograms (a
5510 body is not allowed to serve as its own declaration). The only
5511 exception is that parameterless library level procedures are
5512 not required to have a separate declaration. This exception covers
5513 the most frequent form of main program procedures.
5514
5515 @item ^t^TOKEN^
5516 @emph{Check token spacing.}
5517 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5518 the following token spacing rules are enforced:
5519
5520 @itemize @bullet
5521
5522 @item
5523 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5524
5525 @item
5526 The token @code{=>} must be surrounded by spaces.
5527
5528 @item
5529 The token @code{<>} must be preceded by a space or a left parenthesis.
5530
5531 @item
5532 Binary operators other than @code{**} must be surrounded by spaces.
5533 There is no restriction on the layout of the @code{**} binary operator.
5534
5535 @item
5536 Colon must be surrounded by spaces.
5537
5538 @item
5539 Colon-equal (assignment, initialization) must be surrounded by spaces.
5540
5541 @item
5542 Comma must be the first non-blank character on the line, or be
5543 immediately preceded by a non-blank character, and must be followed
5544 by a space.
5545
5546 @item
5547 If the token preceding a left parenthesis ends with a letter or digit, then
5548 a space must separate the two tokens.
5549
5550 @item
5551 A right parenthesis must either be the first non-blank character on
5552 a line, or it must be preceded by a non-blank character.
5553
5554 @item
5555 A semicolon must not be preceded by a space, and must not be followed by
5556 a non-blank character.
5557
5558 @item
5559 A unary plus or minus may not be followed by a space.
5560
5561 @item
5562 A vertical bar must be surrounded by spaces.
5563 @end itemize
5564
5565 @item ^x^XTRA_PARENS^
5566 @emph{Check extra parentheses.}
5567 Check for the use of an unnecessary extra level of parentheses (C-style)
5568 around conditions in @code{if} statements, @code{while} statements and
5569 @code{exit} statements.
5570
5571 @end table
5572
5573 @noindent
5574 In the above rules, appearing in column one is always permitted, that is,
5575 counts as meeting either a requirement for a required preceding space,
5576 or as meeting a requirement for no preceding space.
5577
5578 Appearing at the end of a line is also always permitted, that is, counts
5579 as meeting either a requirement for a following space, or as meeting
5580 a requirement for no following space.
5581
5582 @noindent
5583 If any of these style rules is violated, a message is generated giving
5584 details on the violation. The initial characters of such messages are
5585 always ``@code{(style)}''. Note that these messages are treated as warning
5586 messages, so they normally do not prevent the generation of an object
5587 file. The @option{-gnatwe} switch can be used to treat warning messages,
5588 including style messages, as fatal errors.
5589
5590 The switch
5591 @ifclear vms
5592 @option{-gnaty} on its own (that is not
5593 followed by any letters or digits),
5594 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
5595 options enabled with the exception of -gnatyo,
5596 @end ifclear
5597 @ifset vms
5598 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5599 the exception of ORDERED_SUBPROGRAMS,
5600 @end ifset
5601 with an indentation level of 3. This is the standard
5602 checking option that is used for the GNAT sources.
5603
5604 The switch
5605 @ifclear vms
5606 @option{-gnatyN}
5607 @end ifclear
5608 @ifset vms
5609 /STYLE_CHECKS=NONE
5610 @end ifset
5611 clears any previously set style checks.
5612
5613 @node Run-Time Checks
5614 @subsection Run-Time Checks
5615 @cindex Division by zero
5616 @cindex Access before elaboration
5617 @cindex Checks, division by zero
5618 @cindex Checks, access before elaboration
5619
5620 @noindent
5621 If you compile with the default options, GNAT will insert many run-time
5622 checks into the compiled code, including code that performs range
5623 checking against constraints, but not arithmetic overflow checking for
5624 integer operations (including division by zero) or checks for access
5625 before elaboration on subprogram calls. All other run-time checks, as
5626 required by the Ada 95 Reference Manual, are generated by default.
5627 The following @command{gcc} switches refine this default behavior:
5628
5629 @table @option
5630 @c !sort!
5631 @item -gnatp
5632 @cindex @option{-gnatp} (@command{gcc})
5633 @cindex Suppressing checks
5634 @cindex Checks, suppressing
5635 @findex Suppress
5636 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5637 had been present in the source. Validity checks are also suppressed (in
5638 other words @option{-gnatp} also implies @option{-gnatVn}.
5639 Use this switch to improve the performance
5640 of the code at the expense of safety in the presence of invalid data or
5641 program bugs.
5642
5643 @item -gnato
5644 @cindex @option{-gnato} (@command{gcc})
5645 @cindex Overflow checks
5646 @cindex Check, overflow
5647 Enables overflow checking for integer operations.
5648 This causes GNAT to generate slower and larger executable
5649 programs by adding code to check for overflow (resulting in raising
5650 @code{Constraint_Error} as required by standard Ada
5651 semantics). These overflow checks correspond to situations in which
5652 the true value of the result of an operation may be outside the base
5653 range of the result type. The following example shows the distinction:
5654
5655 @smallexample @c ada
5656 X1 : Integer := Integer'Last;
5657 X2 : Integer range 1 .. 5 := 5;
5658 X3 : Integer := Integer'Last;
5659 X4 : Integer range 1 .. 5 := 5;
5660 F  : Float := 2.0E+20;
5661 ...
5662 X1 := X1 + 1;
5663 X2 := X2 + 1;
5664 X3 := Integer (F);
5665 X4 := Integer (F);
5666 @end smallexample
5667
5668 @noindent
5669 Here the first addition results in a value that is outside the base range
5670 of Integer, and hence requires an overflow check for detection of the
5671 constraint error. Thus the first assignment to @code{X1} raises a
5672 @code{Constraint_Error} exception only if @option{-gnato} is set.
5673
5674 The second increment operation results in a violation
5675 of the explicit range constraint, and such range checks are always
5676 performed (unless specifically suppressed with a pragma @code{suppress}
5677 or the use of @option{-gnatp}).
5678
5679 The two conversions of @code{F} both result in values that are outside
5680 the base range of type @code{Integer} and thus will raise
5681 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5682 The fact that the result of the second conversion is assigned to
5683 variable @code{X4} with a restricted range is irrelevant, since the problem
5684 is in the conversion, not the assignment.
5685
5686 Basically the rule is that in the default mode (@option{-gnato} not
5687 used), the generated code assures that all integer variables stay
5688 within their declared ranges, or within the base range if there is
5689 no declared range. This prevents any serious problems like indexes
5690 out of range for array operations.
5691
5692 What is not checked in default mode is an overflow that results in
5693 an in-range, but incorrect value. In the above example, the assignments
5694 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5695 range of the target variable, but the result is wrong in the sense that
5696 it is too large to be represented correctly. Typically the assignment
5697 to @code{X1} will result in wrap around to the largest negative number.
5698 The conversions of @code{F} will result in some @code{Integer} value
5699 and if that integer value is out of the @code{X4} range then the
5700 subsequent assignment would generate an exception.
5701
5702 @findex Machine_Overflows
5703 Note that the @option{-gnato} switch does not affect the code generated
5704 for any floating-point operations; it applies only to integer
5705 semantics).
5706 For floating-point, GNAT has the @code{Machine_Overflows}
5707 attribute set to @code{False} and the normal mode of operation is to
5708 generate IEEE NaN and infinite values on overflow or invalid operations
5709 (such as dividing 0.0 by 0.0).
5710
5711 The reason that we distinguish overflow checking from other kinds of
5712 range constraint checking is that a failure of an overflow check can
5713 generate an incorrect value, but cannot cause erroneous behavior. This
5714 is unlike the situation with a constraint check on an array subscript,
5715 where failure to perform the check can result in random memory description,
5716 or the range check on a case statement, where failure to perform the check
5717 can cause a wild jump.
5718
5719 Note again that @option{-gnato} is off by default, so overflow checking is
5720 not performed in default mode. This means that out of the box, with the
5721 default settings, GNAT does not do all the checks expected from the
5722 language description in the Ada Reference Manual. If you want all constraint
5723 checks to be performed, as described in this Manual, then you must
5724 explicitly use the -gnato switch either on the @command{gnatmake} or
5725 @command{gcc} command.
5726
5727 @item -gnatE
5728 @cindex @option{-gnatE} (@command{gcc})
5729 @cindex Elaboration checks
5730 @cindex Check, elaboration
5731 Enables dynamic checks for access-before-elaboration
5732 on subprogram calls and generic instantiations.
5733 For full details of the effect and use of this switch,
5734 @xref{Compiling Using gcc}.
5735 @end table
5736
5737 @findex Unsuppress
5738 @noindent
5739 The setting of these switches only controls the default setting of the
5740 checks. You may modify them using either @code{Suppress} (to remove
5741 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5742 the program source.
5743
5744 @node Stack Overflow Checking
5745 @subsection Stack Overflow Checking
5746 @cindex Stack Overflow Checking
5747 @cindex -fstack-check
5748
5749 @noindent
5750 For most operating systems, @command{gcc} does not perform stack overflow
5751 checking by default. This means that if the main environment task or
5752 some other task exceeds the available stack space, then unpredictable
5753 behavior will occur.
5754
5755 To activate stack checking, compile all units with the gcc option
5756 @option{-fstack-check}. For example:
5757
5758 @smallexample
5759 gcc -c -fstack-check package1.adb
5760 @end smallexample
5761
5762 @noindent
5763 Units compiled with this option will generate extra instructions to check
5764 that any use of the stack (for procedure calls or for declaring local
5765 variables in declare blocks) do not exceed the available stack space.
5766 If the space is exceeded, then a @code{Storage_Error} exception is raised.
5767
5768 For declared tasks, the stack size is always controlled by the size
5769 given in an applicable @code{Storage_Size} pragma (or is set to
5770 the default size if no pragma is used.
5771
5772 For the environment task, the stack size depends on
5773 system defaults and is unknown to the compiler. The stack
5774 may even dynamically grow on some systems, precluding the
5775 normal Ada semantics for stack overflow. In the worst case,
5776 unbounded stack usage, causes unbounded stack expansion
5777 resulting in the system running out of virtual memory.
5778
5779 The stack checking may still work correctly if a fixed
5780 size stack is allocated, but this cannot be guaranteed.
5781 To ensure that a clean exception is signalled for stack
5782 overflow, set the environment variable
5783 @code{GNAT_STACK_LIMIT} to indicate the maximum
5784 stack area that can be used, as in:
5785 @cindex GNAT_STACK_LIMIT
5786
5787 @smallexample
5788 SET GNAT_STACK_LIMIT 1600
5789 @end smallexample
5790
5791 @noindent
5792 The limit is given in kilobytes, so the above declaration would
5793 set the stack limit of the environment task to 1.6 megabytes.
5794 Note that the only purpose of this usage is to limit the amount
5795 of stack used by the environment task. If it is necessary to
5796 increase the amount of stack for the environment task, then this
5797 is an operating systems issue, and must be addressed with the
5798 appropriate operating systems commands.
5799
5800 @node Using gcc for Syntax Checking
5801 @subsection Using @command{gcc} for Syntax Checking
5802 @table @option
5803 @item -gnats
5804 @cindex @option{-gnats} (@command{gcc})
5805 @ifclear vms
5806
5807 @noindent
5808 The @code{s} stands for ``syntax''.
5809 @end ifclear
5810
5811 Run GNAT in syntax checking only mode. For
5812 example, the command
5813
5814 @smallexample
5815 $ gcc -c -gnats x.adb
5816 @end smallexample
5817
5818 @noindent
5819 compiles file @file{x.adb} in syntax-check-only mode. You can check a
5820 series of files in a single command
5821 @ifclear vms
5822 , and can use wild cards to specify such a group of files.
5823 Note that you must specify the @option{-c} (compile
5824 only) flag in addition to the @option{-gnats} flag.
5825 @end ifclear
5826 .
5827 You may use other switches in conjunction with @option{-gnats}. In
5828 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5829 format of any generated error messages.
5830
5831 When the source file is empty or contains only empty lines and/or comments,
5832 the output is a warning:
5833
5834 @smallexample
5835 $ gcc -c -gnats -x ada toto.txt
5836 toto.txt:1:01: warning: empty file, contains no compilation units
5837 $
5838 @end smallexample
5839
5840 Otherwise, the output is simply the error messages, if any. No object file or
5841 ALI file is generated by a syntax-only compilation. Also, no units other
5842 than the one specified are accessed. For example, if a unit @code{X}
5843 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5844 check only mode does not access the source file containing unit
5845 @code{Y}.
5846
5847 @cindex Multiple units, syntax checking
5848 Normally, GNAT allows only a single unit in a source file. However, this
5849 restriction does not apply in syntax-check-only mode, and it is possible
5850 to check a file containing multiple compilation units concatenated
5851 together. This is primarily used by the @code{gnatchop} utility
5852 (@pxref{Renaming Files Using gnatchop}).
5853 @end table
5854
5855 @node Using gcc for Semantic Checking
5856 @subsection Using @command{gcc} for Semantic Checking
5857 @table @option
5858 @item -gnatc
5859 @cindex @option{-gnatc} (@command{gcc})
5860
5861 @ifclear vms
5862 @noindent
5863 The @code{c} stands for ``check''.
5864 @end ifclear
5865 Causes the compiler to operate in semantic check mode,
5866 with full checking for all illegalities specified in the
5867 Ada 95 Reference Manual, but without generation of any object code
5868 (no object file is generated).
5869
5870 Because dependent files must be accessed, you must follow the GNAT
5871 semantic restrictions on file structuring to operate in this mode:
5872
5873 @itemize @bullet
5874 @item
5875 The needed source files must be accessible
5876 (@pxref{Search Paths and the Run-Time Library (RTL)}).
5877
5878 @item
5879 Each file must contain only one compilation unit.
5880
5881 @item
5882 The file name and unit name must match (@pxref{File Naming Rules}).
5883 @end itemize
5884
5885 The output consists of error messages as appropriate. No object file is
5886 generated. An @file{ALI} file is generated for use in the context of
5887 cross-reference tools, but this file is marked as not being suitable
5888 for binding (since no object file is generated).
5889 The checking corresponds exactly to the notion of
5890 legality in the Ada 95 Reference Manual.
5891
5892 Any unit can be compiled in semantics-checking-only mode, including
5893 units that would not normally be compiled (subunits,
5894 and specifications where a separate body is present).
5895 @end table
5896
5897 @node Compiling Different Versions of Ada
5898 @subsection Compiling Different Versions of Ada
5899 @table @option
5900 @cindex Compatibility with Ada 83
5901 @cindex Ada 83 mode
5902 @cindex Ada 95 mode
5903 @cindex Ada 2005 mode
5904
5905 GNAT is primarily an Ada 95 compiler, but the switches described in
5906 this section allow operation in Ada 83 compatibility mode, and also
5907 allow the use of a preliminary implementation of many of the expected
5908 new features in Ada 2005, the forthcoming new version of the standard.
5909
5910 @item -gnat83 (Ada 83 Compatibility Mode)
5911 @cindex @option{-gnat83} (@command{gcc})
5912 @cindex ACVC, Ada 83 tests
5913
5914 @noindent
5915 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
5916 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
5917 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
5918 where this can be done easily.
5919 It is not possible to guarantee this switch does a perfect
5920 job; for example, some subtle tests, such as are
5921 found in earlier ACVC tests (and that have been removed from the ACATS suite
5922 for Ada 95), might not compile correctly.
5923 Nevertheless, this switch may be useful in some circumstances, for example
5924 where, due to contractual reasons, legacy code needs to be maintained
5925 using only Ada 83 features.
5926
5927 With few exceptions (most notably the need to use @code{<>} on
5928 @cindex Generic formal parameters
5929 unconstrained generic formal parameters, the use of the new Ada 95
5930 reserved words, and the use of packages
5931 with optional bodies), it is not necessary to use the
5932 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
5933 exceptions, Ada 95 is upwardly compatible with Ada 83. This
5934 means that a correct Ada 83 program is usually also a correct Ada 95
5935 program.
5936 For further information, please refer to @ref{Compatibility and Porting Guide}.
5937
5938 @item -gnat95 (Ada 95 mode)
5939 @cindex @option{-gnat95} (@command{gcc})
5940
5941 @noindent
5942 GNAT is primarily an Ada 95 compiler, and all current releases of GNAT Pro
5943 compile in Ada 95 mode by default. Typically, Ada 95 is sufficiently upwards
5944 compatible with Ada 83, that legacy Ada 83 programs may be compiled using
5945 this default Ada95 mode without problems (see section above describing the
5946 use of @option{-gnat83} to run in Ada 83 mode).
5947
5948 In Ada 95 mode, the use of Ada 2005 features will in general cause error
5949 messages or warnings. Some specialized releases of GNAT (notably the GAP
5950 academic version) operate in Ada 2005 mode by default (see section below
5951 describing the use of @option{-gnat05} to run in Ada 2005 mode). For such
5952 versions the @option{-gnat95} switch may be used to enforce Ada 95 mode.
5953 This option also can be used to cancel the effect of a previous
5954 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
5955
5956
5957 @item -gnat05 (Ada 2005 mode)
5958 @cindex @option{-gnat05} (@command{gcc})
5959
5960 @noindent
5961 Although GNAT is primarily an Ada 95 compiler, it can be set to operate
5962 in Ada 2005 mode using this option. Although the new standard has not
5963 yet been issued (as of early 2005), many features have been discussed and
5964 approved in ``Ada Issues'' (AI's). For the text of these AI's, see
5965 @url{www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}. Included with GNAT
5966 releases is a file @file{features-ada0y} that describes the current set
5967 of implemented Ada 2005 features.
5968
5969 If these features are used in Ada 95 mode (which is the normal default),
5970 then error messages or warnings may be
5971 generated, reflecting the fact that these new features are otherwise
5972 unauthorized extensions to Ada 95. The use of the @option{-gnat05}
5973 switch (or an equivalent pragma) causes these messages to be suppressed.
5974
5975 Note that some specialized releases of GNAT (notably the GAP academic
5976 version) have Ada 2005 mode on by default, and in such environments,
5977 the Ada 2005 features can be used freely without the use of switches.
5978
5979 @end table
5980
5981 @node Character Set Control
5982 @subsection Character Set Control
5983 @table @option
5984 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
5985 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
5986
5987 @noindent
5988 Normally GNAT recognizes the Latin-1 character set in source program
5989 identifiers, as described in the Ada 95 Reference Manual.
5990 This switch causes
5991 GNAT to recognize alternate character sets in identifiers. @var{c} is a
5992 single character ^^or word^ indicating the character set, as follows:
5993
5994 @table @code
5995 @item 1
5996 ISO 8859-1 (Latin-1) identifiers
5997
5998 @item 2
5999 ISO 8859-2 (Latin-2) letters allowed in identifiers
6000
6001 @item 3
6002 ISO 8859-3 (Latin-3) letters allowed in identifiers
6003
6004 @item 4
6005 ISO 8859-4 (Latin-4) letters allowed in identifiers
6006
6007 @item 5
6008 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6009
6010 @item 9
6011 ISO 8859-15 (Latin-9) letters allowed in identifiers
6012
6013 @item ^p^PC^
6014 IBM PC letters (code page 437) allowed in identifiers
6015
6016 @item ^8^PC850^
6017 IBM PC letters (code page 850) allowed in identifiers
6018
6019 @item ^f^FULL_UPPER^
6020 Full upper-half codes allowed in identifiers
6021
6022 @item ^n^NO_UPPER^
6023 No upper-half codes allowed in identifiers
6024
6025 @item ^w^WIDE^
6026 Wide-character codes (that is, codes greater than 255)
6027 allowed in identifiers
6028 @end table
6029
6030 @xref{Foreign Language Representation}, for full details on the
6031 implementation of these character sets.
6032
6033 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6034 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6035 Specify the method of encoding for wide characters.
6036 @var{e} is one of the following:
6037
6038 @table @code
6039
6040 @item ^h^HEX^
6041 Hex encoding (brackets coding also recognized)
6042
6043 @item ^u^UPPER^
6044 Upper half encoding (brackets encoding also recognized)
6045
6046 @item ^s^SHIFT_JIS^
6047 Shift/JIS encoding (brackets encoding also recognized)
6048
6049 @item ^e^EUC^
6050 EUC encoding (brackets encoding also recognized)
6051
6052 @item ^8^UTF8^
6053 UTF-8 encoding (brackets encoding also recognized)
6054
6055 @item ^b^BRACKETS^
6056 Brackets encoding only (default value)
6057 @end table
6058 For full details on the these encoding
6059 methods see @ref{Wide Character Encodings}.
6060 Note that brackets coding is always accepted, even if one of the other
6061 options is specified, so for example @option{-gnatW8} specifies that both
6062 brackets and @code{UTF-8} encodings will be recognized. The units that are
6063 with'ed directly or indirectly will be scanned using the specified
6064 representation scheme, and so if one of the non-brackets scheme is
6065 used, it must be used consistently throughout the program. However,
6066 since brackets encoding is always recognized, it may be conveniently
6067 used in standard libraries, allowing these libraries to be used with
6068 any of the available coding schemes.
6069 scheme. If no @option{-gnatW?} parameter is present, then the default
6070 representation is Brackets encoding only.
6071
6072 Note that the wide character representation that is specified (explicitly
6073 or by default) for the main program also acts as the default encoding used
6074 for Wide_Text_IO files if not specifically overridden by a WCEM form
6075 parameter.
6076
6077 @end table
6078 @node File Naming Control
6079 @subsection File Naming Control
6080
6081 @table @option
6082 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6083 @cindex @option{-gnatk} (@command{gcc})
6084 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6085 1-999, indicates the maximum allowable length of a file name (not
6086 including the @file{.ads} or @file{.adb} extension). The default is not
6087 to enable file name krunching.
6088
6089 For the source file naming rules, @xref{File Naming Rules}.
6090 @end table
6091
6092 @node Subprogram Inlining Control
6093 @subsection Subprogram Inlining Control
6094
6095 @table @option
6096 @c !sort!
6097 @item -gnatn
6098 @cindex @option{-gnatn} (@command{gcc})
6099 @ifclear vms
6100 The @code{n} here is intended to suggest the first syllable of the
6101 word ``inline''.
6102 @end ifclear
6103 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6104 inlining to actually occur, optimization must be enabled. To enable
6105 inlining of subprograms specified by pragma @code{Inline},
6106 you must also specify this switch.
6107 In the absence of this switch, GNAT does not attempt
6108 inlining and does not need to access the bodies of
6109 subprograms for which @code{pragma Inline} is specified if they are not
6110 in the current unit.
6111
6112 If you specify this switch the compiler will access these bodies,
6113 creating an extra source dependency for the resulting object file, and
6114 where possible, the call will be inlined.
6115 For further details on when inlining is possible
6116 see @ref{Inlining of Subprograms}.
6117
6118 @item -gnatN
6119 @cindex @option{-gnatN} (@command{gcc})
6120 The front end inlining activated by this switch is generally more extensive,
6121 and quite often more effective than the standard @option{-gnatn} inlining mode.
6122 It will also generate additional dependencies.
6123 Note that
6124 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6125 to specify both options.
6126 @end table
6127
6128 @node Auxiliary Output Control
6129 @subsection Auxiliary Output Control
6130
6131 @table @option
6132 @item -gnatt
6133 @cindex @option{-gnatt} (@command{gcc})
6134 @cindex Writing internal trees
6135 @cindex Internal trees, writing to file
6136 Causes GNAT to write the internal tree for a unit to a file (with the
6137 extension @file{.adt}.
6138 This not normally required, but is used by separate analysis tools.
6139 Typically
6140 these tools do the necessary compilations automatically, so you should
6141 not have to specify this switch in normal operation.
6142
6143 @item -gnatu
6144 @cindex @option{-gnatu} (@command{gcc})
6145 Print a list of units required by this compilation on @file{stdout}.
6146 The listing includes all units on which the unit being compiled depends
6147 either directly or indirectly.
6148
6149 @ifclear vms
6150 @item -pass-exit-codes
6151 @cindex @option{-pass-exit-codes} (@command{gcc})
6152 If this switch is not used, the exit code returned by @command{gcc} when
6153 compiling multiple files indicates whether all source files have
6154 been successfully used to generate object files or not.
6155
6156 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6157 exit status and allows an integrated development environment to better
6158 react to a compilation failure. Those exit status are:
6159
6160 @table @asis
6161 @item 5
6162 There was an error in at least one source file.
6163 @item 3
6164 At least one source file did not generate an object file.
6165 @item 2
6166 The compiler died unexpectedly (internal error for example).
6167 @item 0
6168 An object file has been generated for every source file.
6169 @end table
6170 @end ifclear
6171 @end table
6172
6173 @node Debugging Control
6174 @subsection Debugging Control
6175
6176 @table @option
6177 @c !sort!
6178 @cindex Debugging options
6179 @ifclear vms
6180 @item -gnatd@var{x}
6181 @cindex @option{-gnatd} (@command{gcc})
6182 Activate internal debugging switches. @var{x} is a letter or digit, or
6183 string of letters or digits, which specifies the type of debugging
6184 outputs desired. Normally these are used only for internal development
6185 or system debugging purposes. You can find full documentation for these
6186 switches in the body of the @code{Debug} unit in the compiler source
6187 file @file{debug.adb}.
6188 @end ifclear
6189
6190 @item -gnatG
6191 @cindex @option{-gnatG} (@command{gcc})
6192 This switch causes the compiler to generate auxiliary output containing
6193 a pseudo-source listing of the generated expanded code. Like most Ada
6194 compilers, GNAT works by first transforming the high level Ada code into
6195 lower level constructs. For example, tasking operations are transformed
6196 into calls to the tasking run-time routines. A unique capability of GNAT
6197 is to list this expanded code in a form very close to normal Ada source.
6198 This is very useful in understanding the implications of various Ada
6199 usage on the efficiency of the generated code. There are many cases in
6200 Ada (e.g. the use of controlled types), where simple Ada statements can
6201 generate a lot of run-time code. By using @option{-gnatG} you can identify
6202 these cases, and consider whether it may be desirable to modify the coding
6203 approach to improve efficiency.
6204
6205 The format of the output is very similar to standard Ada source, and is
6206 easily understood by an Ada programmer. The following special syntactic
6207 additions correspond to low level features used in the generated code that
6208 do not have any exact analogies in pure Ada source form. The following
6209 is a partial list of these special constructions. See the specification
6210 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6211
6212 @table @code
6213 @item new @var{xxx} [storage_pool = @var{yyy}]
6214 Shows the storage pool being used for an allocator.
6215
6216 @item at end @var{procedure-name};
6217 Shows the finalization (cleanup) procedure for a scope.
6218
6219 @item (if @var{expr} then @var{expr} else @var{expr})
6220 Conditional expression equivalent to the @code{x?y:z} construction in C.
6221
6222 @item @var{target}^^^(@var{source})
6223 A conversion with floating-point truncation instead of rounding.
6224
6225 @item @var{target}?(@var{source})
6226 A conversion that bypasses normal Ada semantic checking. In particular
6227 enumeration types and fixed-point types are treated simply as integers.
6228
6229 @item @var{target}?^^^(@var{source})
6230 Combines the above two cases.
6231
6232 @item @var{x} #/ @var{y}
6233 @itemx @var{x} #mod @var{y}
6234 @itemx @var{x} #* @var{y}
6235 @itemx @var{x} #rem @var{y}
6236 A division or multiplication of fixed-point values which are treated as
6237 integers without any kind of scaling.
6238
6239 @item free @var{expr} [storage_pool = @var{xxx}]
6240 Shows the storage pool associated with a @code{free} statement.
6241
6242 @item freeze @var{typename} [@var{actions}]
6243 Shows the point at which @var{typename} is frozen, with possible
6244 associated actions to be performed at the freeze point.
6245
6246 @item reference @var{itype}
6247 Reference (and hence definition) to internal type @var{itype}.
6248
6249 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6250 Intrinsic function call.
6251
6252 @item @var{labelname} : label
6253 Declaration of label @var{labelname}.
6254
6255 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6256 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6257 @var{expr}, but handled more efficiently).
6258
6259 @item [constraint_error]
6260 Raise the @code{Constraint_Error} exception.
6261
6262 @item @var{expression}'reference
6263 A pointer to the result of evaluating @var{expression}.
6264
6265 @item @var{target-type}!(@var{source-expression})
6266 An unchecked conversion of @var{source-expression} to @var{target-type}.
6267
6268 @item [@var{numerator}/@var{denominator}]
6269 Used to represent internal real literals (that) have no exact
6270 representation in base 2-16 (for example, the result of compile time
6271 evaluation of the expression 1.0/27.0).
6272 @end table
6273
6274 @item -gnatD
6275 @cindex @option{-gnatD} (@command{gcc})
6276 When used in conjunction with @option{-gnatG}, this switch causes
6277 the expanded source, as described above for
6278 @option{-gnatG} to be written to files with names
6279 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6280 instead of to the standard ooutput file. For
6281 example, if the source file name is @file{hello.adb}, then a file
6282 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6283 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6284 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6285 you to do source level debugging using the generated code which is
6286 sometimes useful for complex code, for example to find out exactly
6287 which part of a complex construction raised an exception. This switch
6288 also suppress generation of cross-reference information (see
6289 @option{-gnatx}) since otherwise the cross-reference information
6290 would refer to the @file{^.dg^.DG^} file, which would cause
6291 confusion since this is not the original source file.
6292
6293 Note that @option{-gnatD} actually implies @option{-gnatG}
6294 automatically, so it is not necessary to give both options.
6295 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6296
6297 @ifclear vms
6298 @item -gnatR[0|1|2|3[s]]
6299 @cindex @option{-gnatR} (@command{gcc})
6300 This switch controls output from the compiler of a listing showing
6301 representation information for declared types and objects. For
6302 @option{-gnatR0}, no information is output (equivalent to omitting
6303 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6304 so @option{-gnatR} with no parameter has the same effect), size and alignment
6305 information is listed for declared array and record types. For
6306 @option{-gnatR2}, size and alignment information is listed for all
6307 expression information for values that are computed at run time for
6308 variant records. These symbolic expressions have a mostly obvious
6309 format with #n being used to represent the value of the n'th
6310 discriminant. See source files @file{repinfo.ads/adb} in the
6311 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6312 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6313 the output is to a file with the name @file{^file.rep^file_REP^} where
6314 file is the name of the corresponding source file.
6315 @end ifclear
6316 @ifset vms
6317 @item /REPRESENTATION_INFO
6318 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6319 This qualifier controls output from the compiler of a listing showing
6320 representation information for declared types and objects. For
6321 @option{/REPRESENTATION_INFO=NONE}, no information is output
6322 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6323 @option{/REPRESENTATION_INFO} without option is equivalent to
6324 @option{/REPRESENTATION_INFO=ARRAYS}.
6325 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6326 information is listed for declared array and record types. For
6327 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6328 is listed for all expression information for values that are computed
6329 at run time for variant records. These symbolic expressions have a mostly
6330 obvious format with #n being used to represent the value of the n'th
6331 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6332 @code{GNAT} sources for full details on the format of
6333 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6334 If _FILE is added at the end of an option
6335 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6336 then the output is to a file with the name @file{file_REP} where
6337 file is the name of the corresponding source file.
6338 @end ifset
6339
6340 @item -gnatS
6341 @cindex @option{-gnatS} (@command{gcc})
6342 The use of the switch @option{-gnatS} for an
6343 Ada compilation will cause the compiler to output a
6344 representation of package Standard in a form very
6345 close to standard Ada. It is not quite possible to
6346 do this entirely in standard Ada (since new
6347 numeric base types cannot be created in standard
6348 Ada), but the output is easily
6349 readable to any Ada programmer, and is useful to
6350 determine the characteristics of target dependent
6351 types in package Standard.
6352
6353 @item -gnatx
6354 @cindex @option{-gnatx} (@command{gcc})
6355 Normally the compiler generates full cross-referencing information in
6356 the @file{ALI} file. This information is used by a number of tools,
6357 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6358 suppresses this information. This saves some space and may slightly
6359 speed up compilation, but means that these tools cannot be used.
6360 @end table
6361
6362 @node Exception Handling Control
6363 @subsection Exception Handling Control
6364
6365 @noindent
6366 GNAT uses two methods for handling exceptions at run-time. The
6367 @code{setjmp/longjmp} method saves the context when entering
6368 a frame with an exception handler. Then when an exception is
6369 raised, the context can be restored immediately, without the
6370 need for tracing stack frames. This method provides very fast
6371 exception propagation, but introduces significant overhead for
6372 the use of exception handlers, even if no exception is raised.
6373
6374 The other approach is called ``zero cost'' exception handling.
6375 With this method, the compiler builds static tables to describe
6376 the exception ranges. No dynamic code is required when entering
6377 a frame containing an exception handler. When an exception is
6378 raised, the tables are used to control a back trace of the
6379 subprogram invocation stack to locate the required exception
6380 handler. This method has considerably poorer performance for
6381 the propagation of exceptions, but there is no overhead for
6382 exception handlers if no exception is raised. Note that in this
6383 mode and in the context of mixed Ada and C/C++ programming,
6384 to propagate an exception through a C/C++ code, the C/C++ code
6385 must be compiled with the @option{-funwind-tables} GCC's
6386 option.
6387
6388 The following switches can be used to control which of the
6389 two exception handling methods is used.
6390
6391 @table @option
6392 @c !sort!
6393
6394 @item --RTS=sjlj
6395 @cindex @option{--RTS=sjlj} (@command{gnatmake})
6396 This switch causes the setjmp/longjmp run-time to be used
6397 for exception handling. If this is the default mechanism for the
6398 target (see below), then this has no effect. If the default
6399 mechanism for the target is zero cost exceptions, then
6400 this switch can be used to modify this default, and must be
6401 used for all units in the partition.
6402 This option is rarely used. One case in which it may be
6403 advantageous is if you have an application where exception
6404 raising is common and the overall performance of the
6405 application is improved by favoring exception propagation.
6406
6407 @item --RTS=zcx
6408 @cindex @option{--RTS=zcx} (@command{gnatmake})
6409 @cindex Zero Cost Exceptions
6410 This switch causes the zero cost approach to be used
6411 for exception handling. If this is the default mechanism for the
6412 target (see below), then this has no effect. If the default
6413 mechanism for the target is setjmp/longjmp exceptions, then
6414 this switch can be used to modify this default, and must be
6415 used for all units in the partition.
6416 This option can only be used if the zero cost approach
6417 is available for the target in use (see below).
6418 @end table
6419
6420 @noindent
6421 The @code{setjmp/longjmp} approach is available on all targets, while
6422 the @code{zero cost} approach is available on selected targets.
6423 To determine whether zero cost exceptions can be used for a
6424 particular target, look at the private part of the file system.ads.
6425 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6426 be True to use the zero cost approach. If both of these switches
6427 are set to False, this means that zero cost exception handling
6428 is not yet available for that target. The switch
6429 @code{ZCX_By_Default} indicates the default approach. If this
6430 switch is set to True, then the @code{zero cost} approach is
6431 used by default.
6432
6433 @node Units to Sources Mapping Files
6434 @subsection Units to Sources Mapping Files
6435
6436 @table @option
6437
6438 @item -gnatem^^=^@var{path}
6439 @cindex @option{-gnatem} (@command{gcc})
6440 A mapping file is a way to communicate to the compiler two mappings:
6441 from unit names to file names (without any directory information) and from
6442 file names to path names (with full directory information). These mappings
6443 are used by the compiler to short-circuit the path search.
6444
6445 The use of mapping files is not required for correct operation of the
6446 compiler, but mapping files can improve efficiency, particularly when
6447 sources are read over a slow network connection. In normal operation,
6448 you need not be concerned with the format or use of mapping files,
6449 and the @option{-gnatem} switch is not a switch that you would use
6450 explicitly. it is intended only for use by automatic tools such as
6451 @command{gnatmake} running under the project file facility. The
6452 description here of the format of mapping files is provided
6453 for completeness and for possible use by other tools.
6454
6455 A mapping file is a sequence of sets of three lines. In each set,
6456 the first line is the unit name, in lower case, with ``@code{%s}''
6457 appended for
6458 specifications and ``@code{%b}'' appended for bodies; the second line is the
6459 file name; and the third line is the path name.
6460
6461 Example:
6462 @smallexample
6463    main%b
6464    main.2.ada
6465    /gnat/project1/sources/main.2.ada
6466 @end smallexample
6467
6468 When the switch @option{-gnatem} is specified, the compiler will create
6469 in memory the two mappings from the specified file. If there is any problem
6470 (non existent file, truncated file or duplicate entries), no mapping
6471 will be created.
6472
6473 Several @option{-gnatem} switches may be specified; however, only the last
6474 one on the command line will be taken into account.
6475
6476 When using a project file, @command{gnatmake} create a temporary mapping file
6477 and communicates it to the compiler using this switch.
6478
6479 @end table
6480
6481 @node Integrated Preprocessing
6482 @subsection Integrated Preprocessing
6483
6484 @noindent
6485 GNAT sources may be preprocessed immediately before compilation; the actual
6486 text of the source is not the text of the source file, but is derived from it
6487 through a process called preprocessing. Integrated preprocessing is specified
6488 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6489 indicates, through a text file, the preprocessing data to be used.
6490 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6491
6492 @noindent
6493 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6494 used when Integrated Preprocessing is used. The reason is that preprocessing
6495 with another Preprocessing Data file without changing the sources will
6496 not trigger recompilation without this switch.
6497
6498 @noindent
6499 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6500 always trigger recompilation for sources that are preprocessed,
6501 because @command{gnatmake} cannot compute the checksum of the source after
6502 preprocessing.
6503
6504 @noindent
6505 The actual preprocessing function is described in details in section
6506 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6507 preprocessing is triggered and parameterized.
6508
6509 @table @code
6510
6511 @item -gnatep=@var{file}
6512 @cindex @option{-gnatep} (@command{gcc})
6513 This switch indicates to the compiler the file name (without directory
6514 information) of the preprocessor data file to use. The preprocessor data file
6515 should be found in the source directories.
6516
6517 @noindent
6518 A preprocessing data file is a text file with significant lines indicating
6519 how should be preprocessed either a specific source or all sources not
6520 mentioned in other lines. A significant line is a non empty, non comment line.
6521 Comments are similar to Ada comments.
6522
6523 @noindent
6524 Each significant line starts with either a literal string or the character '*'.
6525 A literal string is the file name (without directory information) of the source
6526 to preprocess. A character '*' indicates the preprocessing for all the sources
6527 that are not specified explicitly on other lines (order of the lines is not
6528 significant). It is an error to have two lines with the same file name or two
6529 lines starting with the character '*'.
6530
6531 @noindent
6532 After the file name or the character '*', another optional literal string
6533 indicating the file name of the definition file to be used for preprocessing
6534 (@pxref{Form of Definitions File}). The definition files are found by the
6535 compiler in one of the source directories. In some cases, when compiling
6536 a source in a directory other than the current directory, if the definition
6537 file is in the current directory, it may be necessary to add the current
6538 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6539 the compiler would not find the definition file.
6540
6541 @noindent
6542 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6543 be found. Those ^switches^switches^ are:
6544
6545 @table @code
6546
6547 @item -b
6548 Causes both preprocessor lines and the lines deleted by
6549 preprocessing to be replaced by blank lines, preserving the line number.
6550 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6551 it cancels the effect of @option{-c}.
6552
6553 @item -c
6554 Causes both preprocessor lines and the lines deleted
6555 by preprocessing to be retained as comments marked
6556 with the special string ``@code{--! }''.
6557
6558 @item -Dsymbol=value
6559 Define or redefine a symbol, associated with value. A symbol is an Ada
6560 identifier, or an Ada reserved word, with the exception of @code{if},
6561 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6562 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6563 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6564 same name defined in a definition file.
6565
6566 @item -s
6567 Causes a sorted list of symbol names and values to be
6568 listed on the standard output file.
6569
6570 @item -u
6571 Causes undefined symbols to be treated as having the value @code{FALSE}
6572 in the context
6573 of a preprocessor test. In the absence of this option, an undefined symbol in
6574 a @code{#if} or @code{#elsif} test will be treated as an error.
6575
6576 @end table
6577
6578 @noindent
6579 Examples of valid lines in a preprocessor data file:
6580
6581 @smallexample
6582   "toto.adb"  "prep.def" -u
6583   --  preprocess "toto.adb", using definition file "prep.def",
6584   --  undefined symbol are False.
6585
6586   * -c -DVERSION=V101
6587   --  preprocess all other sources without a definition file;
6588   --  suppressed lined are commented; symbol VERSION has the value V101.
6589
6590   "titi.adb" "prep2.def" -s
6591   --  preprocess "titi.adb", using definition file "prep2.def";
6592   --  list all symbols with their values.
6593 @end smallexample
6594
6595 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6596 @cindex @option{-gnateD} (@command{gcc})
6597 Define or redefine a preprocessing symbol, associated with value. If no value
6598 is given on the command line, then the value of the symbol is @code{True}.
6599 A symbol is an identifier, following normal Ada (case-insensitive)
6600 rules for its syntax, and value is any sequence (including an empty sequence)
6601 of characters from the set (letters, digits, period, underline).
6602 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6603 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6604
6605 @noindent
6606 A symbol declared with this ^switch^switch^ on the command line replaces a
6607 symbol with the same name either in a definition file or specified with a
6608 ^switch^switch^ -D in the preprocessor data file.
6609
6610 @noindent
6611 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6612
6613 @end table
6614
6615 @node Code Generation Control
6616 @subsection Code Generation Control
6617
6618 @noindent
6619
6620 The GCC technology provides a wide range of target dependent
6621 @option{-m} switches for controlling
6622 details of code generation with respect to different versions of
6623 architectures. This includes variations in instruction sets (e.g.
6624 different members of the power pc family), and different requirements
6625 for optimal arrangement of instructions (e.g. different members of
6626 the x86 family). The list of available @option{-m} switches may be
6627 found in the GCC documentation.
6628
6629 Use of the these @option{-m} switches may in some cases result in improved
6630 code performance.
6631
6632 The GNAT Pro technology is tested and qualified without any
6633 @option{-m} switches,
6634 so generally the most reliable approach is to avoid the use of these
6635 switches. However, we generally expect most of these switches to work
6636 successfully with GNAT Pro, and many customers have reported successful
6637 use of these options.
6638
6639 Our general advice is to avoid the use of @option{-m} switches unless
6640 special needs lead to requirements in this area. In particular,
6641 there is no point in using @option{-m} switches to improve performance
6642 unless you actually see a performance improvement.
6643
6644 @ifset vms
6645 @node Return Codes
6646 @subsection Return Codes
6647 @cindex Return Codes
6648 @cindex @option{/RETURN_CODES=VMS}
6649
6650 @noindent
6651 On VMS, GNAT compiled programs return POSIX-style codes by default,
6652 e.g. @option{/RETURN_CODES=POSIX}.
6653
6654 To enable VMS style return codes, use GNAT BIND and LINK with the option
6655 @option{/RETURN_CODES=VMS}. For example:
6656
6657 @smallexample
6658 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
6659 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6660 @end smallexample
6661
6662 @noindent
6663 Programs built with /RETURN_CODES=VMS are suitable to be called in
6664 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6665 are suitable for spawning with appropriate GNAT RTL routines.
6666
6667 @end ifset
6668
6669 @node Search Paths and the Run-Time Library (RTL)
6670 @section Search Paths and the Run-Time Library (RTL)
6671
6672 @noindent
6673 With the GNAT source-based library system, the compiler must be able to
6674 find source files for units that are needed by the unit being compiled.
6675 Search paths are used to guide this process.
6676
6677 The compiler compiles one source file whose name must be given
6678 explicitly on the command line. In other words, no searching is done
6679 for this file. To find all other source files that are needed (the most
6680 common being the specs of units), the compiler examines the following
6681 directories, in the following order:
6682
6683 @enumerate
6684 @item
6685 The directory containing the source file of the main unit being compiled
6686 (the file name on the command line).
6687
6688 @item
6689 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6690 @command{gcc} command line, in the order given.
6691
6692 @item
6693 @findex ADA_INCLUDE_PATH
6694 Each of the directories listed in the value of the
6695 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6696 @ifclear vms
6697 Construct this value
6698 exactly as the @code{PATH} environment variable: a list of directory
6699 names separated by colons (semicolons when working with the NT version).
6700 @end ifclear
6701 @ifset vms
6702 Normally, define this value as a logical name containing a comma separated
6703 list of directory names.
6704
6705 This variable can also be defined by means of an environment string
6706 (an argument to the DEC C exec* set of functions).
6707
6708 Logical Name:
6709 @smallexample
6710 DEFINE ANOTHER_PATH FOO:[BAG]
6711 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6712 @end smallexample
6713
6714 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6715 first, followed by the standard Ada 95
6716 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6717 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
6718 (Text_IO, Sequential_IO, etc)
6719 instead of the Ada95 packages. Thus, in order to get the Ada 95
6720 packages by default, ADA_INCLUDE_PATH must be redefined.
6721 @end ifset
6722
6723 @item
6724 @findex ADA_PRJ_INCLUDE_FILE
6725 Each of the directories listed in the text file whose name is given
6726 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6727
6728 @noindent
6729 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6730 driver when project files are used. It should not normally be set
6731 by other means.
6732
6733 @item
6734 The content of the @file{ada_source_path} file which is part of the GNAT
6735 installation tree and is used to store standard libraries such as the
6736 GNAT Run Time Library (RTL) source files.
6737 @ifclear vms
6738 @ref{Installing a library}
6739 @end ifclear
6740 @end enumerate
6741
6742 @noindent
6743 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6744 inhibits the use of the directory
6745 containing the source file named in the command line. You can still
6746 have this directory on your search path, but in this case it must be
6747 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6748
6749 Specifying the switch @option{-nostdinc}
6750 inhibits the search of the default location for the GNAT Run Time
6751 Library (RTL) source files.
6752
6753 The compiler outputs its object files and ALI files in the current
6754 working directory.
6755 @ifclear vms
6756 Caution: The object file can be redirected with the @option{-o} switch;
6757 however, @command{gcc} and @code{gnat1} have not been coordinated on this
6758 so the @file{ALI} file will not go to the right place. Therefore, you should
6759 avoid using the @option{-o} switch.
6760 @end ifclear
6761
6762 @findex System.IO
6763 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6764 children make up the GNAT RTL, together with the simple @code{System.IO}
6765 package used in the @code{"Hello World"} example. The sources for these units
6766 are needed by the compiler and are kept together in one directory. Not
6767 all of the bodies are needed, but all of the sources are kept together
6768 anyway. In a normal installation, you need not specify these directory
6769 names when compiling or binding. Either the environment variables or
6770 the built-in defaults cause these files to be found.
6771
6772 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6773 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6774 consisting of child units of @code{GNAT}. This is a collection of generally
6775 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6776 further details.
6777
6778 Besides simplifying access to the RTL, a major use of search paths is
6779 in compiling sources from multiple directories. This can make
6780 development environments much more flexible.
6781
6782 @node Order of Compilation Issues
6783 @section Order of Compilation Issues
6784
6785 @noindent
6786 If, in our earlier example, there was a spec for the @code{hello}
6787 procedure, it would be contained in the file @file{hello.ads}; yet this
6788 file would not have to be explicitly compiled. This is the result of the
6789 model we chose to implement library management. Some of the consequences
6790 of this model are as follows:
6791
6792 @itemize @bullet
6793 @item
6794 There is no point in compiling specs (except for package
6795 specs with no bodies) because these are compiled as needed by clients. If
6796 you attempt a useless compilation, you will receive an error message.
6797 It is also useless to compile subunits because they are compiled as needed
6798 by the parent.
6799
6800 @item
6801 There are no order of compilation requirements: performing a
6802 compilation never obsoletes anything. The only way you can obsolete
6803 something and require recompilations is to modify one of the
6804 source files on which it depends.
6805
6806 @item
6807 There is no library as such, apart from the ALI files
6808 (@pxref{The Ada Library Information Files}, for information on the format
6809 of these files). For now we find it convenient to create separate ALI files,
6810 but eventually the information therein may be incorporated into the object
6811 file directly.
6812
6813 @item
6814 When you compile a unit, the source files for the specs of all units
6815 that it @code{with}'s, all its subunits, and the bodies of any generics it
6816 instantiates must be available (reachable by the search-paths mechanism
6817 described above), or you will receive a fatal error message.
6818 @end itemize
6819
6820 @node Examples
6821 @section Examples
6822
6823 @noindent
6824 The following are some typical Ada compilation command line examples:
6825
6826 @table @code
6827 @item $ gcc -c xyz.adb
6828 Compile body in file @file{xyz.adb} with all default options.
6829
6830 @ifclear vms
6831 @item $ gcc -c -O2 -gnata xyz-def.adb
6832 @end ifclear
6833 @ifset vms
6834 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6835 @end ifset
6836
6837 Compile the child unit package in file @file{xyz-def.adb} with extensive
6838 optimizations, and pragma @code{Assert}/@code{Debug} statements
6839 enabled.
6840
6841 @item $ gcc -c -gnatc abc-def.adb
6842 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6843 mode.
6844 @end table
6845
6846 @node Binding Using gnatbind
6847 @chapter Binding Using @code{gnatbind}
6848 @findex gnatbind
6849
6850 @menu
6851 * Running gnatbind::
6852 * Switches for gnatbind::
6853 * Command-Line Access::
6854 * Search Paths for gnatbind::
6855 * Examples of gnatbind Usage::
6856 @end menu
6857
6858 @noindent
6859 This chapter describes the GNAT binder, @code{gnatbind}, which is used
6860 to bind compiled GNAT objects. The @code{gnatbind} program performs
6861 four separate functions:
6862
6863 @enumerate
6864 @item
6865 Checks that a program is consistent, in accordance with the rules in
6866 Chapter 10 of the Ada 95 Reference Manual. In particular, error
6867 messages are generated if a program uses inconsistent versions of a
6868 given unit.
6869
6870 @item
6871 Checks that an acceptable order of elaboration exists for the program
6872 and issues an error message if it cannot find an order of elaboration
6873 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6874
6875 @item
6876 Generates a main program incorporating the given elaboration order.
6877 This program is a small Ada package (body and spec) that
6878 must be subsequently compiled
6879 using the GNAT compiler. The necessary compilation step is usually
6880 performed automatically by @command{gnatlink}. The two most important
6881 functions of this program
6882 are to call the elaboration routines of units in an appropriate order
6883 and to call the main program.
6884
6885 @item
6886 Determines the set of object files required by the given main program.
6887 This information is output in the forms of comments in the generated program,
6888 to be read by the @command{gnatlink} utility used to link the Ada application.
6889 @end enumerate
6890
6891 @node Running gnatbind
6892 @section Running @code{gnatbind}
6893
6894 @noindent
6895 The form of the @code{gnatbind} command is
6896
6897 @smallexample
6898 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
6899 @end smallexample
6900
6901 @noindent
6902 where @file{@i{mainprog}.adb} is the Ada file containing the main program
6903 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
6904 package in two files whose names are
6905 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
6906 For example, if given the
6907 parameter @file{hello.ali}, for a main program contained in file
6908 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
6909 and @file{b~hello.adb}.
6910
6911 When doing consistency checking, the binder takes into consideration
6912 any source files it can locate. For example, if the binder determines
6913 that the given main program requires the package @code{Pack}, whose
6914 @file{.ALI}
6915 file is @file{pack.ali} and whose corresponding source spec file is
6916 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
6917 (using the same search path conventions as previously described for the
6918 @command{gcc} command). If it can locate this source file, it checks that
6919 the time stamps
6920 or source checksums of the source and its references to in @file{ALI} files
6921 match. In other words, any @file{ALI} files that mentions this spec must have
6922 resulted from compiling this version of the source file (or in the case
6923 where the source checksums match, a version close enough that the
6924 difference does not matter).
6925
6926 @cindex Source files, use by binder
6927 The effect of this consistency checking, which includes source files, is
6928 that the binder ensures that the program is consistent with the latest
6929 version of the source files that can be located at bind time. Editing a
6930 source file without compiling files that depend on the source file cause
6931 error messages to be generated by the binder.
6932
6933 For example, suppose you have a main program @file{hello.adb} and a
6934 package @code{P}, from file @file{p.ads} and you perform the following
6935 steps:
6936
6937 @enumerate
6938 @item
6939 Enter @code{gcc -c hello.adb} to compile the main program.
6940
6941 @item
6942 Enter @code{gcc -c p.ads} to compile package @code{P}.
6943
6944 @item
6945 Edit file @file{p.ads}.
6946
6947 @item
6948 Enter @code{gnatbind hello}.
6949 @end enumerate
6950
6951 @noindent
6952 At this point, the file @file{p.ali} contains an out-of-date time stamp
6953 because the file @file{p.ads} has been edited. The attempt at binding
6954 fails, and the binder generates the following error messages:
6955
6956 @smallexample
6957 error: "hello.adb" must be recompiled ("p.ads" has been modified)
6958 error: "p.ads" has been modified and must be recompiled
6959 @end smallexample
6960
6961 @noindent
6962 Now both files must be recompiled as indicated, and then the bind can
6963 succeed, generating a main program. You need not normally be concerned
6964 with the contents of this file, but for reference purposes a sample
6965 binder output file is given in @ref{Example of Binder Output File}.
6966
6967 In most normal usage, the default mode of @command{gnatbind} which is to
6968 generate the main package in Ada, as described in the previous section.
6969 In particular, this means that any Ada programmer can read and understand
6970 the generated main program. It can also be debugged just like any other
6971 Ada code provided the @option{^-g^/DEBUG^} switch is used for
6972 @command{gnatbind} and @command{gnatlink}.
6973
6974 However for some purposes it may be convenient to generate the main
6975 program in C rather than Ada. This may for example be helpful when you
6976 are generating a mixed language program with the main program in C. The
6977 GNAT compiler itself is an example.
6978 The use of the @option{^-C^/BIND_FILE=C^} switch
6979 for both @code{gnatbind} and @command{gnatlink} will cause the program to
6980 be generated in C (and compiled using the gnu C compiler).
6981
6982 @node Switches for gnatbind
6983 @section Switches for @command{gnatbind}
6984
6985 @noindent
6986 The following switches are available with @code{gnatbind}; details will
6987 be presented in subsequent sections.
6988
6989 @menu
6990 * Consistency-Checking Modes::
6991 * Binder Error Message Control::
6992 * Elaboration Control::
6993 * Output Control::
6994 * Binding with Non-Ada Main Programs::
6995 * Binding Programs with No Main Subprogram::
6996 @end menu
6997
6998 @table @option
6999 @c !sort!
7000 @item ^-aO^/OBJECT_SEARCH^
7001 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7002 Specify directory to be searched for ALI files.
7003
7004 @item ^-aI^/SOURCE_SEARCH^
7005 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7006 Specify directory to be searched for source file.
7007
7008 @item ^-A^/BIND_FILE=ADA^
7009 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7010 Generate binder program in Ada (default)
7011
7012 @item ^-b^/REPORT_ERRORS=BRIEF^
7013 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7014 Generate brief messages to @file{stderr} even if verbose mode set.
7015
7016 @item ^-c^/NOOUTPUT^
7017 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7018 Check only, no generation of binder output file.
7019
7020 @item ^-C^/BIND_FILE=C^
7021 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7022 Generate binder program in C
7023
7024 @item ^-e^/ELABORATION_DEPENDENCIES^
7025 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7026 Output complete list of elaboration-order dependencies.
7027
7028 @item ^-E^/STORE_TRACEBACKS^
7029 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7030 Store tracebacks in exception occurrences when the target supports it.
7031 This is the default with the zero cost exception mechanism.
7032 @ignore
7033 @c The following may get moved to an appendix
7034 This option is currently supported on the following targets:
7035 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7036 @end ignore
7037 See also the packages @code{GNAT.Traceback} and
7038 @code{GNAT.Traceback.Symbolic} for more information.
7039 @ifclear vms
7040 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7041 @command{gcc} option.
7042 @end ifclear
7043
7044 @item ^-F^/FORCE_ELABS_FLAGS^
7045 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7046 Force the checks of elaboration flags. @command{gnatbind} does not normally
7047 generate checks of elaboration flags for the main executable, except when
7048 a Stand-Alone Library is used. However, there are cases when this cannot be
7049 detected by gnatbind. An example is importing an interface of a Stand-Alone
7050 Library through a pragma Import and only specifying through a linker switch
7051 this Stand-Alone Library. This switch is used to guarantee that elaboration
7052 flag checks are generated.
7053
7054 @item ^-h^/HELP^
7055 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7056 Output usage (help) information
7057
7058 @item ^-I^/SEARCH^
7059 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7060 Specify directory to be searched for source and ALI files.
7061
7062 @item ^-I-^/NOCURRENT_DIRECTORY^
7063 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7064 Do not look for sources in the current directory where @code{gnatbind} was
7065 invoked, and do not look for ALI files in the directory containing the
7066 ALI file named in the @code{gnatbind} command line.
7067
7068 @item ^-l^/ORDER_OF_ELABORATION^
7069 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7070 Output chosen elaboration order.
7071
7072 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7073 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7074 Bind the units for library building. In this case the adainit and
7075 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7076 are renamed to ^xxxinit^XXXINIT^ and
7077 ^xxxfinal^XXXFINAL^.
7078 Implies ^-n^/NOCOMPILE^.
7079 @ifclear vms
7080 (@xref{GNAT and Libraries}, for more details.)
7081 @end ifclear
7082 @ifset vms
7083 On OpenVMS, these init and final procedures are exported in uppercase
7084 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7085 the init procedure will be "TOTOINIT" and the exported name of the final
7086 procedure will be "TOTOFINAL".
7087 @end ifset
7088
7089 @item ^-Mxyz^/RENAME_MAIN=xyz^
7090 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7091 Rename generated main program from main to xyz
7092
7093 @item ^-m^/ERROR_LIMIT=^@var{n}
7094 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7095 Limit number of detected errors to @var{n}, where @var{n} is
7096 in the range 1..999_999. The default value if no switch is
7097 given is 9999. Binding is terminated if the limit is exceeded.
7098 @ifset unw
7099 Furthermore, under Windows, the sources pointed to by the libraries path
7100 set in the registry are not searched for.
7101 @end ifset
7102
7103 @item ^-n^/NOMAIN^
7104 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7105 No main program.
7106
7107 @item -nostdinc
7108 @cindex @option{-nostdinc} (@command{gnatbind})
7109 Do not look for sources in the system default directory.
7110
7111 @item -nostdlib
7112 @cindex @option{-nostdlib} (@command{gnatbind})
7113 Do not look for library files in the system default directory.
7114
7115 @item --RTS=@var{rts-path}
7116 @cindex @option{--RTS} (@code{gnatbind})
7117 Specifies the default location of the runtime library. Same meaning as the
7118 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7119
7120 @item ^-o ^/OUTPUT=^@var{file}
7121 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7122 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7123 Note that if this option is used, then linking must be done manually,
7124 gnatlink cannot be used.
7125
7126 @item ^-O^/OBJECT_LIST^
7127 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7128 Output object list.
7129
7130 @item ^-p^/PESSIMISTIC_ELABORATION^
7131 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7132 Pessimistic (worst-case) elaboration order
7133
7134 @item ^-s^/READ_SOURCES=ALL^
7135 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7136 Require all source files to be present.
7137
7138 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7139 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7140 Specifies the value to be used when detecting uninitialized scalar
7141 objects with pragma Initialize_Scalars.
7142 The @var{xxx} ^string specified with the switch^option^ may be either
7143 @itemize @bullet
7144 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7145 @item ``@option{^lo^LOW^}'' for the lowest possible value
7146 possible, and the low
7147 @item ``@option{^hi^HIGH^}'' for the highest possible value
7148 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7149 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7150 @end itemize
7151
7152 In addition, you can specify @option{-Sev} to indicate that the value is
7153 to be set at run time. In this case, the program will look for an environment
7154 @cindex GNAT_INIT_SCALARS
7155 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7156 of @option{in/lo/hi/xx} with the same meanings as above.
7157 If no environment variable is found, or if it does not have a valid value,
7158 then the default is @option{in} (invalid values).
7159
7160 @ifclear vms
7161 @item -static
7162 @cindex @option{-static} (@code{gnatbind})
7163 Link against a static GNAT run time.
7164
7165 @item -shared
7166 @cindex @option{-shared} (@code{gnatbind})
7167 Link against a shared GNAT run time when available.
7168 @end ifclear
7169
7170 @item ^-t^/NOTIME_STAMP_CHECK^
7171 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7172 Tolerate time stamp and other consistency errors
7173
7174 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7175 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7176 Set the time slice value to @var{n} milliseconds. If the system supports
7177 the specification of a specific time slice value, then the indicated value
7178 is used. If the system does not support specific time slice values, but
7179 does support some general notion of round-robin scheduling, then any
7180 non-zero value will activate round-robin scheduling.
7181
7182 A value of zero is treated specially. It turns off time
7183 slicing, and in addition, indicates to the tasking run time that the
7184 semantics should match as closely as possible the Annex D
7185 requirements of the Ada RM, and in particular sets the default
7186 scheduling policy to @code{FIFO_Within_Priorities}.
7187
7188 @item ^-v^/REPORT_ERRORS=VERBOSE^
7189 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7190 Verbose mode. Write error messages, header, summary output to
7191 @file{stdout}.
7192
7193 @ifclear vms
7194 @item -w@var{x}
7195 @cindex @option{-w} (@code{gnatbind})
7196 Warning mode (@var{x}=s/e for suppress/treat as error)
7197 @end ifclear
7198
7199 @ifset vms
7200 @item /WARNINGS=NORMAL
7201 @cindex @option{/WARNINGS} (@code{gnatbind})
7202 Normal warnings mode. Warnings are issued but ignored
7203
7204 @item /WARNINGS=SUPPRESS
7205 @cindex @option{/WARNINGS} (@code{gnatbind})
7206 All warning messages are suppressed
7207
7208 @item /WARNINGS=ERROR
7209 @cindex @option{/WARNINGS} (@code{gnatbind})
7210 Warning messages are treated as fatal errors
7211 @end ifset
7212
7213 @item ^-x^/READ_SOURCES=NONE^
7214 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7215 Exclude source files (check object consistency only).
7216
7217 @ifset vms
7218 @item /READ_SOURCES=AVAILABLE
7219 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7220 Default mode, in which sources are checked for consistency only if
7221 they are available.
7222 @end ifset
7223
7224 @item ^-z^/ZERO_MAIN^
7225 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7226 No main subprogram.
7227 @end table
7228
7229 @ifclear vms
7230 @noindent
7231 You may obtain this listing of switches by running @code{gnatbind} with
7232 no arguments.
7233 @end ifclear
7234
7235 @node Consistency-Checking Modes
7236 @subsection Consistency-Checking Modes
7237
7238 @noindent
7239 As described earlier, by default @code{gnatbind} checks
7240 that object files are consistent with one another and are consistent
7241 with any source files it can locate. The following switches control binder
7242 access to sources.
7243
7244 @table @option
7245 @c !sort!
7246 @item ^-s^/READ_SOURCES=ALL^
7247 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7248 Require source files to be present. In this mode, the binder must be
7249 able to locate all source files that are referenced, in order to check
7250 their consistency. In normal mode, if a source file cannot be located it
7251 is simply ignored. If you specify this switch, a missing source
7252 file is an error.
7253
7254 @item ^-x^/READ_SOURCES=NONE^
7255 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7256 Exclude source files. In this mode, the binder only checks that ALI
7257 files are consistent with one another. Source files are not accessed.
7258 The binder runs faster in this mode, and there is still a guarantee that
7259 the resulting program is self-consistent.
7260 If a source file has been edited since it was last compiled, and you
7261 specify this switch, the binder will not detect that the object
7262 file is out of date with respect to the source file. Note that this is the
7263 mode that is automatically used by @command{gnatmake} because in this
7264 case the checking against sources has already been performed by
7265 @command{gnatmake} in the course of compilation (i.e. before binding).
7266
7267 @ifset vms
7268 @item /READ_SOURCES=AVAILABLE
7269 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7270 This is the default mode in which source files are checked if they are
7271 available, and ignored if they are not available.
7272 @end ifset
7273 @end table
7274
7275 @node Binder Error Message Control
7276 @subsection Binder Error Message Control
7277
7278 @noindent
7279 The following switches provide control over the generation of error
7280 messages from the binder:
7281
7282 @table @option
7283 @c !sort!
7284 @item ^-v^/REPORT_ERRORS=VERBOSE^
7285 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7286 Verbose mode. In the normal mode, brief error messages are generated to
7287 @file{stderr}. If this switch is present, a header is written
7288 to @file{stdout} and any error messages are directed to @file{stdout}.
7289 All that is written to @file{stderr} is a brief summary message.
7290
7291 @item ^-b^/REPORT_ERRORS=BRIEF^
7292 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7293 Generate brief error messages to @file{stderr} even if verbose mode is
7294 specified. This is relevant only when used with the
7295 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7296
7297 @ifclear vms
7298 @item -m@var{n}
7299 @cindex @option{-m} (@code{gnatbind})
7300 Limits the number of error messages to @var{n}, a decimal integer in the
7301 range 1-999. The binder terminates immediately if this limit is reached.
7302
7303 @item -M@var{xxx}
7304 @cindex @option{-M} (@code{gnatbind})
7305 Renames the generated main program from @code{main} to @code{xxx}.
7306 This is useful in the case of some cross-building environments, where
7307 the actual main program is separate from the one generated
7308 by @code{gnatbind}.
7309 @end ifclear
7310
7311 @item ^-ws^/WARNINGS=SUPPRESS^
7312 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7313 @cindex Warnings
7314 Suppress all warning messages.
7315
7316 @item ^-we^/WARNINGS=ERROR^
7317 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7318 Treat any warning messages as fatal errors.
7319
7320 @ifset vms
7321 @item /WARNINGS=NORMAL
7322 Standard mode with warnings generated, but warnings do not get treated
7323 as errors.
7324 @end ifset
7325
7326 @item ^-t^/NOTIME_STAMP_CHECK^
7327 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7328 @cindex Time stamp checks, in binder
7329 @cindex Binder consistency checks
7330 @cindex Consistency checks, in binder
7331 The binder performs a number of consistency checks including:
7332
7333 @itemize @bullet
7334 @item
7335 Check that time stamps of a given source unit are consistent
7336 @item
7337 Check that checksums of a given source unit are consistent
7338 @item
7339 Check that consistent versions of @code{GNAT} were used for compilation
7340 @item
7341 Check consistency of configuration pragmas as required
7342 @end itemize
7343
7344 @noindent
7345 Normally failure of such checks, in accordance with the consistency
7346 requirements of the Ada Reference Manual, causes error messages to be
7347 generated which abort the binder and prevent the output of a binder
7348 file and subsequent link to obtain an executable.
7349
7350 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7351 into warnings, so that
7352 binding and linking can continue to completion even in the presence of such
7353 errors. The result may be a failed link (due to missing symbols), or a
7354 non-functional executable which has undefined semantics.
7355 @emph{This means that
7356 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7357 with extreme care.}
7358 @end table
7359
7360 @node Elaboration Control
7361 @subsection Elaboration Control
7362
7363 @noindent
7364 The following switches provide additional control over the elaboration
7365 order. For full details see @ref{Elaboration Order Handling in GNAT}.
7366
7367 @table @option
7368 @item ^-p^/PESSIMISTIC_ELABORATION^
7369 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7370 Normally the binder attempts to choose an elaboration order that is
7371 likely to minimize the likelihood of an elaboration order error resulting
7372 in raising a @code{Program_Error} exception. This switch reverses the
7373 action of the binder, and requests that it deliberately choose an order
7374 that is likely to maximize the likelihood of an elaboration error.
7375 This is useful in ensuring portability and avoiding dependence on
7376 accidental fortuitous elaboration ordering.
7377
7378 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7379 switch if dynamic
7380 elaboration checking is used (@option{-gnatE} switch used for compilation).
7381 This is because in the default static elaboration mode, all necessary
7382 @code{Elaborate_All} pragmas are implicitly inserted.
7383 These implicit pragmas are still respected by the binder in
7384 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7385 safe elaboration order is assured.
7386 @end table
7387
7388 @node Output Control
7389 @subsection Output Control
7390
7391 @noindent
7392 The following switches allow additional control over the output
7393 generated by the binder.
7394
7395 @table @option
7396 @c !sort!
7397
7398 @item ^-A^/BIND_FILE=ADA^
7399 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7400 Generate binder program in Ada (default). The binder program is named
7401 @file{b~@var{mainprog}.adb} by default. This can be changed with
7402 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7403
7404 @item ^-c^/NOOUTPUT^
7405 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7406 Check only. Do not generate the binder output file. In this mode the
7407 binder performs all error checks but does not generate an output file.
7408
7409 @item ^-C^/BIND_FILE=C^
7410 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7411 Generate binder program in C. The binder program is named
7412 @file{b_@var{mainprog}.c}.
7413 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7414 option.
7415
7416 @item ^-e^/ELABORATION_DEPENDENCIES^
7417 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7418 Output complete list of elaboration-order dependencies, showing the
7419 reason for each dependency. This output can be rather extensive but may
7420 be useful in diagnosing problems with elaboration order. The output is
7421 written to @file{stdout}.
7422
7423 @item ^-h^/HELP^
7424 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7425 Output usage information. The output is written to @file{stdout}.
7426
7427 @item ^-K^/LINKER_OPTION_LIST^
7428 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7429 Output linker options to @file{stdout}. Includes library search paths,
7430 contents of pragmas Ident and Linker_Options, and libraries added
7431 by @code{gnatbind}.
7432
7433 @item ^-l^/ORDER_OF_ELABORATION^
7434 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7435 Output chosen elaboration order. The output is written to @file{stdout}.
7436
7437 @item ^-O^/OBJECT_LIST^
7438 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7439 Output full names of all the object files that must be linked to provide
7440 the Ada component of the program. The output is written to @file{stdout}.
7441 This list includes the files explicitly supplied and referenced by the user
7442 as well as implicitly referenced run-time unit files. The latter are
7443 omitted if the corresponding units reside in shared libraries. The
7444 directory names for the run-time units depend on the system configuration.
7445
7446 @item ^-o ^/OUTPUT=^@var{file}
7447 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7448 Set name of output file to @var{file} instead of the normal
7449 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7450 binder generated body filename. In C mode you would normally give
7451 @var{file} an extension of @file{.c} because it will be a C source program.
7452 Note that if this option is used, then linking must be done manually.
7453 It is not possible to use gnatlink in this case, since it cannot locate
7454 the binder file.
7455
7456 @item ^-r^/RESTRICTION_LIST^
7457 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7458 Generate list of @code{pragma Restrictions} that could be applied to
7459 the current unit. This is useful for code audit purposes, and also may
7460 be used to improve code generation in some cases.
7461
7462 @end table
7463
7464 @node Binding with Non-Ada Main Programs
7465 @subsection Binding with Non-Ada Main Programs
7466
7467 @noindent
7468 In our description so far we have assumed that the main
7469 program is in Ada, and that the task of the binder is to generate a
7470 corresponding function @code{main} that invokes this Ada main
7471 program. GNAT also supports the building of executable programs where
7472 the main program is not in Ada, but some of the called routines are
7473 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7474 The following switch is used in this situation:
7475
7476 @table @option
7477 @item ^-n^/NOMAIN^
7478 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7479 No main program. The main program is not in Ada.
7480 @end table
7481
7482 @noindent
7483 In this case, most of the functions of the binder are still required,
7484 but instead of generating a main program, the binder generates a file
7485 containing the following callable routines:
7486
7487 @table @code
7488 @item adainit
7489 @findex adainit
7490 You must call this routine to initialize the Ada part of the program by
7491 calling the necessary elaboration routines. A call to @code{adainit} is
7492 required before the first call to an Ada subprogram.
7493
7494 Note that it is assumed that the basic execution environment must be setup
7495 to be appropriate for Ada execution at the point where the first Ada
7496 subprogram is called. In particular, if the Ada code will do any
7497 floating-point operations, then the FPU must be setup in an appropriate
7498 manner. For the case of the x86, for example, full precision mode is
7499 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7500 that the FPU is in the right state.
7501
7502 @item adafinal
7503 @findex adafinal
7504 You must call this routine to perform any library-level finalization
7505 required by the Ada subprograms. A call to @code{adafinal} is required
7506 after the last call to an Ada subprogram, and before the program
7507 terminates.
7508 @end table
7509
7510 @noindent
7511 If the @option{^-n^/NOMAIN^} switch
7512 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7513 @cindex Binder, multiple input files
7514 is given, more than one ALI file may appear on
7515 the command line for @code{gnatbind}. The normal @dfn{closure}
7516 calculation is performed for each of the specified units. Calculating
7517 the closure means finding out the set of units involved by tracing
7518 @code{with} references. The reason it is necessary to be able to
7519 specify more than one ALI file is that a given program may invoke two or
7520 more quite separate groups of Ada units.
7521
7522 The binder takes the name of its output file from the last specified ALI
7523 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7524 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7525 The output is an Ada unit in source form that can
7526 be compiled with GNAT unless the -C switch is used in which case the
7527 output is a C source file, which must be compiled using the C compiler.
7528 This compilation occurs automatically as part of the @command{gnatlink}
7529 processing.
7530
7531 Currently the GNAT run time requires a FPU using 80 bits mode
7532 precision. Under targets where this is not the default it is required to
7533 call GNAT.Float_Control.Reset before using floating point numbers (this
7534 include float computation, float input and output) in the Ada code. A
7535 side effect is that this could be the wrong mode for the foreign code
7536 where floating point computation could be broken after this call.
7537
7538 @node Binding Programs with No Main Subprogram
7539 @subsection Binding Programs with No Main Subprogram
7540
7541 @noindent
7542 It is possible to have an Ada program which does not have a main
7543 subprogram. This program will call the elaboration routines of all the
7544 packages, then the finalization routines.
7545
7546 The following switch is used to bind programs organized in this manner:
7547
7548 @table @option
7549 @item ^-z^/ZERO_MAIN^
7550 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7551 Normally the binder checks that the unit name given on the command line
7552 corresponds to a suitable main subprogram. When this switch is used,
7553 a list of ALI files can be given, and the execution of the program
7554 consists of elaboration of these units in an appropriate order.
7555 @end table
7556
7557 @node Command-Line Access
7558 @section Command-Line Access
7559
7560 @noindent
7561 The package @code{Ada.Command_Line} provides access to the command-line
7562 arguments and program name. In order for this interface to operate
7563 correctly, the two variables
7564
7565 @smallexample
7566 @group
7567 int gnat_argc;
7568 char **gnat_argv;
7569 @end group
7570 @end smallexample
7571
7572 @noindent
7573 @findex gnat_argv
7574 @findex gnat_argc
7575 are declared in one of the GNAT library routines. These variables must
7576 be set from the actual @code{argc} and @code{argv} values passed to the
7577 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7578 generates the C main program to automatically set these variables.
7579 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7580 set these variables. If they are not set, the procedures in
7581 @code{Ada.Command_Line} will not be available, and any attempt to use
7582 them will raise @code{Constraint_Error}. If command line access is
7583 required, your main program must set @code{gnat_argc} and
7584 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7585 it.
7586
7587 @node Search Paths for gnatbind
7588 @section Search Paths for @code{gnatbind}
7589
7590 @noindent
7591 The binder takes the name of an ALI file as its argument and needs to
7592 locate source files as well as other ALI files to verify object consistency.
7593
7594 For source files, it follows exactly the same search rules as @command{gcc}
7595 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7596 directories searched are:
7597
7598 @enumerate
7599 @item
7600 The directory containing the ALI file named in the command line, unless
7601 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7602
7603 @item
7604 All directories specified by @option{^-I^/SEARCH^}
7605 switches on the @code{gnatbind}
7606 command line, in the order given.
7607
7608 @item
7609 @findex ADA_OBJECTS_PATH
7610 Each of the directories listed in the value of the
7611 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7612 @ifset unw
7613 Construct this value
7614 exactly as the @code{PATH} environment variable: a list of directory
7615 names separated by colons (semicolons when working with the NT version
7616 of GNAT).
7617 @end ifset
7618 @ifset vms
7619 Normally, define this value as a logical name containing a comma separated
7620 list of directory names.
7621
7622 This variable can also be defined by means of an environment string
7623 (an argument to the DEC C exec* set of functions).
7624
7625 Logical Name:
7626 @smallexample
7627 DEFINE ANOTHER_PATH FOO:[BAG]
7628 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7629 @end smallexample
7630
7631 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7632 first, followed by the standard Ada 95
7633 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7634 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
7635 (Text_IO, Sequential_IO, etc)
7636 instead of the Ada95 packages. Thus, in order to get the Ada 95
7637 packages by default, ADA_OBJECTS_PATH must be redefined.
7638 @end ifset
7639
7640 @item
7641 @findex ADA_PRJ_OBJECTS_FILE
7642 Each of the directories listed in the text file whose name is given
7643 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7644
7645 @noindent
7646 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7647 driver when project files are used. It should not normally be set
7648 by other means.
7649
7650 @item
7651 The content of the @file{ada_object_path} file which is part of the GNAT
7652 installation tree and is used to store standard libraries such as the
7653 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7654 specified.
7655 @ifclear vms
7656 @ref{Installing a library}
7657 @end ifclear
7658 @end enumerate
7659
7660 @noindent
7661 In the binder the switch @option{^-I^/SEARCH^}
7662 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7663 is used to specify both source and
7664 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7665 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7666 instead if you want to specify
7667 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7668 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7669 if you want to specify library paths
7670 only. This means that for the binder
7671 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7672 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7673 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7674 The binder generates the bind file (a C language source file) in the
7675 current working directory.
7676
7677 @findex Ada
7678 @findex System
7679 @findex Interfaces
7680 @findex GNAT
7681 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7682 children make up the GNAT Run-Time Library, together with the package
7683 GNAT and its children, which contain a set of useful additional
7684 library functions provided by GNAT. The sources for these units are
7685 needed by the compiler and are kept together in one directory. The ALI
7686 files and object files generated by compiling the RTL are needed by the
7687 binder and the linker and are kept together in one directory, typically
7688 different from the directory containing the sources. In a normal
7689 installation, you need not specify these directory names when compiling
7690 or binding. Either the environment variables or the built-in defaults
7691 cause these files to be found.
7692
7693 Besides simplifying access to the RTL, a major use of search paths is
7694 in compiling sources from multiple directories. This can make
7695 development environments much more flexible.
7696
7697 @node Examples of gnatbind Usage
7698 @section Examples of @code{gnatbind} Usage
7699
7700 @noindent
7701 This section contains a number of examples of using the GNAT binding
7702 utility @code{gnatbind}.
7703
7704 @table @code
7705 @item gnatbind hello
7706 The main program @code{Hello} (source program in @file{hello.adb}) is
7707 bound using the standard switch settings. The generated main program is
7708 @file{b~hello.adb}. This is the normal, default use of the binder.
7709
7710 @ifclear vms
7711 @item gnatbind hello -o mainprog.adb
7712 @end ifclear
7713 @ifset vms
7714 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7715 @end ifset
7716 The main program @code{Hello} (source program in @file{hello.adb}) is
7717 bound using the standard switch settings. The generated main program is
7718 @file{mainprog.adb} with the associated spec in
7719 @file{mainprog.ads}. Note that you must specify the body here not the
7720 spec, in the case where the output is in Ada. Note that if this option
7721 is used, then linking must be done manually, since gnatlink will not
7722 be able to find the generated file.
7723
7724 @ifclear vms
7725 @item gnatbind main -C -o mainprog.c -x
7726 @end ifclear
7727 @ifset vms
7728 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7729 @end ifset
7730 The main program @code{Main} (source program in
7731 @file{main.adb}) is bound, excluding source files from the
7732 consistency checking, generating
7733 the file @file{mainprog.c}.
7734
7735 @ifclear vms
7736 @item gnatbind -x main_program -C -o mainprog.c
7737 This command is exactly the same as the previous example. Switches may
7738 appear anywhere in the command line, and single letter switches may be
7739 combined into a single switch.
7740 @end ifclear
7741
7742 @ifclear vms
7743 @item gnatbind -n math dbase -C -o ada-control.c
7744 @end ifclear
7745 @ifset vms
7746 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7747 @end ifset
7748 The main program is in a language other than Ada, but calls to
7749 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7750 to @code{gnatbind} generates the file @file{ada-control.c} containing
7751 the @code{adainit} and @code{adafinal} routines to be called before and
7752 after accessing the Ada units.
7753 @end table
7754
7755 @c ------------------------------------
7756 @node Linking Using gnatlink
7757 @chapter Linking Using @command{gnatlink}
7758 @c ------------------------------------
7759 @findex gnatlink
7760
7761 @noindent
7762 This chapter discusses @command{gnatlink}, a tool that links
7763 an Ada program and builds an executable file. This utility
7764 invokes the system linker ^(via the @command{gcc} command)^^
7765 with a correct list of object files and library references.
7766 @command{gnatlink} automatically determines the list of files and
7767 references for the Ada part of a program. It uses the binder file
7768 generated by the @command{gnatbind} to determine this list.
7769
7770 @menu
7771 * Running gnatlink::
7772 * Switches for gnatlink::
7773 * Setting Stack Size from gnatlink::
7774 * Setting Heap Size from gnatlink::
7775 @end menu
7776
7777 @node Running gnatlink
7778 @section Running @command{gnatlink}
7779
7780 @noindent
7781 The form of the @command{gnatlink} command is
7782
7783 @smallexample
7784 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
7785            [@var{non-Ada objects}] [@var{linker options}]
7786 @end smallexample
7787
7788 @noindent
7789 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
7790 non-Ada objects
7791 or linker options) may be in any order, provided that no non-Ada object may
7792 be mistaken for a main @file{ALI} file.
7793 Any file name @file{F} without the @file{.ali}
7794 extension will be taken as the main @file{ALI} file if a file exists
7795 whose name is the concatenation of @file{F} and @file{.ali}.
7796
7797 @noindent
7798 @file{@var{mainprog}.ali} references the ALI file of the main program.
7799 The @file{.ali} extension of this file can be omitted. From this
7800 reference, @command{gnatlink} locates the corresponding binder file
7801 @file{b~@var{mainprog}.adb} and, using the information in this file along
7802 with the list of non-Ada objects and linker options, constructs a
7803 linker command file to create the executable.
7804
7805 The arguments other than the @command{gnatlink} switches and the main
7806 @file{ALI} file are passed to the linker uninterpreted.
7807 They typically include the names of
7808 object files for units written in other languages than Ada and any library
7809 references required to resolve references in any of these foreign language
7810 units, or in @code{Import} pragmas in any Ada units.
7811
7812 @var{linker options} is an optional list of linker specific
7813 switches.
7814 The default linker called by gnatlink is @var{gcc} which in
7815 turn calls the appropriate system linker.
7816 Standard options for the linker such as @option{-lmy_lib} or
7817 @option{-Ldir} can be added as is.
7818 For options that are not recognized by
7819 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7820 @option{-Wl,}.
7821 Refer to the GCC documentation for
7822 details. Here is an example showing how to generate a linker map:
7823
7824 @ifclear vms
7825 @smallexample
7826 $ gnatlink my_prog -Wl,-Map,MAPFILE
7827 @end smallexample
7828 @end ifclear
7829
7830 @ifset vms
7831 <<Need example for VMS>>
7832 @end ifset
7833
7834 Using @var{linker options} it is possible to set the program stack and
7835 heap size. See @ref{Setting Stack Size from gnatlink} and
7836 @ref{Setting Heap Size from gnatlink}.
7837
7838 @command{gnatlink} determines the list of objects required by the Ada
7839 program and prepends them to the list of objects passed to the linker.
7840 @command{gnatlink} also gathers any arguments set by the use of
7841 @code{pragma Linker_Options} and adds them to the list of arguments
7842 presented to the linker.
7843
7844 @ifset vms
7845 @command{gnatlink} accepts the following types of extra files on the command
7846 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7847 options files (.OPT). These are recognized and handled according to their
7848 extension.
7849 @end ifset
7850
7851 @node Switches for gnatlink
7852 @section Switches for @command{gnatlink}
7853
7854 @noindent
7855 The following switches are available with the @command{gnatlink} utility:
7856
7857 @table @option
7858 @c !sort!
7859
7860 @item ^-A^/BIND_FILE=ADA^
7861 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
7862 The binder has generated code in Ada. This is the default.
7863
7864 @item ^-C^/BIND_FILE=C^
7865 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
7866 If instead of generating a file in Ada, the binder has generated one in
7867 C, then the linker needs to know about it. Use this switch to signal
7868 to @command{gnatlink} that the binder has generated C code rather than
7869 Ada code.
7870
7871 @item ^-f^/FORCE_OBJECT_FILE_LIST^
7872 @cindex Command line length
7873 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
7874 On some targets, the command line length is limited, and @command{gnatlink}
7875 will generate a separate file for the linker if the list of object files
7876 is too long.
7877 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
7878 to be generated even if
7879 the limit is not exceeded. This is useful in some cases to deal with
7880 special situations where the command line length is exceeded.
7881
7882 @item ^-g^/DEBUG^
7883 @cindex Debugging information, including
7884 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
7885 The option to include debugging information causes the Ada bind file (in
7886 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7887 @option{^-g^/DEBUG^}.
7888 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7889 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7890 Without @option{^-g^/DEBUG^}, the binder removes these files by
7891 default. The same procedure apply if a C bind file was generated using
7892 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
7893 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7894
7895 @item ^-n^/NOCOMPILE^
7896 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
7897 Do not compile the file generated by the binder. This may be used when
7898 a link is rerun with different options, but there is no need to recompile
7899 the binder file.
7900
7901 @item ^-v^/VERBOSE^
7902 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
7903 Causes additional information to be output, including a full list of the
7904 included object files. This switch option is most useful when you want
7905 to see what set of object files are being used in the link step.
7906
7907 @item ^-v -v^/VERBOSE/VERBOSE^
7908 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
7909 Very verbose mode. Requests that the compiler operate in verbose mode when
7910 it compiles the binder file, and that the system linker run in verbose mode.
7911
7912 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7913 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
7914 @var{exec-name} specifies an alternate name for the generated
7915 executable program. If this switch is omitted, the executable has the same
7916 name as the main unit. For example, @code{gnatlink try.ali} creates
7917 an executable called @file{^try^TRY.EXE^}.
7918
7919 @ifclear vms
7920 @item -b @var{target}
7921 @cindex @option{-b} (@command{gnatlink})
7922 Compile your program to run on @var{target}, which is the name of a
7923 system configuration. You must have a GNAT cross-compiler built if
7924 @var{target} is not the same as your host system.
7925
7926 @item -B@var{dir}
7927 @cindex @option{-B} (@command{gnatlink})
7928 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7929 from @var{dir} instead of the default location. Only use this switch
7930 when multiple versions of the GNAT compiler are available. See the
7931 @command{gcc} manual page for further details. You would normally use the
7932 @option{-b} or @option{-V} switch instead.
7933
7934 @item --GCC=@var{compiler_name}
7935 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
7936 Program used for compiling the binder file. The default is
7937 @command{gcc}. You need to use quotes around @var{compiler_name} if
7938 @code{compiler_name} contains spaces or other separator characters. As
7939 an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to use
7940 @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
7941 inserted after your command name. Thus in the above example the compiler
7942 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
7943 If several @option{--GCC=compiler_name} are used, only the last
7944 @var{compiler_name} is taken into account. However, all the additional
7945 switches are also taken into account. Thus,
7946 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7947 @option{--GCC="bar -x -y -z -t"}.
7948
7949 @item --LINK=@var{name}
7950 @cindex @option{--LINK=} (@command{gnatlink})
7951 @var{name} is the name of the linker to be invoked. This is especially
7952 useful in mixed language programs since languages such as C++ require
7953 their own linker to be used. When this switch is omitted, the default
7954 name for the linker is @command{gcc}. When this switch is used, the
7955 specified linker is called instead of @command{gcc} with exactly the same
7956 parameters that would have been passed to @command{gcc} so if the desired
7957 linker requires different parameters it is necessary to use a wrapper
7958 script that massages the parameters before invoking the real linker. It
7959 may be useful to control the exact invocation by using the verbose
7960 switch.
7961
7962 @end ifclear
7963
7964 @ifset vms
7965 @item /DEBUG=TRACEBACK
7966 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
7967 This qualifier causes sufficient information to be included in the
7968 executable file to allow a traceback, but does not include the full
7969 symbol information needed by the debugger.
7970
7971 @item /IDENTIFICATION="<string>"
7972 @code{"<string>"} specifies the string to be stored in the image file
7973 identification field in the image header.
7974 It overrides any pragma @code{Ident} specified string.
7975
7976 @item /NOINHIBIT-EXEC
7977 Generate the executable file even if there are linker warnings.
7978
7979 @item /NOSTART_FILES
7980 Don't link in the object file containing the ``main'' transfer address.
7981 Used when linking with a foreign language main program compiled with a
7982 Digital compiler.
7983
7984 @item /STATIC
7985 Prefer linking with object libraries over sharable images, even without
7986 /DEBUG.
7987 @end ifset
7988
7989 @end table
7990
7991 @node Setting Stack Size from gnatlink
7992 @section Setting Stack Size from @command{gnatlink}
7993
7994 @noindent
7995 Under Windows systems, it is possible to specify the program stack size from
7996 @command{gnatlink} using either:
7997
7998 @itemize @bullet
7999
8000 @item using @option{-Xlinker} linker option
8001
8002 @smallexample
8003 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
8004 @end smallexample
8005
8006 This sets the stack reserve size to 0x10000 bytes and the stack commit
8007 size to 0x1000 bytes.
8008
8009 @item using @option{-Wl} linker option
8010
8011 @smallexample
8012 $ gnatlink hello -Wl,--stack=0x1000000
8013 @end smallexample
8014
8015 This sets the stack reserve size to 0x1000000 bytes. Note that with
8016 @option{-Wl} option it is not possible to set the stack commit size
8017 because the coma is a separator for this option.
8018
8019 @end itemize
8020
8021 @node Setting Heap Size from gnatlink
8022 @section Setting Heap Size from @command{gnatlink}
8023
8024 @noindent
8025 Under Windows systems, it is possible to specify the program heap size from
8026 @command{gnatlink} using either:
8027
8028 @itemize @bullet
8029
8030 @item using @option{-Xlinker} linker option
8031
8032 @smallexample
8033 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
8034 @end smallexample
8035
8036 This sets the heap reserve size to 0x10000 bytes and the heap commit
8037 size to 0x1000 bytes.
8038
8039 @item using @option{-Wl} linker option
8040
8041 @smallexample
8042 $ gnatlink hello -Wl,--heap=0x1000000
8043 @end smallexample
8044
8045 This sets the heap reserve size to 0x1000000 bytes. Note that with
8046 @option{-Wl} option it is not possible to set the heap commit size
8047 because the coma is a separator for this option.
8048
8049 @end itemize
8050
8051 @node The GNAT Make Program gnatmake
8052 @chapter The GNAT Make Program @command{gnatmake}
8053 @findex gnatmake
8054
8055 @menu
8056 * Running gnatmake::
8057 * Switches for gnatmake::
8058 * Mode Switches for gnatmake::
8059 * Notes on the Command Line::
8060 * How gnatmake Works::
8061 * Examples of gnatmake Usage::
8062 @end menu
8063 @noindent
8064 A typical development cycle when working on an Ada program consists of
8065 the following steps:
8066
8067 @enumerate
8068 @item
8069 Edit some sources to fix bugs.
8070
8071 @item
8072 Add enhancements.
8073
8074 @item
8075 Compile all sources affected.
8076
8077 @item
8078 Rebind and relink.
8079
8080 @item
8081 Test.
8082 @end enumerate
8083
8084 @noindent
8085 The third step can be tricky, because not only do the modified files
8086 @cindex Dependency rules
8087 have to be compiled, but any files depending on these files must also be
8088 recompiled. The dependency rules in Ada can be quite complex, especially
8089 in the presence of overloading, @code{use} clauses, generics and inlined
8090 subprograms.
8091
8092 @command{gnatmake} automatically takes care of the third and fourth steps
8093 of this process. It determines which sources need to be compiled,
8094 compiles them, and binds and links the resulting object files.
8095
8096 Unlike some other Ada make programs, the dependencies are always
8097 accurately recomputed from the new sources. The source based approach of
8098 the GNAT compilation model makes this possible. This means that if
8099 changes to the source program cause corresponding changes in
8100 dependencies, they will always be tracked exactly correctly by
8101 @command{gnatmake}.
8102
8103 @node Running gnatmake
8104 @section Running @command{gnatmake}
8105
8106 @noindent
8107 The usual form of the @command{gnatmake} command is
8108
8109 @smallexample
8110 $ gnatmake [@var{switches}] @var{file_name}
8111       [@var{file_names}] [@var{mode_switches}]
8112 @end smallexample
8113
8114 @noindent
8115 The only required argument is one @var{file_name}, which specifies
8116 a compilation unit that is a main program. Several @var{file_names} can be
8117 specified: this will result in several executables being built.
8118 If @code{switches} are present, they can be placed before the first
8119 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8120 If @var{mode_switches} are present, they must always be placed after
8121 the last @var{file_name} and all @code{switches}.
8122
8123 If you are using standard file extensions (.adb and .ads), then the
8124 extension may be omitted from the @var{file_name} arguments. However, if
8125 you are using non-standard extensions, then it is required that the
8126 extension be given. A relative or absolute directory path can be
8127 specified in a @var{file_name}, in which case, the input source file will
8128 be searched for in the specified directory only. Otherwise, the input
8129 source file will first be searched in the directory where
8130 @command{gnatmake} was invoked and if it is not found, it will be search on
8131 the source path of the compiler as described in
8132 @ref{Search Paths and the Run-Time Library (RTL)}.
8133
8134 All @command{gnatmake} output (except when you specify
8135 @option{^-M^/DEPENDENCIES_LIST^}) is to
8136 @file{stderr}. The output produced by the
8137 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8138 @file{stdout}.
8139
8140 @node Switches for gnatmake
8141 @section Switches for @command{gnatmake}
8142
8143 @noindent
8144 You may specify any of the following switches to @command{gnatmake}:
8145
8146 @table @option
8147 @c !sort!
8148 @ifclear vms
8149 @item --GCC=@var{compiler_name}
8150 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8151 Program used for compiling. The default is `@command{gcc}'. You need to use
8152 quotes around @var{compiler_name} if @code{compiler_name} contains
8153 spaces or other separator characters. As an example @option{--GCC="foo -x
8154 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8155 compiler. Note that switch @option{-c} is always inserted after your
8156 command name. Thus in the above example the compiler command that will
8157 be used by @command{gnatmake} will be @code{foo -c -x -y}.
8158 If several @option{--GCC=compiler_name} are used, only the last
8159 @var{compiler_name} is taken into account. However, all the additional
8160 switches are also taken into account. Thus,
8161 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8162 @option{--GCC="bar -x -y -z -t"}.
8163
8164 @item --GNATBIND=@var{binder_name}
8165 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8166 Program used for binding. The default is `@code{gnatbind}'. You need to
8167 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8168 or other separator characters. As an example @option{--GNATBIND="bar -x
8169 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8170 binder. Binder switches that are normally appended by @command{gnatmake} to
8171 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8172
8173 @item --GNATLINK=@var{linker_name}
8174 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8175 Program used for linking. The default is `@command{gnatlink}'. You need to
8176 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8177 or other separator characters. As an example @option{--GNATLINK="lan -x
8178 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8179 linker. Linker switches that are normally appended by @command{gnatmake} to
8180 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8181
8182 @end ifclear
8183
8184 @item ^-a^/ALL_FILES^
8185 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8186 Consider all files in the make process, even the GNAT internal system
8187 files (for example, the predefined Ada library files), as well as any
8188 locked files. Locked files are files whose ALI file is write-protected.
8189 By default,
8190 @command{gnatmake} does not check these files,
8191 because the assumption is that the GNAT internal files are properly up
8192 to date, and also that any write protected ALI files have been properly
8193 installed. Note that if there is an installation problem, such that one
8194 of these files is not up to date, it will be properly caught by the
8195 binder.
8196 You may have to specify this switch if you are working on GNAT
8197 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8198 in conjunction with @option{^-f^/FORCE_COMPILE^}
8199 if you need to recompile an entire application,
8200 including run-time files, using special configuration pragmas,
8201 such as a @code{Normalize_Scalars} pragma.
8202
8203 By default
8204 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8205 internal files with
8206 @ifclear vms
8207 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8208 @end ifclear
8209 @ifset vms
8210 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8211 @end ifset
8212
8213 @item ^-b^/ACTIONS=BIND^
8214 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8215 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8216 compilation and binding, but no link.
8217 Can be combined with @option{^-l^/ACTIONS=LINK^}
8218 to do binding and linking. When not combined with
8219 @option{^-c^/ACTIONS=COMPILE^}
8220 all the units in the closure of the main program must have been previously
8221 compiled and must be up to date. The root unit specified by @var{file_name}
8222 may be given without extension, with the source extension or, if no GNAT
8223 Project File is specified, with the ALI file extension.
8224
8225 @item ^-c^/ACTIONS=COMPILE^
8226 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8227 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8228 is also specified. Do not perform linking, except if both
8229 @option{^-b^/ACTIONS=BIND^} and
8230  @option{^-l^/ACTIONS=LINK^} are also specified.
8231 If the root unit specified by @var{file_name} is not a main unit, this is the
8232 default. Otherwise @command{gnatmake} will attempt binding and linking
8233 unless all objects are up to date and the executable is more recent than
8234 the objects.
8235
8236 @item ^-C^/MAPPING^
8237 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8238 Use a temporary mapping file. A mapping file is a way to communicate to the
8239 compiler two mappings: from unit names to file names (without any directory
8240 information) and from file names to path names (with full directory
8241 information). These mappings are used by the compiler to short-circuit the path
8242 search. When @command{gnatmake} is invoked with this switch, it will create
8243 a temporary mapping file, initially populated by the project manager,
8244 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8245 Each invocation of the compiler will add the newly accessed sources to the
8246 mapping file. This will improve the source search during the next invocation
8247 of the compiler.
8248
8249 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8250 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8251 Use a specific mapping file. The file, specified as a path name (absolute or
8252 relative) by this switch, should already exist, otherwise the switch is
8253 ineffective. The specified mapping file will be communicated to the compiler.
8254 This switch is not compatible with a project file
8255 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8256 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8257
8258 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8259 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8260 Put all object files and ALI file in directory @var{dir}.
8261 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8262 and ALI files go in the current working directory.
8263
8264 This switch cannot be used when using a project file.
8265
8266 @ifclear vms
8267 @item -eL
8268 @cindex @option{-eL} (@command{gnatmake})
8269 Follow all symbolic links when processing project files.
8270 @end ifclear
8271
8272 @item ^-f^/FORCE_COMPILE^
8273 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
8274 Force recompilations. Recompile all sources, even though some object
8275 files may be up to date, but don't recompile predefined or GNAT internal
8276 files or locked files (files with a write-protected ALI file),
8277 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8278
8279 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8280 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
8281 When using project files, if some errors or warnings are detected during
8282 parsing and verbose mode is not in effect (no use of switch
8283 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8284 file, rather than its simple file name.
8285
8286 @item ^-i^/IN_PLACE^
8287 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
8288 In normal mode, @command{gnatmake} compiles all object files and ALI files
8289 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8290 then instead object files and ALI files that already exist are overwritten
8291 in place. This means that once a large project is organized into separate
8292 directories in the desired manner, then @command{gnatmake} will automatically
8293 maintain and update this organization. If no ALI files are found on the
8294 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8295 the new object and ALI files are created in the
8296 directory containing the source being compiled. If another organization
8297 is desired, where objects and sources are kept in different directories,
8298 a useful technique is to create dummy ALI files in the desired directories.
8299 When detecting such a dummy file, @command{gnatmake} will be forced to
8300 recompile the corresponding source file, and it will be put the resulting
8301 object and ALI files in the directory where it found the dummy file.
8302
8303 @item ^-j^/PROCESSES=^@var{n}
8304 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
8305 @cindex Parallel make
8306 Use @var{n} processes to carry out the (re)compilations. On a
8307 multiprocessor machine compilations will occur in parallel. In the
8308 event of compilation errors, messages from various compilations might
8309 get interspersed (but @command{gnatmake} will give you the full ordered
8310 list of failing compiles at the end). If this is problematic, rerun
8311 the make process with n set to 1 to get a clean list of messages.
8312
8313 @item ^-k^/CONTINUE_ON_ERROR^
8314 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
8315 Keep going. Continue as much as possible after a compilation error. To
8316 ease the programmer's task in case of compilation errors, the list of
8317 sources for which the compile fails is given when @command{gnatmake}
8318 terminates.
8319
8320 If @command{gnatmake} is invoked with several @file{file_names} and with this
8321 switch, if there are compilation errors when building an executable,
8322 @command{gnatmake} will not attempt to build the following executables.
8323
8324 @item ^-l^/ACTIONS=LINK^
8325 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
8326 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8327 and linking. Linking will not be performed if combined with
8328 @option{^-c^/ACTIONS=COMPILE^}
8329 but not with @option{^-b^/ACTIONS=BIND^}.
8330 When not combined with @option{^-b^/ACTIONS=BIND^}
8331 all the units in the closure of the main program must have been previously
8332 compiled and must be up to date, and the main program needs to have been bound.
8333 The root unit specified by @var{file_name}
8334 may be given without extension, with the source extension or, if no GNAT
8335 Project File is specified, with the ALI file extension.
8336
8337 @item ^-m^/MINIMAL_RECOMPILATION^
8338 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
8339 Specify that the minimum necessary amount of recompilations
8340 be performed. In this mode @command{gnatmake} ignores time
8341 stamp differences when the only
8342 modifications to a source file consist in adding/removing comments,
8343 empty lines, spaces or tabs. This means that if you have changed the
8344 comments in a source file or have simply reformatted it, using this
8345 switch will tell gnatmake not to recompile files that depend on it
8346 (provided other sources on which these files depend have undergone no
8347 semantic modifications). Note that the debugging information may be
8348 out of date with respect to the sources if the @option{-m} switch causes
8349 a compilation to be switched, so the use of this switch represents a
8350 trade-off between compilation time and accurate debugging information.
8351
8352 @item ^-M^/DEPENDENCIES_LIST^
8353 @cindex Dependencies, producing list
8354 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
8355 Check if all objects are up to date. If they are, output the object
8356 dependences to @file{stdout} in a form that can be directly exploited in
8357 a @file{Makefile}. By default, each source file is prefixed with its
8358 (relative or absolute) directory name. This name is whatever you
8359 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8360 and @option{^-I^/SEARCH^} switches. If you use
8361 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8362 @option{^-q^/QUIET^}
8363 (see below), only the source file names,
8364 without relative paths, are output. If you just specify the
8365 @option{^-M^/DEPENDENCIES_LIST^}
8366 switch, dependencies of the GNAT internal system files are omitted. This
8367 is typically what you want. If you also specify
8368 the @option{^-a^/ALL_FILES^} switch,
8369 dependencies of the GNAT internal files are also listed. Note that
8370 dependencies of the objects in external Ada libraries (see switch
8371 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8372 are never reported.
8373
8374 @item ^-n^/DO_OBJECT_CHECK^
8375 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
8376 Don't compile, bind, or link. Checks if all objects are up to date.
8377 If they are not, the full name of the first file that needs to be
8378 recompiled is printed.
8379 Repeated use of this option, followed by compiling the indicated source
8380 file, will eventually result in recompiling all required units.
8381
8382 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8383 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
8384 Output executable name. The name of the final executable program will be
8385 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8386 name for the executable will be the name of the input file in appropriate form
8387 for an executable file on the host system.
8388
8389 This switch cannot be used when invoking @command{gnatmake} with several
8390 @file{file_names}.
8391
8392 @item ^-P^/PROJECT_FILE=^@var{project}
8393 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
8394 Use project file @var{project}. Only one such switch can be used.
8395 @xref{gnatmake and Project Files}.
8396
8397 @item ^-q^/QUIET^
8398 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
8399 Quiet. When this flag is not set, the commands carried out by
8400 @command{gnatmake} are displayed.
8401
8402 @item ^-s^/SWITCH_CHECK/^
8403 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
8404 Recompile if compiler switches have changed since last compilation.
8405 All compiler switches but -I and -o are taken into account in the
8406 following way:
8407 orders between different ``first letter'' switches are ignored, but
8408 orders between same switches are taken into account. For example,
8409 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8410 is equivalent to @option{-O -g}.
8411
8412 This switch is recommended when Integrated Preprocessing is used.
8413
8414 @item ^-u^/UNIQUE^
8415 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
8416 Unique. Recompile at most the main files. It implies -c. Combined with
8417 -f, it is equivalent to calling the compiler directly. Note that using
8418 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8419 (@pxref{Project Files and Main Subprograms}).
8420
8421 @item ^-U^/ALL_PROJECTS^
8422 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
8423 When used without a project file or with one or several mains on the command
8424 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8425 on the command line, all sources of all project files are checked and compiled
8426 if not up to date, and libraries are rebuilt, if necessary.
8427
8428 @item ^-v^/REASONS^
8429 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
8430 Verbose. Display the reason for all recompilations @command{gnatmake}
8431 decides are necessary.
8432
8433 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8434 Indicate the verbosity of the parsing of GNAT project files.
8435 @xref{Switches Related to Project Files}.
8436
8437 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8438 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
8439 Indicate that sources that are not part of any Project File may be compiled.
8440 Normally, when using Project Files, only sources that are part of a Project
8441 File may be compile. When this switch is used, a source outside of all Project
8442 Files may be compiled. The ALI file and the object file will be put in the
8443 object directory of the main Project. The compilation switches used will only
8444 be those specified on the command line.
8445
8446 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8447 Indicate that external variable @var{name} has the value @var{value}.
8448 The Project Manager will use this value for occurrences of
8449 @code{external(name)} when parsing the project file.
8450 @xref{Switches Related to Project Files}.
8451
8452 @item ^-z^/NOMAIN^
8453 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
8454 No main subprogram. Bind and link the program even if the unit name
8455 given on the command line is a package name. The resulting executable
8456 will execute the elaboration routines of the package and its closure,
8457 then the finalization routines.
8458
8459 @item ^-g^/DEBUG^
8460 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
8461 Enable debugging. This switch is simply passed to the compiler and to the
8462 linker.
8463
8464 @end table
8465
8466 @table @asis
8467 @item @command{gcc} @asis{switches}
8468 @ifclear vms
8469 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
8470 is passed to @command{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8471 @end ifclear
8472 @ifset vms
8473 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8474 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8475 automatically treated as a compiler switch, and passed on to all
8476 compilations that are carried out.
8477 @end ifset
8478 @end table
8479
8480 @noindent
8481 Source and library search path switches:
8482
8483 @table @option
8484 @c !sort!
8485 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8486 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
8487 When looking for source files also look in directory @var{dir}.
8488 The order in which source files search is undertaken is
8489 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8490
8491 @item ^-aL^/SKIP_MISSING=^@var{dir}
8492 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
8493 Consider @var{dir} as being an externally provided Ada library.
8494 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
8495 files have been located in directory @var{dir}. This allows you to have
8496 missing bodies for the units in @var{dir} and to ignore out of date bodies
8497 for the same units. You still need to specify
8498 the location of the specs for these units by using the switches
8499 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8500 or @option{^-I^/SEARCH=^@var{dir}}.
8501 Note: this switch is provided for compatibility with previous versions
8502 of @command{gnatmake}. The easier method of causing standard libraries
8503 to be excluded from consideration is to write-protect the corresponding
8504 ALI files.
8505
8506 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8507 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
8508 When searching for library and object files, look in directory
8509 @var{dir}. The order in which library files are searched is described in
8510 @ref{Search Paths for gnatbind}.
8511
8512 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8513 @cindex Search paths, for @command{gnatmake}
8514 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
8515 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8516 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8517
8518 @item ^-I^/SEARCH=^@var{dir}
8519 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
8520 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8521 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8522
8523 @item ^-I-^/NOCURRENT_DIRECTORY^
8524 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
8525 @cindex Source files, suppressing search
8526 Do not look for source files in the directory containing the source
8527 file named in the command line.
8528 Do not look for ALI or object files in the directory
8529 where @command{gnatmake} was invoked.
8530
8531 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8532 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
8533 @cindex Linker libraries
8534 Add directory @var{dir} to the list of directories in which the linker
8535 will search for libraries. This is equivalent to
8536 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8537 @ifclear vms
8538 Furthermore, under Windows, the sources pointed to by the libraries path
8539 set in the registry are not searched for.
8540 @end ifclear
8541
8542 @item -nostdinc
8543 @cindex @option{-nostdinc} (@command{gnatmake})
8544 Do not look for source files in the system default directory.
8545
8546 @item -nostdlib
8547 @cindex @option{-nostdlib} (@command{gnatmake})
8548 Do not look for library files in the system default directory.
8549
8550 @item --RTS=@var{rts-path}
8551 @cindex @option{--RTS} (@command{gnatmake})
8552 Specifies the default location of the runtime library. GNAT looks for the
8553 runtime
8554 in the following directories, and stops as soon as a valid runtime is found
8555 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8556 @file{ada_object_path} present):
8557
8558 @itemize @bullet
8559 @item <current directory>/$rts_path
8560
8561 @item <default-search-dir>/$rts_path
8562
8563 @item <default-search-dir>/rts-$rts_path
8564 @end itemize
8565
8566 @noindent
8567 The selected path is handled like a normal RTS path.
8568
8569 @end table
8570
8571 @node Mode Switches for gnatmake
8572 @section Mode Switches for @command{gnatmake}
8573
8574 @noindent
8575 The mode switches (referred to as @code{mode_switches}) allow the
8576 inclusion of switches that are to be passed to the compiler itself, the
8577 binder or the linker. The effect of a mode switch is to cause all
8578 subsequent switches up to the end of the switch list, or up to the next
8579 mode switch, to be interpreted as switches to be passed on to the
8580 designated component of GNAT.
8581
8582 @table @option
8583 @c !sort!
8584 @item -cargs @var{switches}
8585 @cindex @option{-cargs} (@command{gnatmake})
8586 Compiler switches. Here @var{switches} is a list of switches
8587 that are valid switches for @command{gcc}. They will be passed on to
8588 all compile steps performed by @command{gnatmake}.
8589
8590 @item -bargs @var{switches}
8591 @cindex @option{-bargs} (@command{gnatmake})
8592 Binder switches. Here @var{switches} is a list of switches
8593 that are valid switches for @code{gnatbind}. They will be passed on to
8594 all bind steps performed by @command{gnatmake}.
8595
8596 @item -largs @var{switches}
8597 @cindex @option{-largs} (@command{gnatmake})
8598 Linker switches. Here @var{switches} is a list of switches
8599 that are valid switches for @command{gnatlink}. They will be passed on to
8600 all link steps performed by @command{gnatmake}.
8601
8602 @item -margs @var{switches}
8603 @cindex @option{-margs} (@command{gnatmake})
8604 Make switches. The switches are directly interpreted by @command{gnatmake},
8605 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8606 or @option{-largs}.
8607 @end table
8608
8609 @node Notes on the Command Line
8610 @section Notes on the Command Line
8611
8612 @noindent
8613 This section contains some additional useful notes on the operation
8614 of the @command{gnatmake} command.
8615
8616 @itemize @bullet
8617 @item
8618 @cindex Recompilation, by @command{gnatmake}
8619 If @command{gnatmake} finds no ALI files, it recompiles the main program
8620 and all other units required by the main program.
8621 This means that @command{gnatmake}
8622 can be used for the initial compile, as well as during subsequent steps of
8623 the development cycle.
8624
8625 @item
8626 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8627 is a subunit or body of a generic unit, @command{gnatmake} recompiles
8628 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8629 warning.
8630
8631 @item
8632 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
8633 is used to specify both source and
8634 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8635 instead if you just want to specify
8636 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8637 if you want to specify library paths
8638 only.
8639
8640 @item
8641 @command{gnatmake} will ignore any files whose ALI file is write-protected.
8642 This may conveniently be used to exclude standard libraries from
8643 consideration and in particular it means that the use of the
8644 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8645 unless @option{^-a^/ALL_FILES^} is also specified.
8646
8647 @item
8648 @command{gnatmake} has been designed to make the use of Ada libraries
8649 particularly convenient. Assume you have an Ada library organized
8650 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8651 of your Ada compilation units,
8652 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8653 specs of these units, but no bodies. Then to compile a unit
8654 stored in @code{main.adb}, which uses this Ada library you would just type
8655
8656 @smallexample
8657 @ifclear vms
8658 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8659 @end ifclear
8660 @ifset vms
8661 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8662            /SKIP_MISSING=@i{[OBJ_DIR]} main
8663 @end ifset
8664 @end smallexample
8665
8666 @item
8667 Using @command{gnatmake} along with the
8668 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8669 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8670 this switch,
8671 you can update the comments/format of your
8672 source files without having to recompile everything. Note, however, that
8673 adding or deleting lines in a source files may render its debugging
8674 info obsolete. If the file in question is a spec, the impact is rather
8675 limited, as that debugging info will only be useful during the
8676 elaboration phase of your program. For bodies the impact can be more
8677 significant. In all events, your debugger will warn you if a source file
8678 is more recent than the corresponding object, and alert you to the fact
8679 that the debugging information may be out of date.
8680 @end itemize
8681
8682 @node How gnatmake Works
8683 @section How @command{gnatmake} Works
8684
8685 @noindent
8686 Generally @command{gnatmake} automatically performs all necessary
8687 recompilations and you don't need to worry about how it works. However,
8688 it may be useful to have some basic understanding of the @command{gnatmake}
8689 approach and in particular to understand how it uses the results of
8690 previous compilations without incorrectly depending on them.
8691
8692 First a definition: an object file is considered @dfn{up to date} if the
8693 corresponding ALI file exists and if all the source files listed in the
8694 dependency section of this ALI file have time stamps matching those in
8695 the ALI file. This means that neither the source file itself nor any
8696 files that it depends on have been modified, and hence there is no need
8697 to recompile this file.
8698
8699 @command{gnatmake} works by first checking if the specified main unit is up
8700 to date. If so, no compilations are required for the main unit. If not,
8701 @command{gnatmake} compiles the main program to build a new ALI file that
8702 reflects the latest sources. Then the ALI file of the main unit is
8703 examined to find all the source files on which the main program depends,
8704 and @command{gnatmake} recursively applies the above procedure on all these
8705 files.
8706
8707 This process ensures that @command{gnatmake} only trusts the dependencies
8708 in an existing ALI file if they are known to be correct. Otherwise it
8709 always recompiles to determine a new, guaranteed accurate set of
8710 dependencies. As a result the program is compiled ``upside down'' from what may
8711 be more familiar as the required order of compilation in some other Ada
8712 systems. In particular, clients are compiled before the units on which
8713 they depend. The ability of GNAT to compile in any order is critical in
8714 allowing an order of compilation to be chosen that guarantees that
8715 @command{gnatmake} will recompute a correct set of new dependencies if
8716 necessary.
8717
8718 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
8719 imported by several of the executables, it will be recompiled at most once.
8720
8721 Note: when using non-standard naming conventions
8722 (@pxref{Using Other File Names}), changing through a configuration pragmas
8723 file the version of a source and invoking @command{gnatmake} to recompile may
8724 have no effect, if the previous version of the source is still accessible
8725 by @command{gnatmake}. It may be necessary to use the switch
8726 ^-f^/FORCE_COMPILE^.
8727
8728 @node Examples of gnatmake Usage
8729 @section Examples of @command{gnatmake} Usage
8730
8731 @table @code
8732 @item gnatmake hello.adb
8733 Compile all files necessary to bind and link the main program
8734 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8735 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8736
8737 @item gnatmake main1 main2 main3
8738 Compile all files necessary to bind and link the main programs
8739 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8740 (containing unit @code{Main2}) and @file{main3.adb}
8741 (containing unit @code{Main3}) and bind and link the resulting object files
8742 to generate three executable files @file{^main1^MAIN1.EXE^},
8743 @file{^main2^MAIN2.EXE^}
8744 and @file{^main3^MAIN3.EXE^}.
8745
8746 @ifclear vms
8747 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8748 @end ifclear
8749
8750 @ifset vms
8751 @item gnatmake Main_Unit /QUIET
8752    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8753    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8754 @end ifset
8755 Compile all files necessary to bind and link the main program unit
8756 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8757 be done with optimization level 2 and the order of elaboration will be
8758 listed by the binder. @command{gnatmake} will operate in quiet mode, not
8759 displaying commands it is executing.
8760 @end table
8761
8762 @c *************************
8763 @node Improving Performance
8764 @chapter Improving Performance
8765 @cindex Improving performance
8766
8767 @noindent
8768 This chapter presents several topics related to program performance.
8769 It first describes some of the tradeoffs that need to be considered
8770 and some of the techniques for making your program run faster.
8771 It then documents the @command{gnatelim} tool, which can reduce
8772 the size of program executables.
8773
8774 @ifnottex
8775 @menu
8776 * Performance Considerations::
8777 * Reducing the Size of Ada Executables with gnatelim::
8778 @end menu
8779 @end ifnottex
8780
8781 @c *****************************
8782 @node Performance Considerations
8783 @section Performance Considerations
8784
8785 @noindent
8786 The GNAT system provides a number of options that allow a trade-off
8787 between
8788
8789 @itemize @bullet
8790 @item
8791 performance of the generated code
8792
8793 @item
8794 speed of compilation
8795
8796 @item
8797 minimization of dependences and recompilation
8798
8799 @item
8800 the degree of run-time checking.
8801 @end itemize
8802
8803 @noindent
8804 The defaults (if no options are selected) aim at improving the speed
8805 of compilation and minimizing dependences, at the expense of performance
8806 of the generated code:
8807
8808 @itemize @bullet
8809 @item
8810 no optimization
8811
8812 @item
8813 no inlining of subprogram calls
8814
8815 @item
8816 all run-time checks enabled except overflow and elaboration checks
8817 @end itemize
8818
8819 @noindent
8820 These options are suitable for most program development purposes. This
8821 chapter describes how you can modify these choices, and also provides
8822 some guidelines on debugging optimized code.
8823
8824 @menu
8825 * Controlling Run-Time Checks::
8826 * Use of Restrictions::
8827 * Optimization Levels::
8828 * Debugging Optimized Code::
8829 * Inlining of Subprograms::
8830 * Optimization and Strict Aliasing::
8831 @ifset vms
8832 * Coverage Analysis::
8833 @end ifset
8834 @end menu
8835
8836 @node Controlling Run-Time Checks
8837 @subsection Controlling Run-Time Checks
8838
8839 @noindent
8840 By default, GNAT generates all run-time checks, except arithmetic overflow
8841 checking for integer operations and checks for access before elaboration on
8842 subprogram calls. The latter are not required in default mode, because all
8843 necessary checking is done at compile time.
8844 @cindex @option{-gnatp} (@command{gcc})
8845 @cindex @option{-gnato} (@command{gcc})
8846 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8847 be modified. @xref{Run-Time Checks}.
8848
8849 Our experience is that the default is suitable for most development
8850 purposes.
8851
8852 We treat integer overflow specially because these
8853 are quite expensive and in our experience are not as important as other
8854 run-time checks in the development process. Note that division by zero
8855 is not considered an overflow check, and divide by zero checks are
8856 generated where required by default.
8857
8858 Elaboration checks are off by default, and also not needed by default, since
8859 GNAT uses a static elaboration analysis approach that avoids the need for
8860 run-time checking. This manual contains a full chapter discussing the issue
8861 of elaboration checks, and if the default is not satisfactory for your use,
8862 you should read this chapter.
8863
8864 For validity checks, the minimal checks required by the Ada Reference
8865 Manual (for case statements and assignments to array elements) are on
8866 by default. These can be suppressed by use of the @option{-gnatVn} switch.
8867 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8868 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8869 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8870 are also suppressed entirely if @option{-gnatp} is used.
8871
8872 @cindex Overflow checks
8873 @cindex Checks, overflow
8874 @findex Suppress
8875 @findex Unsuppress
8876 @cindex pragma Suppress
8877 @cindex pragma Unsuppress
8878 Note that the setting of the switches controls the default setting of
8879 the checks. They may be modified using either @code{pragma Suppress} (to
8880 remove checks) or @code{pragma Unsuppress} (to add back suppressed
8881 checks) in the program source.
8882
8883 @node Use of Restrictions
8884 @subsection Use of Restrictions
8885
8886 @noindent
8887 The use of pragma Restrictions allows you to control which features are
8888 permitted in your program. Apart from the obvious point that if you avoid
8889 relatively expensive features like finalization (enforceable by the use
8890 of pragma Restrictions (No_Finalization), the use of this pragma does not
8891 affect the generated code in most cases.
8892
8893 One notable exception to this rule is that the possibility of task abort
8894 results in some distributed overhead, particularly if finalization or
8895 exception handlers are used. The reason is that certain sections of code
8896 have to be marked as non-abortable.
8897
8898 If you use neither the @code{abort} statement, nor asynchronous transfer
8899 of control (@code{select .. then abort}), then this distributed overhead
8900 is removed, which may have a general positive effect in improving
8901 overall performance.  Especially code involving frequent use of tasking
8902 constructs and controlled types will show much improved performance.
8903 The relevant restrictions pragmas are
8904
8905 @smallexample
8906    pragma Restrictions (No_Abort_Statements);
8907    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
8908 @end smallexample
8909
8910 @noindent
8911 It is recommended that these restriction pragmas be used if possible. Note
8912 that this also means that you can write code without worrying about the
8913 possibility of an immediate abort at any point.
8914
8915 @node Optimization Levels
8916 @subsection Optimization Levels
8917 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
8918
8919 @noindent
8920 The default is optimization off. This results in the fastest compile
8921 times, but GNAT makes absolutely no attempt to optimize, and the
8922 generated programs are considerably larger and slower than when
8923 optimization is enabled. You can use the
8924 @ifclear vms
8925 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
8926 @end ifclear
8927 @ifset vms
8928 @code{OPTIMIZE} qualifier
8929 @end ifset
8930 to @command{gcc} to control the optimization level:
8931
8932 @table @option
8933 @item ^-O0^/OPTIMIZE=NONE^
8934 No optimization (the default);
8935 generates unoptimized code but has
8936 the fastest compilation time.
8937
8938 @item ^-O1^/OPTIMIZE=SOME^
8939 Medium level optimization;
8940 optimizes reasonably well but does not
8941 degrade compilation time significantly.
8942
8943 @item ^-O2^/OPTIMIZE=ALL^
8944 @ifset vms
8945 @itemx /OPTIMIZE=DEVELOPMENT
8946 @end ifset
8947 Full optimization;
8948 generates highly optimized code and has
8949 the slowest compilation time.
8950
8951 @item ^-O3^/OPTIMIZE=INLINING^
8952 Full optimization as in @option{-O2},
8953 and also attempts automatic inlining of small
8954 subprograms within a unit (@pxref{Inlining of Subprograms}).
8955 @end table
8956
8957 @noindent
8958 Higher optimization levels perform more global transformations on the
8959 program and apply more expensive analysis algorithms in order to generate
8960 faster and more compact code. The price in compilation time, and the
8961 resulting improvement in execution time,
8962 both depend on the particular application and the hardware environment.
8963 You should experiment to find the best level for your application.
8964
8965 Since the precise set of optimizations done at each level will vary from
8966 release to release (and sometime from target to target), it is best to think
8967 of the optimization settings in general terms.
8968 The @cite{Using GNU GCC} manual contains details about
8969 ^the @option{-O} settings and a number of @option{-f} options that^how to^
8970 individually enable or disable specific optimizations.
8971
8972 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
8973 been tested extensively at all optimization levels. There are some bugs
8974 which appear only with optimization turned on, but there have also been
8975 bugs which show up only in @emph{unoptimized} code. Selecting a lower
8976 level of optimization does not improve the reliability of the code
8977 generator, which in practice is highly reliable at all optimization
8978 levels.
8979
8980 Note regarding the use of @option{-O3}: The use of this optimization level
8981 is generally discouraged with GNAT, since it often results in larger
8982 executables which run more slowly. See further discussion of this point
8983 in @ref{Inlining of Subprograms}.
8984
8985 @node Debugging Optimized Code
8986 @subsection Debugging Optimized Code
8987 @cindex Debugging optimized code
8988 @cindex Optimization and debugging
8989
8990 @noindent
8991 Although it is possible to do a reasonable amount of debugging at
8992 @ifclear vms
8993 non-zero optimization levels,
8994 the higher the level the more likely that
8995 @end ifclear
8996 @ifset vms
8997 @option{/OPTIMIZE} settings other than @code{NONE},
8998 such settings will make it more likely that
8999 @end ifset
9000 source-level constructs will have been eliminated by optimization.
9001 For example, if a loop is strength-reduced, the loop
9002 control variable may be completely eliminated and thus cannot be
9003 displayed in the debugger.
9004 This can only happen at @option{-O2} or @option{-O3}.
9005 Explicit temporary variables that you code might be eliminated at
9006 ^level^setting^ @option{-O1} or higher.
9007
9008 The use of the @option{^-g^/DEBUG^} switch,
9009 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9010 which is needed for source-level debugging,
9011 affects the size of the program executable on disk,
9012 and indeed the debugging information can be quite large.
9013 However, it has no effect on the generated code (and thus does not
9014 degrade performance)
9015
9016 Since the compiler generates debugging tables for a compilation unit before
9017 it performs optimizations, the optimizing transformations may invalidate some
9018 of the debugging data.  You therefore need to anticipate certain
9019 anomalous situations that may arise while debugging optimized code.
9020 These are the most common cases:
9021
9022 @enumerate
9023 @item
9024 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
9025 commands show
9026 the PC bouncing back and forth in the code.  This may result from any of
9027 the following optimizations:
9028
9029 @itemize @bullet
9030 @item
9031 @i{Common subexpression elimination:} using a single instance of code for a
9032 quantity that the source computes several times.  As a result you
9033 may not be able to stop on what looks like a statement.
9034
9035 @item
9036 @i{Invariant code motion:} moving an expression that does not change within a
9037 loop, to the beginning of the loop.
9038
9039 @item
9040 @i{Instruction scheduling:} moving instructions so as to
9041 overlap loads and stores (typically) with other code, or in
9042 general to move computations of values closer to their uses. Often
9043 this causes you to pass an assignment statement without the assignment
9044 happening and then later bounce back to the statement when the
9045 value is actually needed.  Placing a breakpoint on a line of code
9046 and then stepping over it may, therefore, not always cause all the
9047 expected side-effects.
9048 @end itemize
9049
9050 @item
9051 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9052 two identical pieces of code are merged and the program counter suddenly
9053 jumps to a statement that is not supposed to be executed, simply because
9054 it (and the code following) translates to the same thing as the code
9055 that @emph{was} supposed to be executed.  This effect is typically seen in
9056 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9057 a @code{break} in a C @code{^switch^switch^} statement.
9058
9059 @item
9060 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9061 There are various reasons for this effect:
9062
9063 @itemize @bullet
9064 @item
9065 In a subprogram prologue, a parameter may not yet have been moved to its
9066 ``home''.
9067
9068 @item
9069 A variable may be dead, and its register re-used.  This is
9070 probably the most common cause.
9071
9072 @item
9073 As mentioned above, the assignment of a value to a variable may
9074 have been moved.
9075
9076 @item
9077 A variable may be eliminated entirely by value propagation or
9078 other means.  In this case, GCC may incorrectly generate debugging
9079 information for the variable
9080 @end itemize
9081
9082 @noindent
9083 In general, when an unexpected value appears for a local variable or parameter
9084 you should first ascertain if that value was actually computed by
9085 your program, as opposed to being incorrectly reported by the debugger.
9086 Record fields or
9087 array elements in an object designated by an access value
9088 are generally less of a problem, once you have ascertained that the access
9089 value is sensible.
9090 Typically, this means checking variables in the preceding code and in the
9091 calling subprogram to verify that the value observed is explainable from other
9092 values (one must apply the procedure recursively to those
9093 other values); or re-running the code and stopping a little earlier
9094 (perhaps before the call) and stepping to better see how the variable obtained
9095 the value in question; or continuing to step @emph{from} the point of the
9096 strange value to see if code motion had simply moved the variable's
9097 assignments later.
9098 @end enumerate
9099
9100 @noindent
9101 In light of such anomalies, a recommended technique is to use @option{-O0}
9102 early in the software development cycle, when extensive debugging capabilities
9103 are most needed, and then move to @option{-O1} and later @option{-O2} as
9104 the debugger becomes less critical.
9105 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9106 a release management issue.
9107 @ifclear vms
9108 Note that if you use @option{-g} you can then use the @command{strip} program
9109 on the resulting executable,
9110 which removes both debugging information and global symbols.
9111 @end ifclear
9112
9113 @node Inlining of Subprograms
9114 @subsection Inlining of Subprograms
9115
9116 @noindent
9117 A call to a subprogram in the current unit is inlined if all the
9118 following conditions are met:
9119
9120 @itemize @bullet
9121 @item
9122 The optimization level is at least @option{-O1}.
9123
9124 @item
9125 The called subprogram is suitable for inlining: It must be small enough
9126 and not contain nested subprograms or anything else that @command{gcc}
9127 cannot support in inlined subprograms.
9128
9129 @item
9130 The call occurs after the definition of the body of the subprogram.
9131
9132 @item
9133 @cindex pragma Inline
9134 @findex Inline
9135 Either @code{pragma Inline} applies to the subprogram or it is
9136 small and automatic inlining (optimization level @option{-O3}) is
9137 specified.
9138 @end itemize
9139
9140 @noindent
9141 Calls to subprograms in @code{with}'ed units are normally not inlined.
9142 To achieve this level of inlining, the following conditions must all be
9143 true:
9144
9145 @itemize @bullet
9146 @item
9147 The optimization level is at least @option{-O1}.
9148
9149 @item
9150 The called subprogram is suitable for inlining: It must be small enough
9151 and not contain nested subprograms or anything else @command{gcc} cannot
9152 support in inlined subprograms.
9153
9154 @item
9155 The call appears in a body (not in a package spec).
9156
9157 @item
9158 There is a @code{pragma Inline} for the subprogram.
9159
9160 @item
9161 @cindex @option{-gnatn} (@command{gcc})
9162 The @option{^-gnatn^/INLINE^} switch
9163 is used in the @command{gcc} command line
9164 @end itemize
9165
9166 Note that specifying the @option{-gnatn} switch causes additional
9167 compilation dependencies. Consider the following:
9168
9169 @smallexample @c ada
9170 @cartouche
9171 package R is
9172    procedure Q;
9173    pragma Inline (Q);
9174 end R;
9175 package body R is
9176    ...
9177 end R;
9178
9179 with R;
9180 procedure Main is
9181 begin
9182    ...
9183    R.Q;
9184 end Main;
9185 @end cartouche
9186 @end smallexample
9187
9188 @noindent
9189 With the default behavior (no @option{-gnatn} switch specified), the
9190 compilation of the @code{Main} procedure depends only on its own source,
9191 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9192 means that editing the body of @code{R} does not require recompiling
9193 @code{Main}.
9194
9195 On the other hand, the call @code{R.Q} is not inlined under these
9196 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9197 is compiled, the call will be inlined if the body of @code{Q} is small
9198 enough, but now @code{Main} depends on the body of @code{R} in
9199 @file{r.adb} as well as on the spec. This means that if this body is edited,
9200 the main program must be recompiled. Note that this extra dependency
9201 occurs whether or not the call is in fact inlined by @command{gcc}.
9202
9203 The use of front end inlining with @option{-gnatN} generates similar
9204 additional dependencies.
9205
9206 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
9207 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9208 can be used to prevent
9209 all inlining. This switch overrides all other conditions and ensures
9210 that no inlining occurs. The extra dependences resulting from
9211 @option{-gnatn} will still be active, even if
9212 this switch is used to suppress the resulting inlining actions.
9213
9214 Note regarding the use of @option{-O3}: There is no difference in inlining
9215 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9216 pragma @code{Inline} assuming the use of @option{-gnatn}
9217 or @option{-gnatN} (the switches that activate inlining). If you have used
9218 pragma @code{Inline} in appropriate cases, then it is usually much better
9219 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9220 in this case only has the effect of inlining subprograms you did not
9221 think should be inlined. We often find that the use of @option{-O3} slows
9222 down code by performing excessive inlining, leading to increased instruction
9223 cache pressure from the increased code size. So the bottom line here is
9224 that you should not automatically assume that @option{-O3} is better than
9225 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9226 it actually improves performance.
9227
9228 @node Optimization and Strict Aliasing
9229 @subsection Optimization and Strict Aliasing
9230 @cindex Aliasing
9231 @cindex Strict Aliasing
9232 @cindex No_Strict_Aliasing
9233
9234 @noindent
9235 The strong typing capabilities of Ada allow an optimizer to generate
9236 efficient code in situations where other languages would be forced to
9237 make worst case assumptions preventing such optimizations. Consider
9238 the following example:
9239
9240 @smallexample @c ada
9241 @cartouche
9242 procedure R is
9243    type Int1 is new Integer;
9244    type Int2 is new Integer;
9245    type Int1A is access Int1;
9246    type Int2A is access Int2;
9247    Int1V : Int1A;
9248    Int2V : Int2A;
9249    ...
9250
9251 begin
9252    ...
9253    for J in Data'Range loop
9254       if Data (J) = Int1V.all then
9255          Int2V.all := Int2V.all + 1;
9256       end if;
9257    end loop;
9258    ...
9259 end R;
9260 @end cartouche
9261 @end smallexample
9262
9263 @noindent
9264 In this example, since the variable @code{Int1V} can only access objects
9265 of type @code{Int1}, and @code{Int2V} can only access objects of type
9266 @code{Int2}, there is no possibility that the assignment to
9267 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9268 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9269 for all iterations of the loop and avoid the extra memory reference
9270 required to dereference it each time through the loop.
9271
9272 This kind of optimziation, called strict aliasing analysis, is
9273 triggered by specifying an optimization level of @option{-O2} or
9274 higher and allows @code{GNAT} to generate more efficient code
9275 when access values are involved.
9276
9277 However, although this optimization is always correct in terms of
9278 the formal semantics of the Ada Reference Manual, difficulties can
9279 arise if features like @code{Unchecked_Conversion} are used to break
9280 the typing system. Consider the following complete program example:
9281
9282 @smallexample @c ada
9283 @cartouche
9284 package p1 is
9285    type int1 is new integer;
9286    type int2 is new integer;
9287    type a1 is access int1;
9288    type a2 is access int2;
9289 end p1;
9290
9291 with p1; use p1;
9292 package p2 is
9293    function to_a2 (Input : a1) return a2;
9294 end p2;
9295
9296 with Unchecked_Conversion;
9297 package body p2 is
9298    function to_a2 (Input : a1) return a2 is
9299       function to_a2u is
9300         new Unchecked_Conversion (a1, a2);
9301    begin
9302       return to_a2u (Input);
9303    end to_a2;
9304 end p2;
9305
9306 with p2; use p2;
9307 with p1; use p1;
9308 with Text_IO; use Text_IO;
9309 procedure m is
9310    v1 : a1 := new int1;
9311    v2 : a2 := to_a2 (v1);
9312 begin
9313    v1.all := 1;
9314    v2.all := 0;
9315    put_line (int1'image (v1.all));
9316 end;
9317 @end cartouche
9318 @end smallexample
9319
9320 @noindent
9321 This program prints out 0 in @code{-O0} or @code{-O1}
9322 mode, but it prints out 1 in @code{-O2} mode. That's
9323 because in strict aliasing mode, the compiler can and
9324 does assume that the assignment to @code{v2.all} could not
9325 affect the value of @code{v1.all}, since different types
9326 are involved.
9327
9328 This behavior is not a case of non-conformance with the standard, since
9329 the Ada RM specifies that an unchecked conversion where the resulting
9330 bit pattern is not a correct value of the target type can result in an
9331 abnormal value and attempting to reference an abnormal value makes the
9332 execution of a program erroneous.  That's the case here since the result
9333 does not point to an object of type @code{int2}.  This means that the
9334 effect is entirely unpredictable.
9335
9336 However, although that explanation may satisfy a language
9337 lawyer, in practice an applications programmer expects an
9338 unchecked conversion involving pointers to create true
9339 aliases and the behavior of printing 1 seems plain wrong.
9340 In this case, the strict aliasing optimization is unwelcome.
9341
9342 Indeed the compiler recognizes this possibility, and the
9343 unchecked conversion generates a warning:
9344
9345 @smallexample
9346 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9347 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9348 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9349 @end smallexample
9350
9351 @noindent
9352 Unfortunately the problem is recognized when compiling the body of
9353 package @code{p2}, but the actual "bad" code is generated while
9354 compiling the body of @code{m} and this latter compilation does not see
9355 the suspicious @code{Unchecked_Conversion}.
9356
9357 As implied by the warning message, there are approaches you can use to
9358 avoid the unwanted strict aliasing optimization in a case like this.
9359
9360 One possibility is to simply avoid the use of @code{-O2}, but
9361 that is a bit drastic, since it throws away a number of useful
9362 optimizations that do not involve strict aliasing assumptions.
9363
9364 A less drastic approach is to compile the program using the
9365 option @code{-fno-strict-aliasing}. Actually it is only the
9366 unit containing the dereferencing of the suspicious pointer
9367 that needs to be compiled. So in this case, if we compile
9368 unit @code{m} with this switch, then we get the expected
9369 value of zero printed. Analyzing which units might need
9370 the switch can be painful, so a more reasonable approach
9371 is to compile the entire program with options @code{-O2}
9372 and @code{-fno-strict-aliasing}. If the performance is
9373 satisfactory with this combination of options, then the
9374 advantage is that the entire issue of possible "wrong"
9375 optimization due to strict aliasing is avoided.
9376
9377 To avoid the use of compiler switches, the configuration
9378 pragma @code{No_Strict_Aliasing} with no parameters may be
9379 used to specify that for all access types, the strict
9380 aliasing optimization should be suppressed.
9381
9382 However, these approaches are still overkill, in that they causes
9383 all manipulations of all access values to be deoptimized. A more
9384 refined approach is to concentrate attention on the specific
9385 access type identified as problematic.
9386
9387 First, if a careful analysis of uses of the pointer shows
9388 that there are no possible problematic references, then
9389 the warning can be suppressed by bracketing the
9390 instantiation of @code{Unchecked_Conversion} to turn
9391 the warning off:
9392
9393 @smallexample @c ada
9394    pragma Warnings (Off);
9395    function to_a2u is
9396      new Unchecked_Conversion (a1, a2);
9397    pragma Warnings (On);
9398 @end smallexample
9399
9400 @noindent
9401 Of course that approach is not appropriate for this particular
9402 example, since indeed there is a problematic reference. In this
9403 case we can take one of two other approaches.
9404
9405 The first possibility is to move the instantiation of unchecked
9406 conversion to the unit in which the type is declared. In
9407 this example, we would move the instantiation of
9408 @code{Unchecked_Conversion} from the body of package
9409 @code{p2} to the spec of package @code{p1}. Now the
9410 warning disappears. That's because any use of the
9411 access type knows there is a suspicious unchecked
9412 conversion, and the strict aliasing optimization
9413 is automatically suppressed for the type.
9414
9415 If it is not practical to move the unchecked conversion to the same unit
9416 in which the destination access type is declared (perhaps because the
9417 source type is not visible in that unit), you may use pragma
9418 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9419 same declarative sequence as the declaration of the access type:
9420
9421 @smallexample @c ada
9422    type a2 is access int2;
9423    pragma No_Strict_Aliasing (a2);
9424 @end smallexample
9425
9426 @noindent
9427 Here again, the compiler now knows that the strict aliasing optimization
9428 should be suppressed for any reference to type @code{a2} and the
9429 expected behavior is obtained.
9430
9431 Finally, note that although the compiler can generate warnings for
9432 simple cases of unchecked conversions, there are tricker and more
9433 indirect ways of creating type incorrect aliases which the compiler
9434 cannot detect. Examples are the use of address overlays and unchecked
9435 conversions involving composite types containing access types as
9436 components. In such cases, no warnings are generated, but there can
9437 still be aliasing problems. One safe coding practice is to forbid the
9438 use of address clauses for type overlaying, and to allow unchecked
9439 conversion only for primitive types. This is not really a significant
9440 restriction since any possible desired effect can be achieved by
9441 unchecked conversion of access values.
9442
9443 @ifset vms
9444 @node Coverage Analysis
9445 @subsection Coverage Analysis
9446
9447 @noindent
9448 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
9449 the user to determine the distribution of execution time across a program,
9450 @pxref{Profiling} for details of usage.
9451 @end ifset
9452
9453 @node Reducing the Size of Ada Executables with gnatelim
9454 @section Reducing the Size of Ada Executables with @code{gnatelim}
9455 @findex gnatelim
9456
9457 @noindent
9458 This section describes @command{gnatelim}, a tool which detects unused
9459 subprograms and helps the compiler to create a smaller executable for your
9460 program.
9461
9462 @menu
9463 * About gnatelim::
9464 * Running gnatelim::
9465 * Correcting the List of Eliminate Pragmas::
9466 * Making Your Executables Smaller::
9467 * Summary of the gnatelim Usage Cycle::
9468 @end menu
9469
9470 @node About gnatelim
9471 @subsection About @code{gnatelim}
9472
9473 @noindent
9474 When a program shares a set of Ada
9475 packages with other programs, it may happen that this program uses
9476 only a fraction of the subprograms defined in these packages. The code
9477 created for these unused subprograms increases the size of the executable.
9478
9479 @code{gnatelim} tracks unused subprograms in an Ada program and
9480 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9481 subprograms that are declared but never called. By placing the list of
9482 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9483 recompiling your program, you may decrease the size of its executable,
9484 because the compiler will not generate the code for 'eliminated' subprograms.
9485 See GNAT Reference Manual for more information about this pragma.
9486
9487 @code{gnatelim} needs as its input data the name of the main subprogram
9488 and a bind file for a main subprogram.
9489
9490 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9491 the main subprogram. @code{gnatelim} can work with both Ada and C
9492 bind files; when both are present, it uses the Ada bind file.
9493 The following commands will build the program and create the bind file:
9494
9495 @smallexample
9496 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9497 $ gnatbind main_prog
9498 @end smallexample
9499
9500 Note that @code{gnatelim} needs neither object nor ALI files.
9501
9502 @node Running gnatelim
9503 @subsection Running @code{gnatelim}
9504
9505 @noindent
9506 @code{gnatelim} has the following command-line interface:
9507
9508 @smallexample
9509 $ gnatelim [options] name
9510 @end smallexample
9511
9512 @noindent
9513 @code{name} should be a name of a source file that contains the main subprogram
9514 of a program (partition).
9515
9516 @code{gnatelim} has the following switches:
9517
9518 @table @option
9519 @c !sort!
9520 @item ^-q^/QUIET^
9521 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9522 Quiet mode: by default @code{gnatelim} outputs to the standard error
9523 stream the number of program units left to be processed. This option turns
9524 this trace off.
9525
9526 @item ^-v^/VERBOSE^
9527 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9528 Verbose mode: @code{gnatelim} version information is printed as Ada
9529 comments to the standard output stream. Also, in addition to the number of
9530 program units left @code{gnatelim} will output the name of the current unit
9531 being processed.
9532
9533 @item ^-a^/ALL^
9534 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9535 Also look for subprograms from the GNAT run time that can be eliminated. Note
9536 that when @file{gnat.adc} is produced using this switch, the entire program
9537 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
9538
9539 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9540 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9541 When looking for source files also look in directory @var{dir}. Specifying
9542 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9543 sources in the current directory.
9544
9545 @item ^-b^/BIND_FILE=^@var{bind_file}
9546 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9547 Specifies @var{bind_file} as the bind file to process. If not set, the name
9548 of the bind file is computed from the full expanded Ada name
9549 of a main subprogram.
9550
9551 @item ^-C^/CONFIG_FILE=^@var{config_file}
9552 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9553 Specifies a file @var{config_file} that contains configuration pragmas. The
9554 file must be specified with full path.
9555
9556 @item ^--GCC^/COMPILER^=@var{compiler_name}
9557 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9558 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
9559 available on the path.
9560
9561 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9562 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9563 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
9564 available on the path.
9565 @end table
9566
9567 @noindent
9568 @code{gnatelim} sends its output to the standard output stream, and all the
9569 tracing and debug information is sent to the standard error stream.
9570 In order to produce a proper GNAT configuration file
9571 @file{gnat.adc}, redirection must be used:
9572
9573 @smallexample
9574 @ifset vms
9575 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9576 @end ifset
9577 @ifclear vms
9578 $ gnatelim main_prog.adb > gnat.adc
9579 @end ifclear
9580 @end smallexample
9581
9582 @ifclear vms
9583 @noindent
9584 or
9585
9586 @smallexample
9587 $ gnatelim main_prog.adb >> gnat.adc
9588 @end smallexample
9589
9590 @noindent
9591 in order to append the @code{gnatelim} output to the existing contents of
9592 @file{gnat.adc}.
9593 @end ifclear
9594
9595 @node Correcting the List of Eliminate Pragmas
9596 @subsection Correcting the List of Eliminate Pragmas
9597
9598 @noindent
9599 In some rare cases @code{gnatelim} may try to eliminate
9600 subprograms that are actually called in the program. In this case, the
9601 compiler will generate an error message of the form:
9602
9603 @smallexample
9604 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9605 @end smallexample
9606
9607 @noindent
9608 You will need to manually remove the wrong @code{Eliminate} pragmas from
9609 the @file{gnat.adc} file. You should recompile your program
9610 from scratch after that, because you need a consistent @file{gnat.adc} file
9611 during the entire compilation.
9612
9613 @node Making Your Executables Smaller
9614 @subsection Making Your Executables Smaller
9615
9616 @noindent
9617 In order to get a smaller executable for your program you now have to
9618 recompile the program completely with the new @file{gnat.adc} file
9619 created by @code{gnatelim} in your current directory:
9620
9621 @smallexample
9622 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9623 @end smallexample
9624
9625 @noindent
9626 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9627 recompile everything
9628 with the set of pragmas @code{Eliminate} that you have obtained with
9629 @command{gnatelim}).
9630
9631 Be aware that the set of @code{Eliminate} pragmas is specific to each
9632 program. It is not recommended to merge sets of @code{Eliminate}
9633 pragmas created for different programs in one @file{gnat.adc} file.
9634
9635 @node Summary of the gnatelim Usage Cycle
9636 @subsection Summary of the gnatelim Usage Cycle
9637
9638 @noindent
9639 Here is a quick summary of the steps to be taken in order to reduce
9640 the size of your executables with @code{gnatelim}. You may use
9641 other GNAT options to control the optimization level,
9642 to produce the debugging information, to set search path, etc.
9643
9644 @enumerate
9645 @item
9646 Produce a bind file
9647
9648 @smallexample
9649 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9650 $ gnatbind main_prog
9651 @end smallexample
9652
9653 @item
9654 Generate a list of @code{Eliminate} pragmas
9655 @smallexample
9656 @ifset vms
9657 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9658 @end ifset
9659 @ifclear vms
9660 $ gnatelim main_prog >[>] gnat.adc
9661 @end ifclear
9662 @end smallexample
9663
9664 @item
9665 Recompile the application
9666
9667 @smallexample
9668 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9669 @end smallexample
9670
9671 @end enumerate
9672
9673 @c ********************************
9674 @node Renaming Files Using gnatchop
9675 @chapter Renaming Files Using @code{gnatchop}
9676 @findex gnatchop
9677
9678 @noindent
9679 This chapter discusses how to handle files with multiple units by using
9680 the @code{gnatchop} utility. This utility is also useful in renaming
9681 files to meet the standard GNAT default file naming conventions.
9682
9683 @menu
9684 * Handling Files with Multiple Units::
9685 * Operating gnatchop in Compilation Mode::
9686 * Command Line for gnatchop::
9687 * Switches for gnatchop::
9688 * Examples of gnatchop Usage::
9689 @end menu
9690
9691 @node Handling Files with Multiple Units
9692 @section Handling Files with Multiple Units
9693
9694 @noindent
9695 The basic compilation model of GNAT requires that a file submitted to the
9696 compiler have only one unit and there be a strict correspondence
9697 between the file name and the unit name.
9698
9699 The @code{gnatchop} utility allows both of these rules to be relaxed,
9700 allowing GNAT to process files which contain multiple compilation units
9701 and files with arbitrary file names. @code{gnatchop}
9702 reads the specified file and generates one or more output files,
9703 containing one unit per file. The unit and the file name correspond,
9704 as required by GNAT.
9705
9706 If you want to permanently restructure a set of ``foreign'' files so that
9707 they match the GNAT rules, and do the remaining development using the
9708 GNAT structure, you can simply use @command{gnatchop} once, generate the
9709 new set of files and work with them from that point on.
9710
9711 Alternatively, if you want to keep your files in the ``foreign'' format,
9712 perhaps to maintain compatibility with some other Ada compilation
9713 system, you can set up a procedure where you use @command{gnatchop} each
9714 time you compile, regarding the source files that it writes as temporary
9715 files that you throw away.
9716
9717 @node Operating gnatchop in Compilation Mode
9718 @section Operating gnatchop in Compilation Mode
9719
9720 @noindent
9721 The basic function of @code{gnatchop} is to take a file with multiple units
9722 and split it into separate files. The boundary between files is reasonably
9723 clear, except for the issue of comments and pragmas. In default mode, the
9724 rule is that any pragmas between units belong to the previous unit, except
9725 that configuration pragmas always belong to the following unit. Any comments
9726 belong to the following unit. These rules
9727 almost always result in the right choice of
9728 the split point without needing to mark it explicitly and most users will
9729 find this default to be what they want. In this default mode it is incorrect to
9730 submit a file containing only configuration pragmas, or one that ends in
9731 configuration pragmas, to @code{gnatchop}.
9732
9733 However, using a special option to activate ``compilation mode'',
9734 @code{gnatchop}
9735 can perform another function, which is to provide exactly the semantics
9736 required by the RM for handling of configuration pragmas in a compilation.
9737 In the absence of configuration pragmas (at the main file level), this
9738 option has no effect, but it causes such configuration pragmas to be handled
9739 in a quite different manner.
9740
9741 First, in compilation mode, if @code{gnatchop} is given a file that consists of
9742 only configuration pragmas, then this file is appended to the
9743 @file{gnat.adc} file in the current directory. This behavior provides
9744 the required behavior described in the RM for the actions to be taken
9745 on submitting such a file to the compiler, namely that these pragmas
9746 should apply to all subsequent compilations in the same compilation
9747 environment. Using GNAT, the current directory, possibly containing a
9748 @file{gnat.adc} file is the representation
9749 of a compilation environment. For more information on the
9750 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
9751
9752 Second, in compilation mode, if @code{gnatchop}
9753 is given a file that starts with
9754 configuration pragmas, and contains one or more units, then these
9755 configuration pragmas are prepended to each of the chopped files. This
9756 behavior provides the required behavior described in the RM for the
9757 actions to be taken on compiling such a file, namely that the pragmas
9758 apply to all units in the compilation, but not to subsequently compiled
9759 units.
9760
9761 Finally, if configuration pragmas appear between units, they are appended
9762 to the previous unit. This results in the previous unit being illegal,
9763 since the compiler does not accept configuration pragmas that follow
9764 a unit. This provides the required RM behavior that forbids configuration
9765 pragmas other than those preceding the first compilation unit of a
9766 compilation.
9767
9768 For most purposes, @code{gnatchop} will be used in default mode. The
9769 compilation mode described above is used only if you need exactly
9770 accurate behavior with respect to compilations, and you have files
9771 that contain multiple units and configuration pragmas. In this
9772 circumstance the use of @code{gnatchop} with the compilation mode
9773 switch provides the required behavior, and is for example the mode
9774 in which GNAT processes the ACVC tests.
9775
9776 @node Command Line for gnatchop
9777 @section Command Line for @code{gnatchop}
9778
9779 @noindent
9780 The @code{gnatchop} command has the form:
9781
9782 @smallexample
9783 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9784       [@var{directory}]
9785 @end smallexample
9786
9787 @noindent
9788 The only required argument is the file name of the file to be chopped.
9789 There are no restrictions on the form of this file name. The file itself
9790 contains one or more Ada units, in normal GNAT format, concatenated
9791 together. As shown, more than one file may be presented to be chopped.
9792
9793 When run in default mode, @code{gnatchop} generates one output file in
9794 the current directory for each unit in each of the files.
9795
9796 @var{directory}, if specified, gives the name of the directory to which
9797 the output files will be written. If it is not specified, all files are
9798 written to the current directory.
9799
9800 For example, given a
9801 file called @file{hellofiles} containing
9802
9803 @smallexample @c ada
9804 @group
9805 @cartouche
9806 procedure hello;
9807
9808 with Text_IO; use Text_IO;
9809 procedure hello is
9810 begin
9811    Put_Line ("Hello");
9812 end hello;
9813 @end cartouche
9814 @end group
9815 @end smallexample
9816
9817 @noindent
9818 the command
9819
9820 @smallexample
9821 $ gnatchop ^hellofiles^HELLOFILES.^
9822 @end smallexample
9823
9824 @noindent
9825 generates two files in the current directory, one called
9826 @file{hello.ads} containing the single line that is the procedure spec,
9827 and the other called @file{hello.adb} containing the remaining text. The
9828 original file is not affected. The generated files can be compiled in
9829 the normal manner.
9830
9831 @noindent
9832 When gnatchop is invoked on a file that is empty or that contains only empty
9833 lines and/or comments, gnatchop will not fail, but will not produce any
9834 new sources.
9835
9836 For example, given a
9837 file called @file{toto.txt} containing
9838
9839 @smallexample @c ada
9840 @group
9841 @cartouche
9842 --  Just a comment
9843 @end cartouche
9844 @end group
9845 @end smallexample
9846
9847 @noindent
9848 the command
9849
9850 @smallexample
9851 $ gnatchop ^toto.txt^TOT.TXT^
9852 @end smallexample
9853
9854 @noindent
9855 will not produce any new file and will result in the following warnings:
9856
9857 @smallexample
9858 toto.txt:1:01: warning: empty file, contains no compilation units
9859 no compilation units found
9860 no source files written
9861 @end smallexample
9862
9863 @node Switches for gnatchop
9864 @section Switches for @code{gnatchop}
9865
9866 @noindent
9867 @command{gnatchop} recognizes the following switches:
9868
9869 @table @option
9870 @c !sort!
9871
9872 @item ^-c^/COMPILATION^
9873 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
9874 Causes @code{gnatchop} to operate in compilation mode, in which
9875 configuration pragmas are handled according to strict RM rules. See
9876 previous section for a full description of this mode.
9877
9878 @ifclear vms
9879 @item -gnatxxx
9880 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
9881 used to parse the given file. Not all @code{xxx} options make sense,
9882 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
9883 process a source file that uses Latin-2 coding for identifiers.
9884 @end ifclear
9885
9886 @item ^-h^/HELP^
9887 Causes @code{gnatchop} to generate a brief help summary to the standard
9888 output file showing usage information.
9889
9890 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
9891 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
9892 Limit generated file names to the specified number @code{mm}
9893 of characters.
9894 This is useful if the
9895 resulting set of files is required to be interoperable with systems
9896 which limit the length of file names.
9897 @ifset vms
9898 If no value is given, or
9899 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
9900 a default of 39, suitable for OpenVMS Alpha
9901 Systems, is assumed
9902 @end ifset
9903 @ifclear vms
9904 No space is allowed between the @option{-k} and the numeric value. The numeric
9905 value may be omitted in which case a default of @option{-k8},
9906 suitable for use
9907 with DOS-like file systems, is used. If no @option{-k} switch
9908 is present then
9909 there is no limit on the length of file names.
9910 @end ifclear
9911
9912 @item ^-p^/PRESERVE^
9913 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
9914 Causes the file ^modification^creation^ time stamp of the input file to be
9915 preserved and used for the time stamp of the output file(s). This may be
9916 useful for preserving coherency of time stamps in an environment where
9917 @code{gnatchop} is used as part of a standard build process.
9918
9919 @item ^-q^/QUIET^
9920 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
9921 Causes output of informational messages indicating the set of generated
9922 files to be suppressed. Warnings and error messages are unaffected.
9923
9924 @item ^-r^/REFERENCE^
9925 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
9926 @findex Source_Reference
9927 Generate @code{Source_Reference} pragmas. Use this switch if the output
9928 files are regarded as temporary and development is to be done in terms
9929 of the original unchopped file. This switch causes
9930 @code{Source_Reference} pragmas to be inserted into each of the
9931 generated files to refers back to the original file name and line number.
9932 The result is that all error messages refer back to the original
9933 unchopped file.
9934 In addition, the debugging information placed into the object file (when
9935 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
9936 specified)
9937 also refers back to this original file so that tools like profilers and
9938 debuggers will give information in terms of the original unchopped file.
9939
9940 If the original file to be chopped itself contains
9941 a @code{Source_Reference}
9942 pragma referencing a third file, then gnatchop respects
9943 this pragma, and the generated @code{Source_Reference} pragmas
9944 in the chopped file refer to the original file, with appropriate
9945 line numbers. This is particularly useful when @code{gnatchop}
9946 is used in conjunction with @code{gnatprep} to compile files that
9947 contain preprocessing statements and multiple units.
9948
9949 @item ^-v^/VERBOSE^
9950 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
9951 Causes @code{gnatchop} to operate in verbose mode. The version
9952 number and copyright notice are output, as well as exact copies of
9953 the gnat1 commands spawned to obtain the chop control information.
9954
9955 @item ^-w^/OVERWRITE^
9956 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
9957 Overwrite existing file names. Normally @code{gnatchop} regards it as a
9958 fatal error if there is already a file with the same name as a
9959 file it would otherwise output, in other words if the files to be
9960 chopped contain duplicated units. This switch bypasses this
9961 check, and causes all but the last instance of such duplicated
9962 units to be skipped.
9963
9964 @ifclear vms
9965 @item --GCC=xxxx
9966 @cindex @option{--GCC=} (@code{gnatchop})
9967 Specify the path of the GNAT parser to be used. When this switch is used,
9968 no attempt is made to add the prefix to the GNAT parser executable.
9969 @end ifclear
9970 @end table
9971
9972 @node Examples of gnatchop Usage
9973 @section Examples of @code{gnatchop} Usage
9974
9975 @table @code
9976 @ifset vms
9977 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
9978 @end ifset
9979 @ifclear vms
9980 @item gnatchop -w hello_s.ada prerelease/files
9981 @end ifclear
9982
9983 Chops the source file @file{hello_s.ada}. The output files will be
9984 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
9985 overwriting any
9986 files with matching names in that directory (no files in the current
9987 directory are modified).
9988
9989 @item gnatchop ^archive^ARCHIVE.^
9990 Chops the source file @file{^archive^ARCHIVE.^}
9991 into the current directory. One
9992 useful application of @code{gnatchop} is in sending sets of sources
9993 around, for example in email messages. The required sources are simply
9994 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
9995 command), and then
9996 @code{gnatchop} is used at the other end to reconstitute the original
9997 file names.
9998
9999 @item gnatchop file1 file2 file3 direc
10000 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10001 the resulting files in the directory @file{direc}. Note that if any units
10002 occur more than once anywhere within this set of files, an error message
10003 is generated, and no files are written. To override this check, use the
10004 @option{^-w^/OVERWRITE^} switch,
10005 in which case the last occurrence in the last file will
10006 be the one that is output, and earlier duplicate occurrences for a given
10007 unit will be skipped.
10008 @end table
10009
10010 @node Configuration Pragmas
10011 @chapter Configuration Pragmas
10012 @cindex Configuration pragmas
10013 @cindex Pragmas, configuration
10014
10015 @noindent
10016 In Ada 95, configuration pragmas include those pragmas described as
10017 such in the Ada 95 Reference Manual, as well as
10018 implementation-dependent pragmas that are configuration pragmas. See the
10019 individual descriptions of pragmas in the GNAT Reference Manual for
10020 details on these additional GNAT-specific configuration pragmas. Most
10021 notably, the pragma @code{Source_File_Name}, which allows
10022 specifying non-default names for source files, is a configuration
10023 pragma. The following is a complete list of configuration pragmas
10024 recognized by @code{GNAT}:
10025
10026 @smallexample
10027    Ada_83
10028    Ada_95
10029    Ada_05
10030    C_Pass_By_Copy
10031    Component_Alignment
10032    Detect_Blocking
10033    Discard_Names
10034    Elaboration_Checks
10035    Eliminate
10036    Extend_System
10037    Extensions_Allowed
10038    External_Name_Casing
10039    Float_Representation
10040    Initialize_Scalars
10041    License
10042    Locking_Policy
10043    Long_Float
10044    Normalize_Scalars
10045    Polling
10046    Profile
10047    Profile_Warnings
10048    Propagate_Exceptions
10049    Queuing_Policy
10050    Ravenscar
10051    Restricted_Run_Time
10052    Restrictions
10053    Restrictions_Warnings
10054    Reviewable
10055    Source_File_Name
10056    Style_Checks
10057    Suppress
10058    Task_Dispatching_Policy
10059    Universal_Data
10060    Unsuppress
10061    Use_VADS_Size
10062    Warnings
10063    Validity_Checks
10064 @end smallexample
10065
10066 @menu
10067 * Handling of Configuration Pragmas::
10068 * The Configuration Pragmas Files::
10069 @end menu
10070
10071 @node Handling of Configuration Pragmas
10072 @section Handling of Configuration Pragmas
10073
10074 Configuration pragmas may either appear at the start of a compilation
10075 unit, in which case they apply only to that unit, or they may apply to
10076 all compilations performed in a given compilation environment.
10077
10078 GNAT also provides the @code{gnatchop} utility to provide an automatic
10079 way to handle configuration pragmas following the semantics for
10080 compilations (that is, files with multiple units), described in the RM.
10081 See @ref{Operating gnatchop in Compilation Mode} for details.
10082 However, for most purposes, it will be more convenient to edit the
10083 @file{gnat.adc} file that contains configuration pragmas directly,
10084 as described in the following section.
10085
10086 @node The Configuration Pragmas Files
10087 @section The Configuration Pragmas Files
10088 @cindex @file{gnat.adc}
10089
10090 @noindent
10091 In GNAT a compilation environment is defined by the current
10092 directory at the time that a compile command is given. This current
10093 directory is searched for a file whose name is @file{gnat.adc}. If
10094 this file is present, it is expected to contain one or more
10095 configuration pragmas that will be applied to the current compilation.
10096 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10097 considered.
10098
10099 Configuration pragmas may be entered into the @file{gnat.adc} file
10100 either by running @code{gnatchop} on a source file that consists only of
10101 configuration pragmas, or more conveniently  by
10102 direct editing of the @file{gnat.adc} file, which is a standard format
10103 source file.
10104
10105 In addition to @file{gnat.adc}, one additional file containing configuration
10106 pragmas may be applied to the current compilation using the switch
10107 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10108 contains only configuration pragmas. These configuration pragmas are
10109 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10110 is present and switch @option{-gnatA} is not used).
10111
10112 It is allowed to specify several switches @option{-gnatec}, however only
10113 the last one on the command line will be taken into account.
10114
10115 If you are using project file, a separate mechanism is provided using
10116 project attributes, see @ref{Specifying Configuration Pragmas} for more
10117 details.
10118
10119 @ifset vms
10120 Of special interest to GNAT OpenVMS Alpha is the following
10121 configuration pragma:
10122
10123 @smallexample @c ada
10124 @cartouche
10125 pragma Extend_System (Aux_DEC);
10126 @end cartouche
10127 @end smallexample
10128
10129 @noindent
10130 In the presence of this pragma, GNAT adds to the definition of the
10131 predefined package SYSTEM all the additional types and subprograms that are
10132 defined in DEC Ada. See @ref{Compatibility with DEC Ada} for details.
10133 @end ifset
10134
10135 @node Handling Arbitrary File Naming Conventions Using gnatname
10136 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10137 @cindex Arbitrary File Naming Conventions
10138
10139 @menu
10140 * Arbitrary File Naming Conventions::
10141 * Running gnatname::
10142 * Switches for gnatname::
10143 * Examples of gnatname Usage::
10144 @end menu
10145
10146 @node Arbitrary File Naming Conventions
10147 @section Arbitrary File Naming Conventions
10148
10149 @noindent
10150 The GNAT compiler must be able to know the source file name of a compilation
10151 unit.  When using the standard GNAT default file naming conventions
10152 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10153 does not need additional information.
10154
10155 @noindent
10156 When the source file names do not follow the standard GNAT default file naming
10157 conventions, the GNAT compiler must be given additional information through
10158 a configuration pragmas file (@pxref{Configuration Pragmas})
10159 or a project file.
10160 When the non standard file naming conventions are well-defined,
10161 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10162 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
10163 if the file naming conventions are irregular or arbitrary, a number
10164 of pragma @code{Source_File_Name} for individual compilation units
10165 must be defined.
10166 To help maintain the correspondence between compilation unit names and
10167 source file names within the compiler,
10168 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10169 set of files.
10170
10171 @node Running gnatname
10172 @section Running @code{gnatname}
10173
10174 @noindent
10175 The usual form of the @code{gnatname} command is
10176
10177 @smallexample
10178 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10179 @end smallexample
10180
10181 @noindent
10182 All of the arguments are optional. If invoked without any argument,
10183 @code{gnatname} will display its usage.
10184
10185 @noindent
10186 When used with at least one naming pattern, @code{gnatname} will attempt to
10187 find all the compilation units in files that follow at least one of the
10188 naming patterns. To find these compilation units,
10189 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10190 regular files.
10191
10192 @noindent
10193 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10194 Each Naming Pattern is enclosed between double quotes.
10195 A Naming Pattern is a regular expression similar to the wildcard patterns
10196 used in file names by the Unix shells or the DOS prompt.
10197
10198 @noindent
10199 Examples of Naming Patterns are
10200
10201 @smallexample
10202    "*.[12].ada"
10203    "*.ad[sb]*"
10204    "body_*"    "spec_*"
10205 @end smallexample
10206
10207 @noindent
10208 For a more complete description of the syntax of Naming Patterns,
10209 see the second kind of regular expressions described in @file{g-regexp.ads}
10210 (the ``Glob'' regular expressions).
10211
10212 @noindent
10213 When invoked with no switches, @code{gnatname} will create a configuration
10214 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10215 @code{Source_File_Name} for each file that contains a valid Ada unit.
10216
10217 @node Switches for gnatname
10218 @section Switches for @code{gnatname}
10219
10220 @noindent
10221 Switches for @code{gnatname} must precede any specified Naming Pattern.
10222
10223 @noindent
10224 You may specify any of the following switches to @code{gnatname}:
10225
10226 @table @option
10227 @c !sort!
10228
10229 @item ^-c^/CONFIG_FILE=^@file{file}
10230 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10231 Create a configuration pragmas file @file{file} (instead of the default
10232 @file{gnat.adc}).
10233 @ifclear vms
10234 There may be zero, one or more space between @option{-c} and
10235 @file{file}.
10236 @end ifclear
10237 @file{file} may include directory information. @file{file} must be
10238 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10239 When a switch @option{^-c^/CONFIG_FILE^} is
10240 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10241
10242 @item ^-d^/SOURCE_DIRS=^@file{dir}
10243 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10244 Look for source files in directory @file{dir}. There may be zero, one or more
10245 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10246 When a switch @option{^-d^/SOURCE_DIRS^}
10247 is specified, the current working directory will not be searched for source
10248 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10249 or @option{^-D^/DIR_FILES^} switch.
10250 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10251 If @file{dir} is a relative path, it is relative to the directory of
10252 the configuration pragmas file specified with switch
10253 @option{^-c^/CONFIG_FILE^},
10254 or to the directory of the project file specified with switch
10255 @option{^-P^/PROJECT_FILE^} or,
10256 if neither switch @option{^-c^/CONFIG_FILE^}
10257 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10258 current working directory. The directory
10259 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10260
10261 @item ^-D^/DIRS_FILE=^@file{file}
10262 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10263 Look for source files in all directories listed in text file @file{file}.
10264 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10265 and @file{file}.
10266 @file{file} must be an existing, readable text file.
10267 Each non empty line in @file{file} must be a directory.
10268 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10269 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10270 @file{file}.
10271
10272 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10273 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10274 Foreign patterns. Using this switch, it is possible to add sources of languages
10275 other than Ada to the list of sources of a project file.
10276 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10277 For example,
10278 @smallexample
10279 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10280 @end smallexample
10281 @noindent
10282 will look for Ada units in all files with the @file{.ada} extension,
10283 and will add to the list of file for project @file{prj.gpr} the C files
10284 with extension ".^c^C^".
10285
10286 @item ^-h^/HELP^
10287 @cindex @option{^-h^/HELP^} (@code{gnatname})
10288 Output usage (help) information. The output is written to @file{stdout}.
10289
10290 @item ^-P^/PROJECT_FILE=^@file{proj}
10291 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10292 Create or update project file @file{proj}. There may be zero, one or more space
10293 between @option{-P} and @file{proj}. @file{proj} may include directory
10294 information. @file{proj} must be writable.
10295 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10296 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10297 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10298
10299 @item ^-v^/VERBOSE^
10300 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10301 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10302 This includes name of the file written, the name of the directories to search
10303 and, for each file in those directories whose name matches at least one of
10304 the Naming Patterns, an indication of whether the file contains a unit,
10305 and if so the name of the unit.
10306
10307 @item ^-v -v^/VERBOSE /VERBOSE^
10308 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10309 Very Verbose mode. In addition to the output produced in verbose mode,
10310 for each file in the searched directories whose name matches none of
10311 the Naming Patterns, an indication is given that there is no match.
10312
10313 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10314 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10315 Excluded patterns. Using this switch, it is possible to exclude some files
10316 that would match the name patterns. For example,
10317 @smallexample
10318 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10319 @end smallexample
10320 @noindent
10321 will look for Ada units in all files with the @file{.ada} extension,
10322 except those whose names end with @file{_nt.ada}.
10323
10324 @end table
10325
10326 @node Examples of gnatname Usage
10327 @section Examples of @code{gnatname} Usage
10328
10329 @ifset vms
10330 @smallexample
10331 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10332 @end smallexample
10333 @end ifset
10334
10335 @ifclear vms
10336 @smallexample
10337 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10338 @end smallexample
10339 @end ifclear
10340
10341 @noindent
10342 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10343 and be writable. In addition, the directory
10344 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10345 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10346
10347 @ifclear vms
10348 Note the optional spaces after @option{-c} and @option{-d}.
10349 @end ifclear
10350
10351 @smallexample
10352 @ifclear vms
10353 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10354   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10355 @end ifclear
10356 @ifset vms
10357 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
10358   /EXCLUDED_PATTERN=*_nt_body.ada
10359   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10360   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10361 @end ifset
10362 @end smallexample
10363
10364 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10365 even in conjunction with one or several switches
10366 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10367 are used in this example.
10368
10369 @c *****************************************
10370 @c * G N A T  P r o j e c t  M a n a g e r *
10371 @c *****************************************
10372 @node GNAT Project Manager
10373 @chapter GNAT Project Manager
10374
10375 @menu
10376 * Introduction::
10377 * Examples of Project Files::
10378 * Project File Syntax::
10379 * Objects and Sources in Project Files::
10380 * Importing Projects::
10381 * Project Extension::
10382 * Project Hierarchy Extension::
10383 * External References in Project Files::
10384 * Packages in Project Files::
10385 * Variables from Imported Projects::
10386 * Naming Schemes::
10387 * Library Projects::
10388 * Stand-alone Library Projects::
10389 * Switches Related to Project Files::
10390 * Tools Supporting Project Files::
10391 * An Extended Example::
10392 * Project File Complete Syntax::
10393 @end menu
10394
10395 @c ****************
10396 @c * Introduction *
10397 @c ****************
10398
10399 @node Introduction
10400 @section Introduction
10401
10402 @noindent
10403 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10404 you to manage complex builds involving a number of source files, directories,
10405 and compilation options for different system configurations. In particular,
10406 project files allow you to specify:
10407 @itemize @bullet
10408 @item
10409 The directory or set of directories containing the source files, and/or the
10410 names of the specific source files themselves
10411 @item
10412 The directory in which the compiler's output
10413 (@file{ALI} files, object files, tree files) is to be placed
10414 @item
10415 The directory in which the executable programs is to be placed
10416 @item
10417 ^Switch^Switch^ settings for any of the project-enabled tools
10418 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10419 @code{gnatfind}); you can apply these settings either globally or to individual
10420 compilation units.
10421 @item
10422 The source files containing the main subprogram(s) to be built
10423 @item
10424 The source programming language(s) (currently Ada and/or C)
10425 @item
10426 Source file naming conventions; you can specify these either globally or for
10427 individual compilation units
10428 @end itemize
10429
10430 @menu
10431 * Project Files::
10432 @end menu
10433
10434 @node Project Files
10435 @subsection Project Files
10436
10437 @noindent
10438 Project files are written in a syntax close to that of Ada, using  familiar
10439 notions such as packages, context clauses, declarations, default values,
10440 assignments, and inheritance. Finally, project files can be built
10441 hierarchically from other project files, simplifying complex system
10442 integration and project reuse.
10443
10444 A @dfn{project} is a specific set of values for various compilation properties.
10445 The settings for a given project are described by means of
10446 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10447 Property values in project files are either strings or lists of strings.
10448 Properties that are not explicitly set receive default values.  A project
10449 file may interrogate the values of @dfn{external variables} (user-defined
10450 command-line switches or environment variables), and it may specify property
10451 settings conditionally, based on the value of such variables.
10452
10453 In simple cases, a project's source files depend only on other source files
10454 in the same project, or on the predefined libraries.  (@emph{Dependence} is
10455 used in
10456 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10457 the Project Manager also allows more sophisticated arrangements,
10458 where the source files in one project depend on source files in other
10459 projects:
10460 @itemize @bullet
10461 @item
10462 One project can @emph{import} other projects containing needed source files.
10463 @item
10464 You can organize GNAT projects in a hierarchy: a @emph{child} project
10465 can extend a @emph{parent} project, inheriting the parent's source files and
10466 optionally overriding any of them with alternative versions
10467 @end itemize
10468
10469 @noindent
10470 More generally, the Project Manager lets you structure large development
10471 efforts into hierarchical subsystems, where build decisions are delegated
10472 to the subsystem level, and thus different compilation environments
10473 (^switch^switch^ settings) used for different subsystems.
10474
10475 The Project Manager is invoked through the
10476 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10477 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10478 @ifclear vms
10479 There may be zero, one or more spaces between @option{-P} and
10480 @option{@emph{projectfile}}.
10481 @end ifclear
10482 If you want to define (on the command line) an external variable that is
10483 queried by the project file, you must use the
10484 @option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10485 The Project Manager parses and interprets the project file, and drives the
10486 invoked tool based on the project settings.
10487
10488 The Project Manager supports a wide range of development strategies,
10489 for systems of all sizes.  Here are some typical practices that are
10490 easily handled:
10491 @itemize @bullet
10492 @item
10493 Using a common set of source files, but generating object files in different
10494 directories via different ^switch^switch^ settings
10495 @item
10496 Using a mostly-shared set of source files, but with different versions of
10497 some unit or units
10498 @end itemize
10499
10500 @noindent
10501 The destination of an executable can be controlled inside a project file
10502 using the @option{^-o^-o^}
10503 ^switch^switch^.
10504 In the absence of such a ^switch^switch^ either inside
10505 the project file or on the command line, any executable files generated by
10506 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10507 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10508 in the object directory of the project.
10509
10510 You can use project files to achieve some of the effects of a source
10511 versioning system (for example, defining separate projects for
10512 the different sets of sources that comprise different releases) but the
10513 Project Manager is independent of any source configuration management tools
10514 that might be used by the developers.
10515
10516 The next section introduces the main features of GNAT's project facility
10517 through a sequence of examples; subsequent sections will present the syntax
10518 and semantics in more detail. A more formal description of the project
10519 facility appears in the GNAT Reference Manual.
10520
10521 @c *****************************
10522 @c * Examples of Project Files *
10523 @c *****************************
10524
10525 @node Examples of Project Files
10526 @section Examples of Project Files
10527 @noindent
10528 This section illustrates some of the typical uses of project files and
10529 explains their basic structure and behavior.
10530
10531 @menu
10532 * Common Sources with Different ^Switches^Switches^ and Directories::
10533 * Using External Variables::
10534 * Importing Other Projects::
10535 * Extending a Project::
10536 @end menu
10537
10538 @node Common Sources with Different ^Switches^Switches^ and Directories
10539 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10540
10541 @menu
10542 * Source Files::
10543 * Specifying the Object Directory::
10544 * Specifying the Exec Directory::
10545 * Project File Packages::
10546 * Specifying ^Switch^Switch^ Settings::
10547 * Main Subprograms::
10548 * Executable File Names::
10549 * Source File Naming Conventions::
10550 * Source Language(s)::
10551 @end menu
10552
10553 @noindent
10554 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10555 @file{proc.adb} are in the @file{/common} directory.  The file
10556 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10557 package @code{Pack}.  We want to compile these source files under two sets
10558 of ^switches^switches^:
10559 @itemize @bullet
10560 @item
10561 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10562 and the @option{^-gnata^-gnata^},
10563 @option{^-gnato^-gnato^},
10564 and @option{^-gnatE^-gnatE^} switches to the
10565 compiler; the compiler's output is to appear in @file{/common/debug}
10566 @item
10567 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10568 to the compiler; the compiler's output is to appear in @file{/common/release}
10569 @end itemize
10570
10571 @noindent
10572 The GNAT project files shown below, respectively @file{debug.gpr} and
10573 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10574
10575 Schematically:
10576 @smallexample
10577 @group
10578 ^/common^[COMMON]^
10579   debug.gpr
10580   release.gpr
10581   pack.ads
10582   pack.adb
10583   proc.adb
10584 @end group
10585 @group
10586 ^/common/debug^[COMMON.DEBUG]^
10587   proc.ali, proc.o
10588   pack.ali, pack.o
10589 @end group
10590 @group
10591 ^/common/release^[COMMON.RELEASE]^
10592   proc.ali, proc.o
10593   pack.ali, pack.o
10594 @end group
10595 @end smallexample
10596 Here are the corresponding project files:
10597
10598 @smallexample @c projectfile
10599 @group
10600 project Debug is
10601   for Object_Dir use "debug";
10602   for Main use ("proc");
10603
10604   package Builder is
10605     for ^Default_Switches^Default_Switches^ ("Ada")
10606         use ("^-g^-g^");
10607     for Executable ("proc.adb") use "proc1";
10608   end Builder;
10609 @end group
10610
10611 @group
10612   package Compiler is
10613     for ^Default_Switches^Default_Switches^ ("Ada")
10614        use ("-fstack-check",
10615             "^-gnata^-gnata^",
10616             "^-gnato^-gnato^",
10617             "^-gnatE^-gnatE^");
10618   end Compiler;
10619 end Debug;
10620 @end group
10621 @end smallexample
10622
10623 @smallexample @c projectfile
10624 @group
10625 project Release is
10626   for Object_Dir use "release";
10627   for Exec_Dir use ".";
10628   for Main use ("proc");
10629
10630   package Compiler is
10631     for ^Default_Switches^Default_Switches^ ("Ada")
10632         use ("^-O2^-O2^");
10633   end Compiler;
10634 end Release;
10635 @end group
10636 @end smallexample
10637
10638 @noindent
10639 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10640 insensitive), and analogously the project defined by @file{release.gpr} is
10641 @code{"Release"}.  For consistency the file should have the same name as the
10642 project, and the project file's extension should be @code{"gpr"}. These
10643 conventions are not required, but a warning is issued if they are not followed.
10644
10645 If the current directory is @file{^/temp^[TEMP]^}, then the command
10646 @smallexample
10647 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10648 @end smallexample
10649
10650 @noindent
10651 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10652 as well as the @code{^proc1^PROC1.EXE^} executable,
10653 using the ^switch^switch^ settings defined in the project file.
10654
10655 Likewise, the command
10656 @smallexample
10657 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10658 @end smallexample
10659
10660 @noindent
10661 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10662 and the @code{^proc^PROC.EXE^}
10663 executable in @file{^/common^[COMMON]^},
10664 using the ^switch^switch^ settings from the project file.
10665
10666 @node Source Files
10667 @unnumberedsubsubsec Source Files
10668
10669 @noindent
10670 If a project file does not explicitly specify a set of source directories or
10671 a set of source files, then by default the project's source files are the
10672 Ada source files in the project file directory.  Thus @file{pack.ads},
10673 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10674
10675 @node Specifying the Object Directory
10676 @unnumberedsubsubsec Specifying the Object Directory
10677
10678 @noindent
10679 Several project properties are modeled by Ada-style @emph{attributes};
10680 a property is defined by supplying the equivalent of an Ada attribute
10681 definition clause in the project file.
10682 A project's object directory is another such a property; the corresponding
10683 attribute is @code{Object_Dir}, and its value is also a string expression,
10684 specified either as absolute or relative. In the later case,
10685 it is relative to the project file directory. Thus the compiler's
10686 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10687 (for the @code{Debug} project)
10688 and to @file{^/common/release^[COMMON.RELEASE]^}
10689 (for the @code{Release} project).
10690 If @code{Object_Dir} is not specified, then the default is the project file
10691 directory itself.
10692
10693 @node Specifying the Exec Directory
10694 @unnumberedsubsubsec Specifying the Exec Directory
10695
10696 @noindent
10697 A project's exec directory is another property; the corresponding
10698 attribute is @code{Exec_Dir}, and its value is also a string expression,
10699 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10700 then the default is the object directory (which may also be the project file
10701 directory if attribute @code{Object_Dir} is not specified). Thus the executable
10702 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10703 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10704 and in @file{^/common^[COMMON]^} for the @code{Release} project.
10705
10706 @node Project File Packages
10707 @unnumberedsubsubsec Project File Packages
10708
10709 @noindent
10710 A GNAT tool that is integrated with the Project Manager is modeled by a
10711 corresponding package in the project file. In the example above,
10712 The @code{Debug} project defines the packages @code{Builder}
10713 (for @command{gnatmake}) and @code{Compiler};
10714 the @code{Release} project defines only the @code{Compiler} package.
10715
10716 The Ada-like package syntax is not to be taken literally.  Although packages in
10717 project files bear a surface resemblance to packages in Ada source code, the
10718 notation is simply a way to convey a grouping of properties for a named
10719 entity.  Indeed, the package names permitted in project files are restricted
10720 to a predefined set, corresponding to the project-aware tools, and the contents
10721 of packages are limited to a small set of constructs.
10722 The packages in the example above contain attribute definitions.
10723
10724 @node Specifying ^Switch^Switch^ Settings
10725 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10726
10727 @noindent
10728 ^Switch^Switch^ settings for a project-aware tool can be specified through
10729 attributes in the package that corresponds to the tool.
10730 The example above illustrates one of the relevant attributes,
10731 @code{^Default_Switches^Default_Switches^}, which is defined in packages
10732 in both project files.
10733 Unlike simple attributes like @code{Source_Dirs},
10734 @code{^Default_Switches^Default_Switches^} is
10735 known as an @emph{associative array}.  When you define this attribute, you must
10736 supply an ``index'' (a literal string), and the effect of the attribute
10737 definition is to set the value of the array at the specified index.
10738 For the @code{^Default_Switches^Default_Switches^} attribute,
10739 the index is a programming language (in our case, Ada),
10740 and the value specified (after @code{use}) must be a list
10741 of string expressions.
10742
10743 The attributes permitted in project files are restricted to a predefined set.
10744 Some may appear at project level, others in packages.
10745 For any attribute that is an associative array, the index must always be a
10746 literal string, but the restrictions on this string (e.g., a file name or a
10747 language name) depend on the individual attribute.
10748 Also depending on the attribute, its specified value will need to be either a
10749 string or a string list.
10750
10751 In the @code{Debug} project, we set the switches for two tools,
10752 @command{gnatmake} and the compiler, and thus we include the two corresponding
10753 packages; each package defines the @code{^Default_Switches^Default_Switches^}
10754 attribute with index @code{"Ada"}.
10755 Note that the package corresponding to
10756 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
10757 similar, but only includes the @code{Compiler} package.
10758
10759 In project @code{Debug} above, the ^switches^switches^ starting with
10760 @option{-gnat} that are specified in package @code{Compiler}
10761 could have been placed in package @code{Builder}, since @command{gnatmake}
10762 transmits all such ^switches^switches^ to the compiler.
10763
10764 @node Main Subprograms
10765 @unnumberedsubsubsec Main Subprograms
10766
10767 @noindent
10768 One of the specifiable properties of a project is a list of files that contain
10769 main subprograms.  This property is captured in the @code{Main} attribute,
10770 whose value is a list of strings.  If a project defines the @code{Main}
10771 attribute, it is not necessary to identify the main subprogram(s) when
10772 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
10773
10774 @node Executable File Names
10775 @unnumberedsubsubsec Executable File Names
10776
10777 @noindent
10778 By default, the executable file name corresponding to a main source is
10779 deduced from the main source file name. Through the attributes
10780 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10781 it is possible to change this default.
10782 In project @code{Debug} above, the executable file name
10783 for main source @file{^proc.adb^PROC.ADB^} is
10784 @file{^proc1^PROC1.EXE^}.
10785 Attribute @code{Executable_Suffix}, when specified, may change the suffix
10786 of the the executable files, when no attribute @code{Executable} applies:
10787 its value replace the platform-specific executable suffix.
10788 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10789 specify a non default executable file name when several mains are built at once
10790 in a single @command{gnatmake} command.
10791
10792 @node Source File Naming Conventions
10793 @unnumberedsubsubsec Source File Naming Conventions
10794
10795 @noindent
10796 Since the project files above do not specify any source file naming
10797 conventions, the GNAT defaults are used.  The mechanism for defining source
10798 file naming conventions -- a package named @code{Naming} --
10799 is described below (@pxref{Naming Schemes}).
10800
10801 @node Source Language(s)
10802 @unnumberedsubsubsec Source Language(s)
10803
10804 @noindent
10805 Since the project files do not specify a @code{Languages} attribute, by
10806 default the GNAT tools assume that the language of the project file is Ada.
10807 More generally, a project can comprise source files
10808 in Ada, C, and/or other languages.
10809
10810 @node Using External Variables
10811 @subsection Using External Variables
10812
10813 @noindent
10814 Instead of supplying different project files for debug and release, we can
10815 define a single project file that queries an external variable (set either
10816 on the command line or via an ^environment variable^logical name^) in order to
10817 conditionally define the appropriate settings.  Again, assume that the
10818 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
10819 located in directory @file{^/common^[COMMON]^}.  The following project file,
10820 @file{build.gpr}, queries the external variable named @code{STYLE} and
10821 defines an object directory and ^switch^switch^ settings based on whether
10822 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
10823 the default is @code{"deb"}.
10824
10825 @smallexample @c projectfile
10826 @group
10827 project Build is
10828   for Main use ("proc");
10829
10830   type Style_Type is ("deb", "rel");
10831   Style : Style_Type := external ("STYLE", "deb");
10832
10833   case Style is
10834     when "deb" =>
10835       for Object_Dir use "debug";
10836
10837     when "rel" =>
10838       for Object_Dir use "release";
10839       for Exec_Dir use ".";
10840   end case;
10841 @end group
10842
10843 @group
10844   package Builder is
10845
10846     case Style is
10847       when "deb" =>
10848         for ^Default_Switches^Default_Switches^ ("Ada")
10849             use ("^-g^-g^");
10850         for Executable ("proc") use "proc1";
10851       when others =>
10852         null;
10853     end case;
10854
10855   end Builder;
10856 @end group
10857
10858 @group
10859   package Compiler is
10860
10861     case Style is
10862       when "deb" =>
10863         for ^Default_Switches^Default_Switches^ ("Ada")
10864             use ("^-gnata^-gnata^",
10865                  "^-gnato^-gnato^",
10866                  "^-gnatE^-gnatE^");
10867
10868       when "rel" =>
10869         for ^Default_Switches^Default_Switches^ ("Ada")
10870             use ("^-O2^-O2^");
10871     end case;
10872
10873   end Compiler;
10874
10875 end Build;
10876 @end group
10877 @end smallexample
10878
10879 @noindent
10880 @code{Style_Type} is an example of a @emph{string type}, which is the project
10881 file analog of an Ada enumeration type but whose components are string literals
10882 rather than identifiers.  @code{Style} is declared as a variable of this type.
10883
10884 The form @code{external("STYLE", "deb")} is known as an
10885 @emph{external reference}; its first argument is the name of an
10886 @emph{external variable}, and the second argument is a default value to be
10887 used if the external variable doesn't exist.  You can define an external
10888 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
10889 or you can use ^an environment variable^a logical name^
10890 as an external variable.
10891
10892 Each @code{case} construct is expanded by the Project Manager based on the
10893 value of @code{Style}. Thus the command
10894 @ifclear vms
10895 @smallexample
10896 gnatmake -P/common/build.gpr -XSTYLE=deb
10897 @end smallexample
10898 @end ifclear
10899
10900 @ifset vms
10901 @smallexample
10902 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
10903 @end smallexample
10904 @end ifset
10905
10906 @noindent
10907 is equivalent to the @command{gnatmake} invocation using the project file
10908 @file{debug.gpr} in the earlier example.  So is the command
10909 @smallexample
10910 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
10911 @end smallexample
10912
10913 @noindent
10914 since @code{"deb"} is the default for @code{STYLE}.
10915
10916 Analogously,
10917
10918 @ifclear vms
10919 @smallexample
10920 gnatmake -P/common/build.gpr -XSTYLE=rel
10921 @end smallexample
10922 @end ifclear
10923
10924 @ifset vms
10925 @smallexample
10926 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
10927 @end smallexample
10928 @end ifset
10929
10930 @noindent
10931 is equivalent to the @command{gnatmake} invocation using the project file
10932 @file{release.gpr} in the earlier example.
10933
10934 @node Importing Other Projects
10935 @subsection Importing Other Projects
10936
10937 @noindent
10938 A compilation unit in a source file in one project may depend on compilation
10939 units in source files in other projects.  To compile this unit under
10940 control of a project file, the
10941 dependent project must @emph{import} the projects containing the needed source
10942 files.
10943 This effect is obtained using syntax similar to an Ada @code{with} clause,
10944 but where @code{with}ed entities are strings that denote project files.
10945
10946 As an example, suppose that the two projects @code{GUI_Proj} and
10947 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
10948 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
10949 and @file{^/comm^[COMM]^}, respectively.
10950 Suppose that the source files for @code{GUI_Proj} are
10951 @file{gui.ads} and @file{gui.adb}, and that the source files for
10952 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
10953 files is located in its respective project file directory.  Schematically:
10954
10955 @smallexample
10956 @group
10957 ^/gui^[GUI]^
10958   gui_proj.gpr
10959   gui.ads
10960   gui.adb
10961 @end group
10962
10963 @group
10964 ^/comm^[COMM]^
10965   comm_proj.gpr
10966   comm.ads
10967   comm.adb
10968 @end group
10969 @end smallexample
10970
10971 @noindent
10972 We want to develop an application in directory @file{^/app^[APP]^} that
10973 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
10974 the corresponding project files (e.g. the ^switch^switch^ settings
10975 and object directory).
10976 Skeletal code for a main procedure might be something like the following:
10977
10978 @smallexample @c ada
10979 @group
10980 with GUI, Comm;
10981 procedure App_Main is
10982    ...
10983 begin
10984    ...
10985 end App_Main;
10986 @end group
10987 @end smallexample
10988
10989 @noindent
10990 Here is a project file, @file{app_proj.gpr}, that achieves the desired
10991 effect:
10992
10993 @smallexample @c projectfile
10994 @group
10995 with "/gui/gui_proj", "/comm/comm_proj";
10996 project App_Proj is
10997    for Main use ("app_main");
10998 end App_Proj;
10999 @end group
11000 @end smallexample
11001
11002 @noindent
11003 Building an executable is achieved through the command:
11004 @smallexample
11005 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
11006 @end smallexample
11007 @noindent
11008 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
11009 in the directory where @file{app_proj.gpr} resides.
11010
11011 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
11012 (as illustrated above) the @code{with} clause can omit the extension.
11013
11014 Our example specified an absolute path for each imported project file.
11015 Alternatively, the directory name of an imported object can be omitted
11016 if either
11017 @itemize @bullet
11018 @item
11019 The imported project file is in the same directory as the importing project
11020 file, or
11021 @item
11022 You have defined ^an environment variable^a logical name^
11023 that includes the directory containing
11024 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
11025 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
11026 directory names separated by colons (semicolons on Windows).
11027 @end itemize
11028
11029 @noindent
11030 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
11031 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
11032 as follows:
11033
11034 @smallexample @c projectfile
11035 @group
11036 with "gui_proj", "comm_proj";
11037 project App_Proj is
11038    for Main use ("app_main");
11039 end App_Proj;
11040 @end group
11041 @end smallexample
11042
11043 @noindent
11044 Importing other projects can create ambiguities.
11045 For example, the same unit might be present in different imported projects, or
11046 it might be present in both the importing project and in an imported project.
11047 Both of these conditions are errors.  Note that in the current version of
11048 the Project Manager, it is illegal to have an ambiguous unit even if the
11049 unit is never referenced by the importing project.  This restriction may be
11050 relaxed in a future release.
11051
11052 @node Extending a Project
11053 @subsection Extending a Project
11054
11055 @noindent
11056 In large software systems it is common to have multiple
11057 implementations of a common interface; in Ada terms, multiple versions of a
11058 package body for the same specification.  For example, one implementation
11059 might be safe for use in tasking programs, while another might only be used
11060 in sequential applications.  This can be modeled in GNAT using the concept
11061 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
11062 another project (the ``parent'') then by default all source files of the
11063 parent project are inherited by the child, but the child project can
11064 override any of the parent's source files with new versions, and can also
11065 add new files.  This facility is the project analog of a type extension in
11066 Object-Oriented Programming.  Project hierarchies are permitted (a child
11067 project may be the parent of yet another project), and a project that
11068 inherits one project can also import other projects.
11069
11070 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11071 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11072 @file{pack.adb}, and @file{proc.adb}:
11073
11074 @smallexample
11075 @group
11076 ^/seq^[SEQ]^
11077   pack.ads
11078   pack.adb
11079   proc.adb
11080   seq_proj.gpr
11081 @end group
11082 @end smallexample
11083
11084 @noindent
11085 Note that the project file can simply be empty (that is, no attribute or
11086 package is defined):
11087
11088 @smallexample @c projectfile
11089 @group
11090 project Seq_Proj is
11091 end Seq_Proj;
11092 @end group
11093 @end smallexample
11094
11095 @noindent
11096 implying that its source files are all the Ada source files in the project
11097 directory.
11098
11099 Suppose we want to supply an alternate version of @file{pack.adb}, in
11100 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11101 @file{pack.ads} and @file{proc.adb}.  We can define a project
11102 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11103
11104 @smallexample
11105 @group
11106 ^/tasking^[TASKING]^
11107   pack.adb
11108   tasking_proj.gpr
11109 @end group
11110
11111 @group
11112 project Tasking_Proj extends "/seq/seq_proj" is
11113 end Tasking_Proj;
11114 @end group
11115 @end smallexample
11116
11117 @noindent
11118 The version of @file{pack.adb} used in a build depends on which project file
11119 is specified.
11120
11121 Note that we could have obtained the desired behavior using project import
11122 rather than project inheritance; a @code{base} project would contain the
11123 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11124 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11125 would import @code{base} and add a different version of @file{pack.adb}.  The
11126 choice depends on whether other sources in the original project need to be
11127 overridden.  If they do, then project extension is necessary, otherwise,
11128 importing is sufficient.
11129
11130 @noindent
11131 In a project file that extends another project file, it is possible to
11132 indicate that an inherited source is not part of the sources of the extending
11133 project. This is necessary sometimes when a package spec has been overloaded
11134 and no longer requires a body: in this case, it is necessary to indicate that
11135 the inherited body is not part of the sources of the project, otherwise there
11136 will be a compilation error when compiling the spec.
11137
11138 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11139 Its value is a string list: a list of file names.
11140
11141 @smallexample @c @projectfile
11142 project B extends "a" is
11143    for Source_Files use ("pkg.ads");
11144    --  New spec of Pkg does not need a completion
11145    for Locally_Removed_Files use ("pkg.adb");
11146 end B;
11147 @end smallexample
11148
11149 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11150 is still needed: if it is possible to build using @command{gnatmake} when such
11151 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11152 it is possible to remove the source completely from a system that includes
11153 project P.
11154
11155 @c ***********************
11156 @c * Project File Syntax *
11157 @c ***********************
11158
11159 @node Project File Syntax
11160 @section Project File Syntax
11161
11162 @menu
11163 * Basic Syntax::
11164 * Packages::
11165 * Expressions::
11166 * String Types::
11167 * Variables::
11168 * Attributes::
11169 * Associative Array Attributes::
11170 * case Constructions::
11171 @end menu
11172
11173 @noindent
11174 This section describes the structure of project files.
11175
11176 A project may be an @emph{independent project}, entirely defined by a single
11177 project file. Any Ada source file in an independent project depends only
11178 on the predefined library and other Ada source files in the same project.
11179
11180 @noindent
11181 A project may also @dfn{depend on} other projects, in either or both of
11182 the following ways:
11183 @itemize @bullet
11184 @item It may import any number of projects
11185 @item It may extend at most one other project
11186 @end itemize
11187
11188 @noindent
11189 The dependence relation is a directed acyclic graph (the subgraph reflecting
11190 the ``extends'' relation is a tree).
11191
11192 A project's @dfn{immediate sources} are the source files directly defined by
11193 that project, either implicitly by residing in the project file's directory,
11194 or explicitly through any of the source-related attributes described below.
11195 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11196 of @var{proj} together with the immediate sources (unless overridden) of any
11197 project on which @var{proj} depends (either directly or indirectly).
11198
11199 @node Basic Syntax
11200 @subsection Basic Syntax
11201
11202 @noindent
11203 As seen in the earlier examples, project files have an Ada-like syntax.
11204 The minimal project file is:
11205 @smallexample @c projectfile
11206 @group
11207 project Empty is
11208
11209 end Empty;
11210 @end group
11211 @end smallexample
11212
11213 @noindent
11214 The identifier @code{Empty} is the name of the project.
11215 This project name must be present after the reserved
11216 word @code{end} at the end of the project file, followed by a semi-colon.
11217
11218 Any name in a project file, such as the project name or a variable name,
11219 has the same syntax as an Ada identifier.
11220
11221 The reserved words of project files are the Ada reserved words plus
11222 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11223 reserved words currently used in project file syntax are:
11224
11225 @itemize @bullet
11226 @item
11227 @code{case}
11228 @item
11229 @code{end}
11230 @item
11231 @code{for}
11232 @item
11233 @code{is}
11234 @item
11235 @code{others}
11236 @item
11237 @code{package}
11238 @item
11239 @code{renames}
11240 @item
11241 @code{type}
11242 @item
11243 @code{use}
11244 @item
11245 @code{when}
11246 @item
11247 @code{with}
11248 @end itemize
11249
11250 @noindent
11251 Comments in project files have the same syntax as in Ada, two consecutives
11252 hyphens through the end of the line.
11253
11254 @node Packages
11255 @subsection Packages
11256
11257 @noindent
11258 A project file may contain @emph{packages}. The name of a package must be one
11259 of the identifiers from the following list. A package
11260 with a given name may only appear once in a project file. Package names are
11261 case insensitive. The following package names are legal:
11262
11263 @itemize @bullet
11264 @item
11265 @code{Naming}
11266 @item
11267 @code{Builder}
11268 @item
11269 @code{Compiler}
11270 @item
11271 @code{Binder}
11272 @item
11273 @code{Linker}
11274 @item
11275 @code{Finder}
11276 @item
11277 @code{Cross_Reference}
11278 @item
11279 @code{Eliminate}
11280 @item
11281 @code{Pretty_Printer}
11282 @item
11283 @code{Metrics}
11284 @item
11285 @code{gnatls}
11286 @item
11287 @code{gnatstub}
11288 @item
11289 @code{IDE}
11290 @item
11291 @code{Language_Processing}
11292 @end itemize
11293
11294 @noindent
11295 In its simplest form, a package may be empty:
11296
11297 @smallexample @c projectfile
11298 @group
11299 project Simple is
11300   package Builder is
11301   end Builder;
11302 end Simple;
11303 @end group
11304 @end smallexample
11305
11306 @noindent
11307 A package may contain @emph{attribute declarations},
11308 @emph{variable declarations} and @emph{case constructions}, as will be
11309 described below.
11310
11311 When there is ambiguity between a project name and a package name,
11312 the name always designates the project. To avoid possible confusion, it is
11313 always a good idea to avoid naming a project with one of the
11314 names allowed for packages or any name that starts with @code{gnat}.
11315
11316 @node Expressions
11317 @subsection Expressions
11318
11319 @noindent
11320 An @emph{expression} is either a @emph{string expression} or a
11321 @emph{string list expression}.
11322
11323 A @emph{string expression} is either a @emph{simple string expression} or a
11324 @emph{compound string expression}.
11325
11326 A @emph{simple string expression} is one of the following:
11327 @itemize @bullet
11328 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11329 @item A string-valued variable reference (@pxref{Variables})
11330 @item A string-valued attribute reference (@pxref{Attributes})
11331 @item An external reference (@pxref{External References in Project Files})
11332 @end itemize
11333
11334 @noindent
11335 A @emph{compound string expression} is a concatenation of string expressions,
11336 using the operator @code{"&"}
11337 @smallexample
11338        Path & "/" & File_Name & ".ads"
11339 @end smallexample
11340
11341 @noindent
11342 A @emph{string list expression} is either a
11343 @emph{simple string list expression} or a
11344 @emph{compound string list expression}.
11345
11346 A @emph{simple string list expression} is one of the following:
11347 @itemize @bullet
11348 @item A parenthesized list of zero or more string expressions,
11349 separated by commas
11350 @smallexample
11351    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11352    Empty_List := ();
11353 @end smallexample
11354 @item A string list-valued variable reference
11355 @item A string list-valued attribute reference
11356 @end itemize
11357
11358 @noindent
11359 A @emph{compound string list expression} is the concatenation (using
11360 @code{"&"}) of a simple string list expression and an expression.  Note that
11361 each term in a compound string list expression, except the first, may be
11362 either a string expression or a string list expression.
11363
11364 @smallexample @c projectfile
11365 @group
11366    File_Name_List := () & File_Name; --  One string in this list
11367    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11368    --  Two strings
11369    Big_List := File_Name_List & Extended_File_Name_List;
11370    --  Concatenation of two string lists: three strings
11371    Illegal_List := "gnat.adc" & Extended_File_Name_List;
11372    --  Illegal: must start with a string list
11373 @end group
11374 @end smallexample
11375
11376 @node String Types
11377 @subsection String Types
11378
11379 @noindent
11380 A @emph{string type declaration} introduces a discrete set of string literals.
11381 If a string variable is declared to have this type, its value
11382 is restricted to the given set of literals.
11383
11384 Here is an example of a string type declaration:
11385
11386 @smallexample @c projectfile
11387    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11388 @end smallexample
11389
11390 @noindent
11391 Variables of a string type are called @emph{typed variables}; all other
11392 variables are called @emph{untyped variables}. Typed variables are
11393 particularly useful in @code{case} constructions, to support conditional
11394 attribute declarations.
11395 (@pxref{case Constructions}).
11396
11397 The string literals in the list are case sensitive and must all be different.
11398 They may include any graphic characters allowed in Ada, including spaces.
11399
11400 A string type may only be declared at the project level, not inside a package.
11401
11402 A string type may be referenced by its name if it has been declared in the same
11403 project file, or by an expanded name whose prefix is the name of the project
11404 in which it is declared.
11405
11406 @node Variables
11407 @subsection Variables
11408
11409 @noindent
11410 A variable may be declared at the project file level, or within a package.
11411 Here are some examples of variable declarations:
11412
11413 @smallexample @c projectfile
11414 @group
11415    This_OS : OS := external ("OS"); --  a typed variable declaration
11416    That_OS := "GNU/Linux";          --  an untyped variable declaration
11417 @end group
11418 @end smallexample
11419
11420 @noindent
11421 The syntax of a @emph{typed variable declaration} is identical to the Ada
11422 syntax for an object declaration. By contrast, the syntax of an untyped
11423 variable declaration is identical to an Ada assignment statement. In fact,
11424 variable declarations in project files have some of the characteristics of
11425 an assignment, in that successive declarations for the same variable are
11426 allowed. Untyped variable declarations do establish the expected kind of the
11427 variable (string or string list), and successive declarations for it must
11428 respect the initial kind.
11429
11430 @noindent
11431 A string variable declaration (typed or untyped) declares a variable
11432 whose value is a string. This variable may be used as a string expression.
11433 @smallexample @c projectfile
11434    File_Name       := "readme.txt";
11435    Saved_File_Name := File_Name & ".saved";
11436 @end smallexample
11437
11438 @noindent
11439 A string list variable declaration declares a variable whose value is a list
11440 of strings. The list may contain any number (zero or more) of strings.
11441
11442 @smallexample @c projectfile
11443    Empty_List := ();
11444    List_With_One_Element := ("^-gnaty^-gnaty^");
11445    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11446    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11447                  "pack2.ada", "util_.ada", "util.ada");
11448 @end smallexample
11449
11450 @noindent
11451 The same typed variable may not be declared more than once at project level,
11452 and it may not be declared more than once in any package; it is in effect
11453 a constant.
11454
11455 The same untyped variable may be declared several times. Declarations are
11456 elaborated in the order in which they appear, so  the new value replaces
11457 the old one, and any subsequent reference to the variable uses the new value.
11458 However, as noted above, if a variable has been declared as a string, all
11459 subsequent
11460 declarations must give it a string value. Similarly, if a variable has
11461 been declared as a string list, all subsequent declarations
11462 must give it a string list value.
11463
11464 A @emph{variable reference} may take several forms:
11465
11466 @itemize @bullet
11467 @item The simple variable name, for a variable in the current package (if any)
11468 or in the current project
11469 @item An expanded name, whose prefix is a context name.
11470 @end itemize
11471
11472 @noindent
11473 A @emph{context} may be one of the following:
11474
11475 @itemize @bullet
11476 @item The name of an existing package in the current project
11477 @item The name of an imported project of the current project
11478 @item The name of an ancestor project (i.e., a project extended by the current
11479 project, either directly or indirectly)
11480 @item An expanded name whose prefix is an imported/parent project name, and
11481 whose selector is a package name in that project.
11482 @end itemize
11483
11484 @noindent
11485 A variable reference may be used in an expression.
11486
11487 @node Attributes
11488 @subsection Attributes
11489
11490 @noindent
11491 A project (and its packages) may have @emph{attributes} that define
11492 the project's properties.  Some attributes have values that are strings;
11493 others have values that are string lists.
11494
11495 There are two categories of attributes: @emph{simple attributes}
11496 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
11497
11498 Legal project attribute names, and attribute names for each legal package are
11499 listed below. Attributes names are case-insensitive.
11500
11501 The following attributes are defined on projects (all are simple attributes):
11502
11503 @multitable @columnfractions .4 .3
11504 @item @emph{Attribute Name}
11505 @tab @emph{Value}
11506 @item @code{Source_Files}
11507 @tab string list
11508 @item @code{Source_Dirs}
11509 @tab string list
11510 @item @code{Source_List_File}
11511 @tab string
11512 @item @code{Object_Dir}
11513 @tab string
11514 @item @code{Exec_Dir}
11515 @tab string
11516 @item @code{Locally_Removed_Files}
11517 @tab string list
11518 @item @code{Main}
11519 @tab string list
11520 @item @code{Languages}
11521 @tab string list
11522 @item @code{Main_Language}
11523 @tab string
11524 @item @code{Library_Dir}
11525 @tab string
11526 @item @code{Library_Name}
11527 @tab string
11528 @item @code{Library_Kind}
11529 @tab string
11530 @item @code{Library_Version}
11531 @tab string
11532 @item @code{Library_Interface}
11533 @tab string
11534 @item @code{Library_Auto_Init}
11535 @tab string
11536 @item @code{Library_Options}
11537 @tab string list
11538 @item @code{Library_GCC}
11539 @tab string
11540 @end multitable
11541
11542 @noindent
11543 The following attributes are defined for package  @code{Naming}
11544 (@pxref{Naming Schemes}):
11545
11546 @multitable @columnfractions .4 .2 .2 .2
11547 @item Attribute Name @tab Category @tab Index @tab Value
11548 @item @code{Spec_Suffix}
11549 @tab associative array
11550 @tab language name
11551 @tab string
11552 @item @code{Body_Suffix}
11553 @tab associative array
11554 @tab language name
11555 @tab string
11556 @item @code{Separate_Suffix}
11557 @tab simple attribute
11558 @tab n/a
11559 @tab string
11560 @item @code{Casing}
11561 @tab simple attribute
11562 @tab n/a
11563 @tab string
11564 @item @code{Dot_Replacement}
11565 @tab simple attribute
11566 @tab n/a
11567 @tab string
11568 @item @code{Spec}
11569 @tab associative array
11570 @tab Ada unit name
11571 @tab string
11572 @item @code{Body}
11573 @tab associative array
11574 @tab Ada unit name
11575 @tab string
11576 @item @code{Specification_Exceptions}
11577 @tab associative array
11578 @tab language name
11579 @tab string list
11580 @item @code{Implementation_Exceptions}
11581 @tab associative array
11582 @tab language name
11583 @tab string list
11584 @end multitable
11585
11586 @noindent
11587 The following attributes are defined for packages @code{Builder},
11588 @code{Compiler}, @code{Binder},
11589 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
11590 (@pxref{^Switches^Switches^ and Project Files}).
11591
11592 @multitable @columnfractions .4 .2 .2 .2
11593 @item Attribute Name @tab Category @tab Index @tab Value
11594 @item @code{^Default_Switches^Default_Switches^}
11595 @tab associative array
11596 @tab language name
11597 @tab string list
11598 @item @code{^Switches^Switches^}
11599 @tab associative array
11600 @tab file name
11601 @tab string list
11602 @end multitable
11603
11604 @noindent
11605 In addition, package @code{Compiler} has a single string attribute
11606 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11607 string attribute @code{Global_Configuration_Pragmas}.
11608
11609 @noindent
11610 Each simple attribute has a default value: the empty string (for string-valued
11611 attributes) and the empty list (for string list-valued attributes).
11612
11613 An attribute declaration defines a new value for an attribute.
11614
11615 Examples of simple attribute declarations:
11616
11617 @smallexample @c projectfile
11618    for Object_Dir use "objects";
11619    for Source_Dirs use ("units", "test/drivers");
11620 @end smallexample
11621
11622 @noindent
11623 The syntax of a @dfn{simple attribute declaration} is similar to that of an
11624 attribute definition clause in Ada.
11625
11626 Attributes references may be appear in expressions.
11627 The general form for such a reference is @code{<entity>'<attribute>}:
11628 Associative array attributes are functions. Associative
11629 array attribute references must have an argument that is a string literal.
11630
11631 Examples are:
11632
11633 @smallexample @c projectfile
11634   project'Object_Dir
11635   Naming'Dot_Replacement
11636   Imported_Project'Source_Dirs
11637   Imported_Project.Naming'Casing
11638   Builder'^Default_Switches^Default_Switches^("Ada")
11639 @end smallexample
11640
11641 @noindent
11642 The prefix of an attribute may be:
11643 @itemize @bullet
11644 @item @code{project} for an attribute of the current project
11645 @item The name of an existing package of the current project
11646 @item The name of an imported project
11647 @item The name of a parent project that is extended by the current project
11648 @item An expanded name whose prefix is imported/parent project name,
11649       and whose selector is a package name
11650 @end itemize
11651
11652 @noindent
11653 Example:
11654 @smallexample @c projectfile
11655 @group
11656    project Prj is
11657      for Source_Dirs use project'Source_Dirs & "units";
11658      for Source_Dirs use project'Source_Dirs & "test/drivers"
11659    end Prj;
11660 @end group
11661 @end smallexample
11662
11663 @noindent
11664 In the first attribute declaration, initially the attribute @code{Source_Dirs}
11665 has the default value: an empty string list. After this declaration,
11666 @code{Source_Dirs} is a string list of one element: @code{"units"}.
11667 After the second attribute declaration @code{Source_Dirs} is a string list of
11668 two elements: @code{"units"} and @code{"test/drivers"}.
11669
11670 Note: this example is for illustration only. In practice,
11671 the project file would contain only one attribute declaration:
11672
11673 @smallexample @c projectfile
11674    for Source_Dirs use ("units", "test/drivers");
11675 @end smallexample
11676
11677 @node Associative Array Attributes
11678 @subsection Associative Array Attributes
11679
11680 @noindent
11681 Some attributes are defined as @emph{associative arrays}. An associative
11682 array may be regarded as a function that takes a string as a parameter
11683 and delivers a string or string list value as its result.
11684
11685 Here are some examples of single associative array attribute associations:
11686
11687 @smallexample @c projectfile
11688    for Body ("main") use "Main.ada";
11689    for ^Switches^Switches^ ("main.ada")
11690        use ("^-v^-v^",
11691             "^-gnatv^-gnatv^");
11692    for ^Switches^Switches^ ("main.ada")
11693             use Builder'^Switches^Switches^ ("main.ada")
11694               & "^-g^-g^";
11695 @end smallexample
11696
11697 @noindent
11698 Like untyped variables and simple attributes, associative array attributes
11699 may be declared several times. Each declaration supplies a new value for the
11700 attribute, and replaces the previous setting.
11701
11702 @noindent
11703 An associative array attribute may be declared as a full associative array
11704 declaration, with the value of the same attribute in an imported or extended
11705 project.
11706
11707 @smallexample @c projectfile
11708    package Builder is
11709       for Default_Switches use Default.Builder'Default_Switches;
11710    end Builder;
11711 @end smallexample
11712
11713 @noindent
11714 In this example, @code{Default} must be either an project imported by the
11715 current project, or the project that the current project extends. If the
11716 attribute is in a package (in this case, in package @code{Builder}), the same
11717 package needs to be specified.
11718
11719 @noindent
11720 A full associative array declaration replaces any other declaration for the
11721 attribute, including other full associative array declaration. Single
11722 associative array associations may be declare after a full associative
11723 declaration, modifying the value for a single association of the attribute.
11724
11725 @node case Constructions
11726 @subsection @code{case} Constructions
11727
11728 @noindent
11729 A @code{case} construction is used in a project file to effect conditional
11730 behavior.
11731 Here is a typical example:
11732
11733 @smallexample @c projectfile
11734 @group
11735 project MyProj is
11736    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11737
11738    OS : OS_Type := external ("OS", "GNU/Linux");
11739 @end group
11740
11741 @group
11742    package Compiler is
11743      case OS is
11744        when "GNU/Linux" | "Unix" =>
11745          for ^Default_Switches^Default_Switches^ ("Ada")
11746              use ("^-gnath^-gnath^");
11747        when "NT" =>
11748          for ^Default_Switches^Default_Switches^ ("Ada")
11749              use ("^-gnatP^-gnatP^");
11750        when others =>
11751      end case;
11752    end Compiler;
11753 end MyProj;
11754 @end group
11755 @end smallexample
11756
11757 @noindent
11758 The syntax of a @code{case} construction is based on the Ada case statement
11759 (although there is no @code{null} construction for empty alternatives).
11760
11761 The case expression must a typed string variable.
11762 Each alternative comprises the reserved word @code{when}, either a list of
11763 literal strings separated by the @code{"|"} character or the reserved word
11764 @code{others},  and the @code{"=>"} token.
11765 Each literal string must belong to the string type that is the type of the
11766 case variable.
11767 An @code{others} alternative, if present, must occur last.
11768
11769 After each @code{=>}, there are zero or more constructions.  The only
11770 constructions allowed in a case construction are other case constructions and
11771 attribute declarations. String type declarations, variable declarations and
11772 package declarations are not allowed.
11773
11774 The value of the case variable is often given by an external reference
11775 (@pxref{External References in Project Files}).
11776
11777 @c ****************************************
11778 @c * Objects and Sources in Project Files *
11779 @c ****************************************
11780
11781 @node Objects and Sources in Project Files
11782 @section Objects and Sources in Project Files
11783
11784 @menu
11785 * Object Directory::
11786 * Exec Directory::
11787 * Source Directories::
11788 * Source File Names::
11789 @end menu
11790
11791 @noindent
11792 Each project has exactly one object directory and one or more source
11793 directories. The source directories must contain at least one source file,
11794 unless  the project file explicitly specifies that no source files are present
11795 (@pxref{Source File Names}).
11796
11797 @node Object Directory
11798 @subsection Object Directory
11799
11800 @noindent
11801 The object directory for a project is the directory containing the compiler's
11802 output (such as @file{ALI} files and object files) for the project's immediate
11803 sources.
11804
11805 The object directory is given by the value of the attribute @code{Object_Dir}
11806 in the project file.
11807
11808 @smallexample @c projectfile
11809    for Object_Dir use "objects";
11810 @end smallexample
11811
11812 @noindent
11813 The attribute @var{Object_Dir} has a string value, the path name of the object
11814 directory. The path name may be absolute or relative to the directory of the
11815 project file. This directory must already exist, and be readable and writable.
11816
11817 By default, when the attribute @code{Object_Dir} is not given an explicit value
11818 or when its value is the empty string, the object directory is the same as the
11819 directory containing the project file.
11820
11821 @node Exec Directory
11822 @subsection Exec Directory
11823
11824 @noindent
11825 The exec directory for a project is the directory containing the executables
11826 for the project's main subprograms.
11827
11828 The exec directory is given by the value of the attribute @code{Exec_Dir}
11829 in the project file.
11830
11831 @smallexample @c projectfile
11832    for Exec_Dir use "executables";
11833 @end smallexample
11834
11835 @noindent
11836 The attribute @var{Exec_Dir} has a string value, the path name of the exec
11837 directory. The path name may be absolute or relative to the directory of the
11838 project file. This directory must already exist, and be writable.
11839
11840 By default, when the attribute @code{Exec_Dir} is not given an explicit value
11841 or when its value is the empty string, the exec directory is the same as the
11842 object directory of the project file.
11843
11844 @node Source Directories
11845 @subsection Source Directories
11846
11847 @noindent
11848 The source directories of a project are specified by the project file
11849 attribute @code{Source_Dirs}.
11850
11851 This attribute's value is a string list. If the attribute is not given an
11852 explicit value, then there is only one source directory, the one where the
11853 project file resides.
11854
11855 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
11856 as in
11857
11858 @smallexample @c projectfile
11859     for Source_Dirs use ();
11860 @end smallexample
11861
11862 @noindent
11863 indicates that the project contains no source files.
11864
11865 Otherwise, each string in the string list designates one or more
11866 source directories.
11867
11868 @smallexample @c projectfile
11869    for Source_Dirs use ("sources", "test/drivers");
11870 @end smallexample
11871
11872 @noindent
11873 If a string in the list ends with @code{"/**"},  then the directory whose path
11874 name precedes the two asterisks, as well as all its subdirectories
11875 (recursively), are source directories.
11876
11877 @smallexample @c projectfile
11878    for Source_Dirs use ("/system/sources/**");
11879 @end smallexample
11880
11881 @noindent
11882 Here the directory @code{/system/sources} and all of its subdirectories
11883 (recursively) are source directories.
11884
11885 To specify that the source directories are the directory of the project file
11886 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
11887 @smallexample @c projectfile
11888    for Source_Dirs use ("./**");
11889 @end smallexample
11890
11891 @noindent
11892 Each of the source directories must exist and be readable.
11893
11894 @node Source File Names
11895 @subsection Source File Names
11896
11897 @noindent
11898 In a project that contains source files, their names may be specified by the
11899 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
11900 (a string). Source file names never include any directory information.
11901
11902 If the attribute @code{Source_Files} is given an explicit value, then each
11903 element of the list is a source file name.
11904
11905 @smallexample @c projectfile
11906    for Source_Files use ("main.adb");
11907    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
11908 @end smallexample
11909
11910 @noindent
11911 If the attribute @code{Source_Files} is not given an explicit value,
11912 but the attribute @code{Source_List_File} is given a string value,
11913 then the source file names are contained in the text file whose path name
11914 (absolute or relative to the directory of the project file) is the
11915 value of the attribute @code{Source_List_File}.
11916
11917 Each line in the file that is not empty or is not a comment
11918 contains a source file name.
11919
11920 @smallexample @c projectfile
11921    for Source_List_File use "source_list.txt";
11922 @end smallexample
11923
11924 @noindent
11925 By default, if neither the attribute @code{Source_Files} nor the attribute
11926 @code{Source_List_File} is given an explicit value, then each file in the
11927 source directories that conforms to the project's naming scheme
11928 (@pxref{Naming Schemes}) is an immediate source of the project.
11929
11930 A warning is issued if both attributes @code{Source_Files} and
11931 @code{Source_List_File} are given explicit values. In this case, the attribute
11932 @code{Source_Files} prevails.
11933
11934 Each source file name must be the name of one existing source file
11935 in one of the source directories.
11936
11937 A @code{Source_Files} attribute whose value is an empty list
11938 indicates that there are no source files in the project.
11939
11940 If the order of the source directories is known statically, that is if
11941 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
11942 be several files with the same source file name. In this case, only the file
11943 in the first directory is considered as an immediate source of the project
11944 file. If the order of the source directories is not known statically, it is
11945 an error to have several files with the same source file name.
11946
11947 Projects can be specified to have no Ada source
11948 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
11949 list, or the @code{"Ada"} may be absent from @code{Languages}:
11950
11951 @smallexample @c projectfile
11952    for Source_Dirs use ();
11953    for Source_Files use ();
11954    for Languages use ("C", "C++");
11955 @end smallexample
11956
11957 @noindent
11958 Otherwise, a project must contain at least one immediate source.
11959
11960 Projects with no source files are useful as template packages
11961 (@pxref{Packages in Project Files}) for other projects; in particular to
11962 define a package @code{Naming} (@pxref{Naming Schemes}).
11963
11964 @c ****************************
11965 @c * Importing Projects *
11966 @c ****************************
11967
11968 @node  Importing Projects
11969 @section Importing Projects
11970
11971 @noindent
11972 An immediate source of a project P may depend on source files that
11973 are neither immediate sources of P nor in the predefined library.
11974 To get this effect, P must @emph{import} the projects that contain the needed
11975 source files.
11976
11977 @smallexample @c projectfile
11978 @group
11979   with "project1", "utilities.gpr";
11980   with "/namings/apex.gpr";
11981   project Main is
11982     ...
11983 @end group
11984 @end smallexample
11985
11986 @noindent
11987 As can be seen in this example, the syntax for importing projects is similar
11988 to the syntax for importing compilation units in Ada. However, project files
11989 use literal strings instead of names, and the @code{with} clause identifies
11990 project files rather than packages.
11991
11992 Each literal string is the file name or path name (absolute or relative) of a
11993 project file. If a string is simply a file name, with no path, then its
11994 location is determined by the @emph{project path}:
11995
11996 @itemize @bullet
11997 @item
11998 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} exists,
11999 then the project path includes all the directories in this
12000 ^environment variable^logical name^, plus the directory of the project file.
12001
12002 @item
12003 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} does not
12004 exist, then the project path contains only one directory, namely the one where
12005 the project file is located.
12006 @end itemize
12007
12008 @noindent
12009 If a relative pathname is used, as in
12010
12011 @smallexample @c projectfile
12012   with "tests/proj";
12013 @end smallexample
12014
12015 @noindent
12016 then the path is relative to the directory where the importing project file is
12017 located. Any symbolic link will be fully resolved in the directory
12018 of the importing project file before the imported project file is examined.
12019
12020 If the @code{with}'ed project file name does not have an extension,
12021 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
12022 then the file name as specified in the @code{with} clause (no extension) will
12023 be used. In the above example, if a file @code{project1.gpr} is found, then it
12024 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
12025 then it will be used; if neither file exists, this is an error.
12026
12027 A warning is issued if the name of the project file does not match the
12028 name of the project; this check is case insensitive.
12029
12030 Any source file that is an immediate source of the imported project can be
12031 used by the immediate sources of the importing project, transitively. Thus
12032 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
12033 sources of @code{A} may depend on the immediate sources of @code{C}, even if
12034 @code{A} does not import @code{C} explicitly. However, this is not recommended,
12035 because if and when @code{B} ceases to import @code{C}, some sources in
12036 @code{A} will no longer compile.
12037
12038 A side effect of this capability is that normally cyclic dependencies are not
12039 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
12040 is not allowed to import @code{A}. However, there are cases when cyclic
12041 dependencies would be beneficial. For these cases, another form of import
12042 between projects exists, the @code{limited with}: a project @code{A} that
12043 imports a project @code{B} with a straigh @code{with} may also be imported,
12044 directly or indirectly, by @code{B} on the condition that imports from @code{B}
12045 to @code{A} include at least one @code{limited with}.
12046
12047 @smallexample @c 0projectfile
12048 with "../b/b.gpr";
12049 with "../c/c.gpr";
12050 project A is
12051 end A;
12052
12053 limited with "../a/a.gpr";
12054 project B is
12055 end B;
12056
12057 with "../d/d.gpr";
12058 project C is
12059 end C;
12060
12061 limited with "../a/a.gpr";
12062 project D is
12063 end D;
12064 @end smallexample
12065
12066 @noindent
12067 In the above legal example, there are two project cycles:
12068 @itemize @bullet
12069 @item A-> B-> A
12070 @item A -> C -> D -> A
12071 @end itemize
12072
12073 @noindent
12074 In each of these cycle there is one @code{limited with}: import of @code{A}
12075 from @code{B} and import of @code{A} from @code{D}.
12076
12077 The difference between straight @code{with} and @code{limited with} is that
12078 the name of a project imported with a @code{limited with} cannot be used in the
12079 project that imports it. In particular, its packages cannot be renamed and
12080 its variables cannot be referred to.
12081
12082 An exception to the above rules for @code{limited with} is that for the main
12083 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12084 @code{limited with} is equivalent to a straight @code{with}. For example,
12085 in the example above, projects @code{B} and @code{D} could not be main
12086 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12087 each have a @code{limited with} that is the only one in a cycle of importing
12088 projects.
12089
12090 @c *********************
12091 @c * Project Extension *
12092 @c *********************
12093
12094 @node Project Extension
12095 @section Project Extension
12096
12097 @noindent
12098 During development of a large system, it is sometimes necessary to use
12099 modified versions of some of the source files, without changing the original
12100 sources. This can be achieved through the @emph{project extension} facility.
12101
12102 @smallexample @c projectfile
12103    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12104 @end smallexample
12105
12106 @noindent
12107 A project extension declaration introduces an extending project
12108 (the @emph{child}) and a project being extended (the @emph{parent}).
12109
12110 By default, a child project inherits all the sources of its parent.
12111 However, inherited sources can be overridden: a unit in a parent is hidden
12112 by a unit of the same name in the child.
12113
12114 Inherited sources are considered to be sources (but not immediate sources)
12115 of the child project; see @ref{Project File Syntax}.
12116
12117 An inherited source file retains any switches specified in the parent project.
12118
12119 For example if the project @code{Utilities} contains the specification and the
12120 body of an Ada package @code{Util_IO}, then the project
12121 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12122 The original body of @code{Util_IO} will not be considered in program builds.
12123 However, the package specification will still be found in the project
12124 @code{Utilities}.
12125
12126 A child project can have only one parent but it may import any number of other
12127 projects.
12128
12129 A project is not allowed to import directly or indirectly at the same time a
12130 child project and any of its ancestors.
12131
12132 @c *******************************
12133 @c * Project Hierarchy Extension *
12134 @c *******************************
12135
12136 @node Project Hierarchy Extension
12137 @section Project Hierarchy Extension
12138
12139 @noindent
12140 When extending a large system spanning multiple projects, it is often
12141 inconvenient to extend every project in the hierarchy that is impacted by a
12142 small change introduced. In such cases, it is possible to create a virtual
12143 extension of entire hierarchy using @code{extends all} relationship.
12144
12145 When the project is extended using @code{extends all} inheritance, all projects
12146 that are imported by it, both directly and indirectly, are considered virtually
12147 extended. That is, the Project Manager creates "virtual projects"
12148 that extend every project in the hierarchy; all these virtual projects have
12149 no sources of their own and have as object directory the object directory of
12150 the root of "extending all" project.
12151
12152 It is possible to explicitly extend one or more projects in the hierarchy
12153 in order to modify the sources. These extending projects must be imported by
12154 the "extending all" project, which will replace the corresponding virtual
12155 projects with the explicit ones.
12156
12157 When building such a project hierarchy extension, the Project Manager will
12158 ensure that both modified sources and sources in virtual extending projects
12159 that depend on them, are recompiled.
12160
12161 By means of example, consider the following hierarchy of projects.
12162
12163 @enumerate
12164 @item
12165 project A, containing package P1
12166 @item
12167 project B importing A and containing package P2 which depends on P1
12168 @item
12169 project C importing B and containing package P3 which depends on P2
12170 @end enumerate
12171
12172 @noindent
12173 We want to modify packages P1 and P3.
12174
12175 This project hierarchy will need to be extended as follows:
12176
12177 @enumerate
12178 @item
12179 Create project A1 that extends A, placing modified P1 there:
12180
12181 @smallexample @c 0projectfile
12182 project A1 extends "(...)/A" is
12183 end A1;
12184 @end smallexample
12185
12186 @item
12187 Create project C1 that "extends all" C and imports A1, placing modified
12188 P3 there:
12189
12190 @smallexample @c 0projectfile
12191 with "(...)/A1";
12192 project C1 extends all "(...)/C" is
12193 end C1;
12194 @end smallexample
12195 @end enumerate
12196
12197 When you build project C1, your entire modified project space will be
12198 recompiled, including the virtual project B1 that has been impacted by the
12199 "extending all" inheritance of project C.
12200
12201 Note that if a Library Project in the hierarchy is virtually extended,
12202 the virtual project that extends the Library Project is not a Library Project.
12203
12204 @c ****************************************
12205 @c * External References in Project Files *
12206 @c ****************************************
12207
12208 @node  External References in Project Files
12209 @section External References in Project Files
12210
12211 @noindent
12212 A project file may contain references to external variables; such references
12213 are called @emph{external references}.
12214
12215 An external variable is either defined as part of the environment (an
12216 environment variable in Unix, for example) or else specified on the command
12217 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12218 If both, then the command line value is used.
12219
12220 The value of an external reference is obtained by means of the built-in
12221 function @code{external}, which returns a string value.
12222 This function has two forms:
12223 @itemize @bullet
12224 @item @code{external (external_variable_name)}
12225 @item @code{external (external_variable_name, default_value)}
12226 @end itemize
12227
12228 @noindent
12229 Each parameter must be a string literal.  For example:
12230
12231 @smallexample @c projectfile
12232    external ("USER")
12233    external ("OS", "GNU/Linux")
12234 @end smallexample
12235
12236 @noindent
12237 In the form with one parameter, the function returns the value of
12238 the external variable given as parameter. If this name is not present in the
12239 environment, the function returns an empty string.
12240
12241 In the form with two string parameters, the second argument is
12242 the value returned when the variable given as the first argument is not
12243 present in the environment. In the example above, if @code{"OS"} is not
12244 the name of ^an environment variable^a logical name^ and is not passed on
12245 the command line, then the returned value is @code{"GNU/Linux"}.
12246
12247 An external reference may be part of a string expression or of a string
12248 list expression, and can therefore appear in a variable declaration or
12249 an attribute declaration.
12250
12251 @smallexample @c projectfile
12252 @group
12253    type Mode_Type is ("Debug", "Release");
12254    Mode : Mode_Type := external ("MODE");
12255    case Mode is
12256      when "Debug" =>
12257         ...
12258 @end group
12259 @end smallexample
12260
12261 @c *****************************
12262 @c * Packages in Project Files *
12263 @c *****************************
12264
12265 @node  Packages in Project Files
12266 @section Packages in Project Files
12267
12268 @noindent
12269 A @emph{package} defines the settings for project-aware tools within a
12270 project.
12271 For each such tool one can declare a package; the names for these
12272 packages are preset (@pxref{Packages}).
12273 A package may contain variable declarations, attribute declarations, and case
12274 constructions.
12275
12276 @smallexample @c projectfile
12277 @group
12278    project Proj is
12279       package Builder is  -- used by gnatmake
12280          for ^Default_Switches^Default_Switches^ ("Ada")
12281              use ("^-v^-v^",
12282                   "^-g^-g^");
12283       end Builder;
12284    end Proj;
12285 @end group
12286 @end smallexample
12287
12288 @noindent
12289 The syntax of package declarations mimics that of package in Ada.
12290
12291 Most of the packages have an attribute
12292 @code{^Default_Switches^Default_Switches^}.
12293 This attribute is an associative array, and its value is a string list.
12294 The index of the associative array is the name of a programming language (case
12295 insensitive). This attribute indicates the ^switch^switch^
12296 or ^switches^switches^ to be used
12297 with the corresponding tool.
12298
12299 Some packages also have another attribute, @code{^Switches^Switches^},
12300 an associative array whose value is a string list.
12301 The index is the name of a source file.
12302 This attribute indicates the ^switch^switch^
12303 or ^switches^switches^ to be used by the corresponding
12304 tool when dealing with this specific file.
12305
12306 Further information on these ^switch^switch^-related attributes is found in
12307 @ref{^Switches^Switches^ and Project Files}.
12308
12309 A package may be declared as a @emph{renaming} of another package; e.g., from
12310 the project file for an imported project.
12311
12312 @smallexample @c projectfile
12313 @group
12314   with "/global/apex.gpr";
12315   project Example is
12316     package Naming renames Apex.Naming;
12317     ...
12318   end Example;
12319 @end group
12320 @end smallexample
12321
12322 @noindent
12323 Packages that are renamed in other project files often come from project files
12324 that have no sources: they are just used as templates. Any modification in the
12325 template will be reflected automatically in all the project files that rename
12326 a package from the template.
12327
12328 In addition to the tool-oriented packages, you can also declare a package
12329 named @code{Naming} to establish specialized source file naming conventions
12330 (@pxref{Naming Schemes}).
12331
12332 @c ************************************
12333 @c * Variables from Imported Projects *
12334 @c ************************************
12335
12336 @node Variables from Imported Projects
12337 @section Variables from Imported Projects
12338
12339 @noindent
12340 An attribute or variable defined in an imported or parent project can
12341 be used in expressions in the importing / extending project.
12342 Such an attribute or variable is denoted by an expanded name whose prefix
12343 is either the name of the project or the expanded name of a package within
12344 a project.
12345
12346 @smallexample @c projectfile
12347 @group
12348   with "imported";
12349   project Main extends "base" is
12350      Var1 := Imported.Var;
12351      Var2 := Base.Var & ".new";
12352 @end group
12353
12354 @group
12355      package Builder is
12356         for ^Default_Switches^Default_Switches^ ("Ada")
12357             use Imported.Builder.Ada_^Switches^Switches^ &
12358                 "^-gnatg^-gnatg^" &
12359                 "^-v^-v^";
12360      end Builder;
12361 @end group
12362
12363 @group
12364      package Compiler is
12365         for ^Default_Switches^Default_Switches^ ("Ada")
12366             use Base.Compiler.Ada_^Switches^Switches^;
12367      end Compiler;
12368   end Main;
12369 @end group
12370 @end smallexample
12371
12372 @noindent
12373 In this example:
12374
12375 @itemize @bullet
12376 @item
12377 The value of @code{Var1} is a copy of the variable @code{Var} defined
12378 in the project file @file{"imported.gpr"}
12379 @item
12380 the value of @code{Var2} is a copy of the value of variable @code{Var}
12381 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12382 @item
12383 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12384 @code{Builder} is a string list that includes in its value a copy of the value
12385 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12386 in project file @file{imported.gpr} plus two new elements:
12387 @option{"^-gnatg^-gnatg^"}
12388 and @option{"^-v^-v^"};
12389 @item
12390 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12391 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12392 defined in the @code{Compiler} package in project file @file{base.gpr},
12393 the project being extended.
12394 @end itemize
12395
12396 @c ******************
12397 @c * Naming Schemes *
12398 @c ******************
12399
12400 @node  Naming Schemes
12401 @section Naming Schemes
12402
12403 @noindent
12404 Sometimes an Ada software system is ported from a foreign compilation
12405 environment to GNAT, and the file names do not use the default GNAT
12406 conventions. Instead of changing all the file names (which for a variety
12407 of reasons might not be possible), you can define the relevant file
12408 naming scheme in the @code{Naming} package in your project file.
12409
12410 @noindent
12411 Note that the use of pragmas described in
12412 @ref{Alternative File Naming Schemes} by mean of a configuration
12413 pragmas file is not supported when using project files. You must use
12414 the features described in this paragraph. You can however use specify
12415 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
12416
12417 @ifclear vms
12418 For example, the following
12419 package models the Apex file naming rules:
12420
12421 @smallexample @c projectfile
12422 @group
12423   package Naming is
12424     for Casing               use "lowercase";
12425     for Dot_Replacement      use ".";
12426     for Spec_Suffix ("Ada")  use ".1.ada";
12427     for Body_Suffix ("Ada")  use ".2.ada";
12428   end Naming;
12429 @end group
12430 @end smallexample
12431 @end ifclear
12432
12433 @ifset vms
12434 For example, the following package models the DEC Ada file naming rules:
12435
12436 @smallexample @c projectfile
12437 @group
12438   package Naming is
12439     for Casing               use "lowercase";
12440     for Dot_Replacement      use "__";
12441     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12442     for Body_Suffix ("Ada")  use ".^ada^ada^";
12443   end Naming;
12444 @end group
12445 @end smallexample
12446
12447 @noindent
12448 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12449 names in lower case)
12450 @end ifset
12451
12452 @noindent
12453 You can define the following attributes in package @code{Naming}:
12454
12455 @table @code
12456
12457 @item @var{Casing}
12458 This must be a string with one of the three values @code{"lowercase"},
12459 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12460
12461 @noindent
12462 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12463
12464 @item @var{Dot_Replacement}
12465 This must be a string whose value satisfies the following conditions:
12466
12467 @itemize @bullet
12468 @item It must not be empty
12469 @item It cannot start or end with an alphanumeric character
12470 @item It cannot be a single underscore
12471 @item It cannot start with an underscore followed by an alphanumeric
12472 @item It cannot contain a dot @code{'.'} except if the entire string
12473 is @code{"."}
12474 @end itemize
12475
12476 @noindent
12477 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12478
12479 @item @var{Spec_Suffix}
12480 This is an associative array (indexed by the programming language name, case
12481 insensitive) whose value is a string that must satisfy the following
12482 conditions:
12483
12484 @itemize @bullet
12485 @item It must not be empty
12486 @item It must include at least one dot
12487 @end itemize
12488 @noindent
12489 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12490 @code{"^.ads^.ADS^"}.
12491
12492 @item @var{Body_Suffix}
12493 This is an associative array (indexed by the programming language name, case
12494 insensitive) whose value is a string that must satisfy the following
12495 conditions:
12496
12497 @itemize @bullet
12498 @item It must not be empty
12499 @item It must include at least one dot
12500 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12501 @end itemize
12502 @noindent
12503 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12504 @code{"^.adb^.ADB^"}.
12505
12506 @item @var{Separate_Suffix}
12507 This must be a string whose value satisfies the same conditions as
12508 @code{Body_Suffix}.
12509
12510 @noindent
12511 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12512 value as @code{Body_Suffix ("Ada")}.
12513
12514 @item @var{Spec}
12515 @noindent
12516 You can use the associative array attribute @code{Spec}  to define
12517 the source file name for an individual Ada compilation unit's spec. The array
12518 index must be a string literal that identifies the Ada unit (case insensitive).
12519 The value of this attribute must be a string that identifies the file that
12520 contains this unit's spec (case sensitive or insensitive depending on the
12521 operating system).
12522
12523 @smallexample @c projectfile
12524    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12525 @end smallexample
12526
12527 @item @var{Body}
12528
12529 You can use the associative array attribute @code{Body} to
12530 define the source file name for an individual Ada compilation unit's body
12531 (possibly a subunit).  The array index must be a string literal that identifies
12532 the Ada unit (case insensitive).  The value of this attribute must be a string
12533 that identifies the file that contains this unit's body or subunit (case
12534 sensitive or insensitive depending on the operating system).
12535
12536 @smallexample @c projectfile
12537    for Body ("MyPack.MyChild") use "mypack.mychild.body";
12538 @end smallexample
12539 @end table
12540
12541 @c ********************
12542 @c * Library Projects *
12543 @c ********************
12544
12545 @node Library Projects
12546 @section Library Projects
12547
12548 @noindent
12549 @emph{Library projects} are projects whose object code is placed in a library.
12550 (Note that this facility is not yet supported on all platforms)
12551
12552 To create a library project, you need to define in its project file
12553 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12554 Additionally, you may define the library-related attributes
12555 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12556 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12557
12558 The @code{Library_Name} attribute has a string value. There is no restriction
12559 on the name of a library. It is the responsability of the developer to
12560 choose a name that will be accepted by the platform. It is recommanded to
12561 choose names that could be Ada identifiers; such names are almost guaranteed
12562 to be acceptable on all platforms.
12563
12564 The @code{Library_Dir} attribute has a string value that designates the path
12565 (absolute or relative) of the directory where the library will reside.
12566 It must designate an existing directory, and this directory must be
12567 different from the project's object directory. It also needs to be writable.
12568 The directory should only be used for one library; the reason is that all
12569 files contained in this directory may be deleted by the Project Manager.
12570
12571 If both @code{Library_Name} and @code{Library_Dir} are specified and
12572 are legal, then the project file defines a library project.  The optional
12573 library-related attributes are checked only for such project files.
12574
12575 The @code{Library_Kind} attribute has a string value that must be one of the
12576 following (case insensitive): @code{"static"}, @code{"dynamic"} or
12577 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
12578 attribute is not specified, the library is a static library, that is
12579 an archive of object files that can be potentially linked into an
12580 static executable. Otherwise, the library may be dynamic or
12581 relocatable, that is a library that is loaded only at the start of execution.
12582
12583 If you need to build both a static and a dynamic library, you should use two
12584 different object directories, since in some cases some extra code needs to
12585 be generated for the latter. For such cases, it is recommended to either use
12586 two different project files, or a single one which uses external variables
12587 to indicate what kind of library should be build.
12588
12589 The @code{Library_Version} attribute has a string value whose interpretation
12590 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12591 used only for dynamic/relocatable libraries as the internal name of the
12592 library (the @code{"soname"}). If the library file name (built from the
12593 @code{Library_Name}) is different from the @code{Library_Version}, then the
12594 library file will be a symbolic link to the actual file whose name will be
12595 @code{Library_Version}.
12596
12597 Example (on Unix):
12598
12599 @smallexample @c projectfile
12600 @group
12601 project Plib is
12602
12603    Version := "1";
12604
12605    for Library_Dir use "lib_dir";
12606    for Library_Name use "dummy";
12607    for Library_Kind use "relocatable";
12608    for Library_Version use "libdummy.so." & Version;
12609
12610 end Plib;
12611 @end group
12612 @end smallexample
12613
12614 @noindent
12615 Directory @file{lib_dir} will contain the internal library file whose name
12616 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12617 @file{libdummy.so.1}.
12618
12619 When @command{gnatmake} detects that a project file
12620 is a library project file, it will check all immediate sources of the project
12621 and rebuild the library if any of the sources have been recompiled.
12622
12623 Standard project files can import library project files. In such cases,
12624 the libraries will only be rebuild if some of its sources are recompiled
12625 because they are in the closure of some other source in an importing project.
12626 Sources of the library project files that are not in such a closure will
12627 not be checked, unless the full library is checked, because one of its sources
12628 needs to be recompiled.
12629
12630 For instance, assume the project file @code{A} imports the library project file
12631 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
12632 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
12633 @file{l2.ads}, @file{l2.adb}.
12634
12635 If @file{l1.adb} has been modified, then the library associated with @code{L}
12636 will be rebuild when compiling all the immediate sources of @code{A} only
12637 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
12638 @code{"with L1;"}.
12639
12640 To be sure that all the sources in the library associated with @code{L} are
12641 up to date, and that all the sources of parject @code{A} are also up to date,
12642 the following two commands needs to be used:
12643
12644 @smallexample
12645 gnatmake -Pl.gpr
12646 gnatmake -Pa.gpr
12647 @end smallexample
12648
12649 When a library is built or rebuilt, an attempt is made first to delete all
12650 files in the library directory.
12651 All @file{ALI} files will also be copied from the object directory to the
12652 library directory. To build executables, @command{gnatmake} will use the
12653 library rather than the individual object files.
12654
12655 @ifclear vms
12656 It is also possible to create library project files for third-party libraries
12657 that are precompiled and cannot be compiled locally thanks to the
12658 @code{externally_built} attribute. (See @ref{Installing a library}).
12659 @end ifclear
12660
12661 @c *******************************
12662 @c * Stand-alone Library Projects *
12663 @c *******************************
12664
12665 @node Stand-alone Library Projects
12666 @section Stand-alone Library Projects
12667
12668 @noindent
12669 A Stand-alone Library is a library that contains the necessary code to
12670 elaborate the Ada units that are included in the library. A Stand-alone
12671 Library is suitable to be used in an executable when the main is not
12672 in Ada. However, Stand-alone Libraries may also be used with an Ada main
12673 subprogram.
12674
12675 A Stand-alone Library Project is a Library Project where the library is
12676 a Stand-alone Library.
12677
12678 To be a Stand-alone Library Project, in addition to the two attributes
12679 that make a project a Library Project (@code{Library_Name} and
12680 @code{Library_Dir}, see @ref{Library Projects}), the attribute
12681 @code{Library_Interface} must be defined.
12682
12683 @smallexample @c projectfile
12684 @group
12685    for Library_Dir use "lib_dir";
12686    for Library_Name use "dummy";
12687    for Library_Interface use ("int1", "int1.child");
12688 @end group
12689 @end smallexample
12690
12691 Attribute @code{Library_Interface} has a non empty string list value,
12692 each string in the list designating a unit contained in an immediate source
12693 of the project file.
12694
12695 When a Stand-alone Library is built, first the binder is invoked to build
12696 a package whose name depends on the library name
12697 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12698 This binder-generated package includes initialization and
12699 finalization procedures whose
12700 names depend on the library name (dummyinit and dummyfinal in the example
12701 above). The object corresponding to this package is included in the library.
12702
12703 A dynamic or relocatable Stand-alone Library is automatically initialized
12704 if automatic initialization of Stand-alone Libraries is supported on the
12705 platform and if attribute @code{Library_Auto_Init} is not specified or
12706 is specified with the value "true". A static Stand-alone Library is never
12707 automatically initialized.
12708
12709 Single string attribute @code{Library_Auto_Init} may be specified with only
12710 two possible values: "false" or "true" (case-insensitive). Specifying
12711 "false" for attribute @code{Library_Auto_Init} will prevent automatic
12712 initialization of dynamic or relocatable libraries.
12713
12714 When a non automatically initialized Stand-alone Library is used
12715 in an executable, its initialization procedure must be called before
12716 any service of the library is used.
12717 When the main subprogram is in Ada, it may mean that the initialization
12718 procedure has to be called during elaboration of another package.
12719
12720 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12721 (those that are listed in attribute @code{Library_Interface}) are copied to
12722 the Library Directory. As a consequence, only the Interface Units may be
12723 imported from Ada units outside of the library. If other units are imported,
12724 the binding phase will fail.
12725
12726 When a Stand-Alone Library is bound, the switches that are specified in
12727 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12728 used in the call to @command{gnatbind}.
12729
12730 The string list attribute @code{Library_Options} may be used to specified
12731 additional switches to the call to @command{gcc} to link the library.
12732
12733 The attribute @code{Library_Src_Dir}, may be specified for a
12734 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12735 single string value. Its value must be the path (absolute or relative to the
12736 project directory) of an existing directory. This directory cannot be the
12737 object directory or one of the source directories, but it can be the same as
12738 the library directory. The sources of the Interface
12739 Units of the library, necessary to an Ada client of the library, will be
12740 copied to the designated directory, called Interface Copy directory.
12741 These sources includes the specs of the Interface Units, but they may also
12742 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12743 are used, or when there is a generic units in the spec. Before the sources
12744 are copied to the Interface Copy directory, an attempt is made to delete all
12745 files in the Interface Copy directory.
12746
12747 @c *************************************
12748 @c * Switches Related to Project Files *
12749 @c *************************************
12750 @node Switches Related to Project Files
12751 @section Switches Related to Project Files
12752
12753 @noindent
12754 The following switches are used by GNAT tools that support project files:
12755
12756 @table @option
12757
12758 @item ^-P^/PROJECT_FILE=^@var{project}
12759 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12760 Indicates the name of a project file. This project file will be parsed with
12761 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12762 if any, and using the external references indicated
12763 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12764 @ifclear vms
12765 There may zero, one or more spaces between @option{-P} and @var{project}.
12766 @end ifclear
12767
12768 @noindent
12769 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12770
12771 @noindent
12772 Since the Project Manager parses the project file only after all the switches
12773 on the command line are checked, the order of the switches
12774 @option{^-P^/PROJECT_FILE^},
12775 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12776 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12777
12778 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12779 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12780 Indicates that external variable @var{name} has the value @var{value}.
12781 The Project Manager will use this value for occurrences of
12782 @code{external(name)} when parsing the project file.
12783
12784 @ifclear vms
12785 @noindent
12786 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12787 put between quotes.
12788 @smallexample
12789   -XOS=NT
12790   -X"user=John Doe"
12791 @end smallexample
12792 @end ifclear
12793
12794 @noindent
12795 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12796 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12797 @var{name}, only the last one is used.
12798
12799 @noindent
12800 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12801 takes precedence over the value of the same name in the environment.
12802
12803 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12804 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
12805 @c Previous line uses code vs option command, to stay less than 80 chars
12806 Indicates the verbosity of the parsing of GNAT project files.
12807
12808 @ifclear vms
12809 @option{-vP0} means Default;
12810 @option{-vP1} means Medium;
12811 @option{-vP2} means High.
12812 @end ifclear
12813
12814 @ifset vms
12815 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12816 HIGH.
12817 @end ifset
12818
12819 @noindent
12820 The default is ^Default^DEFAULT^: no output for syntactically correct
12821 project files.
12822 @noindent
12823 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12824 only the last one is used.
12825
12826 @end table
12827
12828 @c **********************************
12829 @c * Tools Supporting Project Files *
12830 @c **********************************
12831
12832 @node  Tools Supporting Project Files
12833 @section Tools Supporting Project Files
12834
12835 @menu
12836 * gnatmake and Project Files::
12837 * The GNAT Driver and Project Files::
12838 @ifclear vms
12839 * Glide and Project Files::
12840 @end ifclear
12841 @end menu
12842
12843 @node gnatmake and Project Files
12844 @subsection gnatmake and Project Files
12845
12846 @noindent
12847 This section covers several topics related to @command{gnatmake} and
12848 project files: defining ^switches^switches^ for @command{gnatmake}
12849 and for the tools that it invokes; specifying configuration pragmas;
12850 the use of the @code{Main} attribute; building and rebuilding library project
12851 files.
12852
12853 @menu
12854 * ^Switches^Switches^ and Project Files::
12855 * Specifying Configuration Pragmas::
12856 * Project Files and Main Subprograms::
12857 * Library Project Files::
12858 @end menu
12859
12860 @node ^Switches^Switches^ and Project Files
12861 @subsubsection ^Switches^Switches^ and Project Files
12862
12863 @ifset vms
12864 It is not currently possible to specify VMS style qualifiers in the project
12865 files; only Unix style ^switches^switches^ may be specified.
12866 @end ifset
12867
12868 @noindent
12869 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12870 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12871 attribute, a @code{^Switches^Switches^} attribute, or both;
12872 as their names imply, these ^switch^switch^-related
12873 attributes affect the ^switches^switches^ that are used for each of these GNAT
12874 components when
12875 @command{gnatmake} is invoked.  As will be explained below, these
12876 component-specific ^switches^switches^ precede
12877 the ^switches^switches^ provided on the @command{gnatmake} command line.
12878
12879 The @code{^Default_Switches^Default_Switches^} attribute is an associative
12880 array indexed by language name (case insensitive) whose value is a string list.
12881 For example:
12882
12883 @smallexample @c projectfile
12884 @group
12885 package Compiler is
12886   for ^Default_Switches^Default_Switches^ ("Ada")
12887       use ("^-gnaty^-gnaty^",
12888            "^-v^-v^");
12889 end Compiler;
12890 @end group
12891 @end smallexample
12892
12893 @noindent
12894 The @code{^Switches^Switches^} attribute is also an associative array,
12895 indexed by a file name (which may or may not be case sensitive, depending
12896 on the operating system) whose value is a string list.  For example:
12897
12898 @smallexample @c projectfile
12899 @group
12900 package Builder is
12901    for ^Switches^Switches^ ("main1.adb")
12902        use ("^-O2^-O2^");
12903    for ^Switches^Switches^ ("main2.adb")
12904        use ("^-g^-g^");
12905 end Builder;
12906 @end group
12907 @end smallexample
12908
12909 @noindent
12910 For the @code{Builder} package, the file names must designate source files
12911 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12912 file names must designate @file{ALI} or source files for main subprograms.
12913 In each case just the file name without an explicit extension is acceptable.
12914
12915 For each tool used in a program build (@command{gnatmake}, the compiler, the
12916 binder, and the linker), the corresponding package @dfn{contributes} a set of
12917 ^switches^switches^ for each file on which the tool is invoked, based on the
12918 ^switch^switch^-related attributes defined in the package.
12919 In particular, the ^switches^switches^
12920 that each of these packages contributes for a given file @var{f} comprise:
12921
12922 @itemize @bullet
12923 @item
12924 the value of attribute @code{^Switches^Switches^ (@var{f})},
12925 if it is specified in the package for the given file,
12926 @item
12927 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12928 if it is specified in the package.
12929 @end itemize
12930
12931 @noindent
12932 If neither of these attributes is defined in the package, then the package does
12933 not contribute any ^switches^switches^ for the given file.
12934
12935 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12936 two sets, in the following order: those contributed for the file
12937 by the @code{Builder} package;
12938 and the switches passed on the command line.
12939
12940 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12941 the ^switches^switches^ passed to the tool comprise three sets,
12942 in the following order:
12943
12944 @enumerate
12945 @item
12946 the applicable ^switches^switches^ contributed for the file
12947 by the @code{Builder} package in the project file supplied on the command line;
12948
12949 @item
12950 those contributed for the file by the package (in the relevant project file --
12951 see below) corresponding to the tool; and
12952
12953 @item
12954 the applicable switches passed on the command line.
12955 @end enumerate
12956
12957 @noindent
12958 The term @emph{applicable ^switches^switches^} reflects the fact that
12959 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12960 tools, depending on the individual ^switch^switch^.
12961
12962 @command{gnatmake} may invoke the compiler on source files from different
12963 projects. The Project Manager will use the appropriate project file to
12964 determine the @code{Compiler} package for each source file being compiled.
12965 Likewise for the @code{Binder} and @code{Linker} packages.
12966
12967 As an example, consider the following package in a project file:
12968
12969 @smallexample @c projectfile
12970 @group
12971 project Proj1 is
12972    package Compiler is
12973       for ^Default_Switches^Default_Switches^ ("Ada")
12974           use ("^-g^-g^");
12975       for ^Switches^Switches^ ("a.adb")
12976           use ("^-O1^-O1^");
12977       for ^Switches^Switches^ ("b.adb")
12978           use ("^-O2^-O2^",
12979                "^-gnaty^-gnaty^");
12980    end Compiler;
12981 end Proj1;
12982 @end group
12983 @end smallexample
12984
12985 @noindent
12986 If @command{gnatmake} is invoked with this project file, and it needs to
12987 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12988 @file{a.adb} will be compiled with the ^switch^switch^
12989 @option{^-O1^-O1^},
12990 @file{b.adb} with ^switches^switches^
12991 @option{^-O2^-O2^}
12992 and @option{^-gnaty^-gnaty^},
12993 and @file{c.adb} with @option{^-g^-g^}.
12994
12995 The following example illustrates the ordering of the ^switches^switches^
12996 contributed by different packages:
12997
12998 @smallexample @c projectfile
12999 @group
13000 project Proj2 is
13001    package Builder is
13002       for ^Switches^Switches^ ("main.adb")
13003           use ("^-g^-g^",
13004                "^-O1^-)1^",
13005                "^-f^-f^");
13006    end Builder;
13007 @end group
13008
13009 @group
13010    package Compiler is
13011       for ^Switches^Switches^ ("main.adb")
13012           use ("^-O2^-O2^");
13013    end Compiler;
13014 end Proj2;
13015 @end group
13016 @end smallexample
13017
13018 @noindent
13019 If you issue the command:
13020
13021 @smallexample
13022     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
13023 @end smallexample
13024
13025 @noindent
13026 then the compiler will be invoked on @file{main.adb} with the following
13027 sequence of ^switches^switches^
13028
13029 @smallexample
13030    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
13031 @end smallexample
13032
13033 with the last @option{^-O^-O^}
13034 ^switch^switch^ having precedence over the earlier ones;
13035 several other ^switches^switches^
13036 (such as @option{^-c^-c^}) are added implicitly.
13037
13038 The ^switches^switches^
13039 @option{^-g^-g^}
13040 and @option{^-O1^-O1^} are contributed by package
13041 @code{Builder},  @option{^-O2^-O2^} is contributed
13042 by the package @code{Compiler}
13043 and @option{^-O0^-O0^} comes from the command line.
13044
13045 The @option{^-g^-g^}
13046 ^switch^switch^ will also be passed in the invocation of
13047 @command{Gnatlink.}
13048
13049 A final example illustrates switch contributions from packages in different
13050 project files:
13051
13052 @smallexample @c projectfile
13053 @group
13054 project Proj3 is
13055    for Source_Files use ("pack.ads", "pack.adb");
13056    package Compiler is
13057       for ^Default_Switches^Default_Switches^ ("Ada")
13058           use ("^-gnata^-gnata^");
13059    end Compiler;
13060 end Proj3;
13061 @end group
13062
13063 @group
13064 with "Proj3";
13065 project Proj4 is
13066    for Source_Files use ("foo_main.adb", "bar_main.adb");
13067    package Builder is
13068       for ^Switches^Switches^ ("foo_main.adb")
13069           use ("^-s^-s^",
13070                "^-g^-g^");
13071    end Builder;
13072 end Proj4;
13073 @end group
13074
13075 @group
13076 -- Ada source file:
13077 with Pack;
13078 procedure Foo_Main is
13079    ...
13080 end Foo_Main;
13081 @end group
13082 @end smallexample
13083
13084 If the command is
13085 @smallexample
13086 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13087 @end smallexample
13088
13089 @noindent
13090 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13091 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13092 @option{^-gnato^-gnato^} (passed on the command line).
13093 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13094 are @option{^-g^-g^} from @code{Proj4.Builder},
13095 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13096 and @option{^-gnato^-gnato^} from the command line.
13097
13098 @noindent
13099 When using @command{gnatmake} with project files, some ^switches^switches^ or
13100 arguments may be expressed as relative paths. As the working directory where
13101 compilation occurs may change, these relative paths are converted to absolute
13102 paths. For the ^switches^switches^ found in a project file, the relative paths
13103 are relative to the project file directory, for the switches on the command
13104 line, they are relative to the directory where @command{gnatmake} is invoked.
13105 The ^switches^switches^ for which this occurs are:
13106 ^-I^-I^,
13107 ^-A^-A^,
13108 ^-L^-L^,
13109 ^-aO^-aO^,
13110 ^-aL^-aL^,
13111 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13112 ^switch^switch^
13113 ^-o^-o^, object files specified in package @code{Linker} or after
13114 -largs on the command line). The exception to this rule is the ^switch^switch^
13115 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13116
13117 @node Specifying Configuration Pragmas
13118 @subsubsection Specifying Configuration Pragmas
13119
13120 When using @command{gnatmake} with project files, if there exists a file
13121 @file{gnat.adc} that contains configuration pragmas, this file will be
13122 ignored.
13123
13124 Configuration pragmas can be defined by means of the following attributes in
13125 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13126 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13127
13128 Both these attributes are single string attributes. Their values is the path
13129 name of a file containing configuration pragmas. If a path name is relative,
13130 then it is relative to the project directory of the project file where the
13131 attribute is defined.
13132
13133 When compiling a source, the configuration pragmas used are, in order,
13134 those listed in the file designated by attribute
13135 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13136 project file, if it is specified, and those listed in the file designated by
13137 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13138 the project file of the source, if it exists.
13139
13140 @node Project Files and Main Subprograms
13141 @subsubsection Project Files and Main Subprograms
13142
13143 @noindent
13144 When using a project file, you can invoke @command{gnatmake}
13145 with one or several main subprograms, by specifying their source files on the
13146 command line.
13147
13148 @smallexample
13149     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13150 @end smallexample
13151
13152 @noindent
13153 Each of these needs to be a source file of the same project, except
13154 when the switch ^-u^/UNIQUE^ is used.
13155
13156 @noindent
13157 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13158 same project, one of the project in the tree rooted at the project specified
13159 on the command line. The package @code{Builder} of this common project, the
13160 "main project" is the one that is considered by @command{gnatmake}.
13161
13162 @noindent
13163 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13164 imported directly or indirectly by the project specified on the command line.
13165 Note that if such a source file is not part of the project specified on the
13166 command line, the ^switches^switches^ found in package @code{Builder} of the
13167 project specified on the command line, if any, that are transmitted
13168 to the compiler will still be used, not those found in the project file of
13169 the source file.
13170
13171 @noindent
13172 When using a project file, you can also invoke @command{gnatmake} without
13173 explicitly specifying any main, and the effect depends on whether you have
13174 defined the @code{Main} attribute.  This attribute has a string list value,
13175 where each element in the list is the name of a source file (the file
13176 extension is optional) that contains a unit that can be a main subprogram.
13177
13178 If the @code{Main} attribute is defined in a project file as a non-empty
13179 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13180 line, then invoking @command{gnatmake} with this project file but without any
13181 main on the command line is equivalent to invoking @command{gnatmake} with all
13182 the file names in the @code{Main} attribute on the command line.
13183
13184 Example:
13185 @smallexample @c projectfile
13186 @group
13187    project Prj is
13188       for Main use ("main1", "main2", "main3");
13189    end Prj;
13190 @end group
13191 @end smallexample
13192
13193 @noindent
13194 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13195 is equivalent to
13196 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13197
13198 When the project attribute @code{Main} is not specified, or is specified
13199 as an empty string list, or when the switch @option{-u} is used on the command
13200 line, then invoking @command{gnatmake} with no main on the command line will
13201 result in all immediate sources of the project file being checked, and
13202 potentially recompiled. Depending on the presence of the switch @option{-u},
13203 sources from other project files on which the immediate sources of the main
13204 project file depend are also checked and potentially recompiled. In other
13205 words, the @option{-u} switch is applied to all of the immediate sources of the
13206 main project file.
13207
13208 When no main is specified on the command line and attribute @code{Main} exists
13209 and includes several mains, or when several mains are specified on the
13210 command line, the default ^switches^switches^ in package @code{Builder} will
13211 be used for all mains, even if there are specific ^switches^switches^
13212 specified for one or several mains.
13213
13214 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13215 the specific ^switches^switches^ for each main, if they are specified.
13216
13217 @node Library Project Files
13218 @subsubsection Library Project Files
13219
13220 @noindent
13221 When @command{gnatmake} is invoked with a main project file that is a library
13222 project file, it is not allowed to specify one or more mains on the command
13223 line.
13224
13225 @noindent
13226 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13227 ^-l^/ACTION=LINK^ have special meanings.
13228
13229 @itemize @bullet
13230 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13231 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13232 library.
13233
13234 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13235 to @command{gnatmake} that the binder generated file should be compiled
13236 (in the case of a stand-alone library) and that the library should be built.
13237
13238 @end itemize
13239
13240 @node The GNAT Driver and Project Files
13241 @subsection The GNAT Driver and Project Files
13242
13243 @noindent
13244 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13245 are project-aware:
13246 @command{^gnatbind^gnatbind^},
13247 @command{^gnatfind^gnatfind^},
13248 @command{^gnatlink^gnatlink^},
13249 @command{^gnatls^gnatls^},
13250 @command{^gnatelim^gnatelim^},
13251 @command{^gnatpp^gnatpp^},
13252 @command{^gnatmetric^gnatmetric^},
13253 @command{^gnatstub^gnatstub^},
13254 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13255 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13256 They must be invoked through the @command{gnat} driver.
13257
13258 The @command{gnat} driver is a front-end that accepts a number of commands and
13259 call the corresponding tool. It has been designed initially for VMS to convert
13260 VMS style qualifiers to Unix style switches, but it is now available to all
13261 the GNAT supported platforms.
13262
13263 On non VMS platforms, the @command{gnat} driver accepts the following commands
13264 (case insensitive):
13265
13266 @itemize @bullet
13267 @item
13268 BIND to invoke @command{^gnatbind^gnatbind^}
13269 @item
13270 CHOP to invoke @command{^gnatchop^gnatchop^}
13271 @item
13272 CLEAN to invoke @command{^gnatclean^gnatclean^}
13273 @item
13274 COMP or COMPILE to invoke the compiler
13275 @item
13276 ELIM to invoke @command{^gnatelim^gnatelim^}
13277 @item
13278 FIND to invoke @command{^gnatfind^gnatfind^}
13279 @item
13280 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13281 @item
13282 LINK to invoke @command{^gnatlink^gnatlink^}
13283 @item
13284 LS or LIST to invoke @command{^gnatls^gnatls^}
13285 @item
13286 MAKE to invoke @command{^gnatmake^gnatmake^}
13287 @item
13288 NAME to invoke @command{^gnatname^gnatname^}
13289 @item
13290 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13291 @item
13292 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13293 @item
13294 METRIC to invoke @command{^gnatmetric^gnatmetric^}
13295 @item
13296 STUB to invoke @command{^gnatstub^gnatstub^}
13297 @item
13298 XREF to invoke @command{^gnatxref^gnatxref^}
13299 @end itemize
13300
13301 @noindent
13302 (note that the compiler is invoked using the command
13303 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13304
13305 @noindent
13306 On non VMS platforms, between @command{gnat} and the command, two
13307 special switches may be used:
13308
13309 @itemize @bullet
13310 @item
13311 @command{-v} to display the invocation of the tool.
13312 @item
13313 @command{-dn} to prevent the @command{gnat} driver from removing
13314 the temporary files it has created. These temporary files are
13315 configuration files and temporary file list files.
13316 @end itemize
13317
13318 @noindent
13319 The command may be followed by switches and arguments for the invoked
13320 tool.
13321
13322 @smallexample
13323   gnat bind -C main.ali
13324   gnat ls -a main
13325   gnat chop foo.txt
13326 @end smallexample
13327
13328 @noindent
13329 Switches may also be put in text files, one switch per line, and the text
13330 files may be specified with their path name preceded by '@@'.
13331
13332 @smallexample
13333    gnat bind @@args.txt main.ali
13334 @end smallexample
13335
13336 @noindent
13337 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13338 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
13339 (@option{^-P^/PROJECT_FILE^},
13340 @option{^-X^/EXTERNAL_REFERENCE^} and
13341 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13342 the switches of the invoking tool.
13343
13344 @noindent
13345 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13346 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13347 the immediate sources of the specified project file.
13348
13349 @noindent
13350 When GNAT METRIC is used with a project file, but with no source
13351 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13352 with all the immediate sources of the specified project file and with
13353 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13354 of the project.
13355
13356 @noindent
13357 For each of the following commands, there is optionally a corresponding
13358 package in the main project.
13359
13360 @itemize @bullet
13361 @item
13362 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13363
13364 @item
13365 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13366
13367 @item
13368 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13369
13370 @item
13371 package @code{Eliminate} for command ELIM (invoking
13372 @code{^gnatelim^gnatelim^})
13373
13374 @item
13375 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13376
13377 @item
13378 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13379
13380 @item
13381 package @code{Metrics} for command METRIC
13382 (invoking @code{^gnatmetric^gnatmetric^})
13383
13384 @item
13385 package @code{Pretty_Printer} for command PP or PRETTY
13386 (invoking @code{^gnatpp^gnatpp^})
13387
13388 @item
13389 package @code{Gnatstub} for command STUB
13390 (invoking @code{^gnatstub^gnatstub^})
13391
13392 @item
13393 package @code{Cross_Reference} for command XREF (invoking
13394 @code{^gnatxref^gnatxref^})
13395
13396 @end itemize
13397
13398 @noindent
13399 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13400 a simple variable with a string list value. It contains ^switches^switches^
13401 for the invocation of @code{^gnatls^gnatls^}.
13402
13403 @smallexample @c projectfile
13404 @group
13405 project Proj1 is
13406    package gnatls is
13407       for ^Switches^Switches^
13408           use ("^-a^-a^",
13409                "^-v^-v^");
13410    end gnatls;
13411 end Proj1;
13412 @end group
13413 @end smallexample
13414
13415 @noindent
13416 All other packages have two attribute @code{^Switches^Switches^} and
13417 @code{^Default_Switches^Default_Switches^}.
13418
13419 @noindent
13420 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13421 source file name, that has a string list value: the ^switches^switches^ to be
13422 used when the tool corresponding to the package is invoked for the specific
13423 source file.
13424
13425 @noindent
13426 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13427 indexed by  the programming language that has a string list value.
13428 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13429 ^switches^switches^ for the invocation of the tool corresponding
13430 to the package, except if a specific @code{^Switches^Switches^} attribute
13431 is specified for the source file.
13432
13433 @smallexample @c projectfile
13434 @group
13435 project Proj is
13436
13437    for Source_Dirs use ("./**");
13438
13439    package gnatls is
13440       for ^Switches^Switches^ use
13441           ("^-a^-a^",
13442            "^-v^-v^");
13443    end gnatls;
13444 @end group
13445 @group
13446
13447    package Compiler is
13448       for ^Default_Switches^Default_Switches^ ("Ada")
13449           use ("^-gnatv^-gnatv^",
13450                "^-gnatwa^-gnatwa^");
13451    end Binder;
13452 @end group
13453 @group
13454
13455    package Binder is
13456       for ^Default_Switches^Default_Switches^ ("Ada")
13457           use ("^-C^-C^",
13458                "^-e^-e^");
13459    end Binder;
13460 @end group
13461 @group
13462
13463    package Linker is
13464       for ^Default_Switches^Default_Switches^ ("Ada")
13465           use ("^-C^-C^");
13466       for ^Switches^Switches^ ("main.adb")
13467           use ("^-C^-C^",
13468                "^-v^-v^",
13469                "^-v^-v^");
13470    end Linker;
13471 @end group
13472 @group
13473
13474    package Finder is
13475       for ^Default_Switches^Default_Switches^ ("Ada")
13476            use ("^-a^-a^",
13477                 "^-f^-f^");
13478    end Finder;
13479 @end group
13480 @group
13481
13482    package Cross_Reference is
13483       for ^Default_Switches^Default_Switches^ ("Ada")
13484           use ("^-a^-a^",
13485                "^-f^-f^",
13486                "^-d^-d^",
13487                "^-u^-u^");
13488    end Cross_Reference;
13489 end Proj;
13490 @end group
13491 @end smallexample
13492
13493 @noindent
13494 With the above project file, commands such as
13495
13496 @smallexample
13497    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13498    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13499    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13500    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13501    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13502 @end smallexample
13503
13504 @noindent
13505 will set up the environment properly and invoke the tool with the switches
13506 found in the package corresponding to the tool:
13507 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13508 except @code{^Switches^Switches^ ("main.adb")}
13509 for @code{^gnatlink^gnatlink^}.
13510
13511 @ifclear vms
13512 @node Glide and Project Files
13513 @subsection Glide and Project Files
13514
13515 @noindent
13516 Glide will automatically recognize the @file{.gpr} extension for
13517 project files, and will
13518 convert them to its own internal format automatically. However, it
13519 doesn't provide a syntax-oriented editor for modifying these
13520 files.
13521 The project file will be loaded as text when you select the menu item
13522 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13523 You can edit this text and save the @file{gpr} file;
13524 when you next select this project file in Glide it
13525 will be automatically reloaded.
13526 @end ifclear
13527
13528 @c **********************
13529 @node An Extended Example
13530 @section An Extended Example
13531
13532 @noindent
13533 Suppose that we have two programs, @var{prog1} and @var{prog2},
13534 whose sources are in corresponding directories. We would like
13535 to build them with a single @command{gnatmake} command, and we want to place
13536 their object files into @file{build} subdirectories of the source directories.
13537 Furthermore, we want to have to have two separate subdirectories
13538 in @file{build}  -- @file{release} and @file{debug} -- which will contain
13539 the object files compiled with different set of compilation flags.
13540
13541 In other words, we have the following structure:
13542
13543 @smallexample
13544 @group
13545    main
13546      |- prog1
13547      |    |- build
13548      |         | debug
13549      |         | release
13550      |- prog2
13551           |- build
13552                | debug
13553                | release
13554 @end group
13555 @end smallexample
13556
13557 @noindent
13558 Here are the project files that we must place in a directory @file{main}
13559 to maintain this structure:
13560
13561 @enumerate
13562
13563 @item We create a @code{Common} project with a package @code{Compiler} that
13564 specifies the compilation ^switches^switches^:
13565
13566 @smallexample
13567 File "common.gpr":
13568 @group
13569 @b{project} Common @b{is}
13570
13571    @b{for} Source_Dirs @b{use} (); -- No source files
13572 @end group
13573
13574 @group
13575    @b{type} Build_Type @b{is} ("release", "debug");
13576    Build : Build_Type := External ("BUILD", "debug");
13577 @end group
13578 @group
13579    @b{package} Compiler @b{is}
13580       @b{case} Build @b{is}
13581          @b{when} "release" =>
13582            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13583                    @b{use} ("^-O2^-O2^");
13584          @b{when} "debug"   =>
13585            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13586                    @b{use} ("^-g^-g^");
13587       @b{end case};
13588    @b{end} Compiler;
13589
13590 @b{end} Common;
13591 @end group
13592 @end smallexample
13593
13594 @item We create separate projects for the two programs:
13595
13596 @smallexample
13597 @group
13598 File "prog1.gpr":
13599
13600 @b{with} "common";
13601 @b{project} Prog1 @b{is}
13602
13603     @b{for} Source_Dirs @b{use} ("prog1");
13604     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
13605
13606     @b{package} Compiler @b{renames} Common.Compiler;
13607
13608 @b{end} Prog1;
13609 @end group
13610 @end smallexample
13611
13612 @smallexample
13613 @group
13614 File "prog2.gpr":
13615
13616 @b{with} "common";
13617 @b{project} Prog2 @b{is}
13618
13619     @b{for} Source_Dirs @b{use} ("prog2");
13620     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
13621
13622     @b{package} Compiler @b{renames} Common.Compiler;
13623
13624 @end group
13625 @b{end} Prog2;
13626 @end smallexample
13627
13628 @item We create a wrapping project @code{Main}:
13629
13630 @smallexample
13631 @group
13632 File "main.gpr":
13633
13634 @b{with} "common";
13635 @b{with} "prog1";
13636 @b{with} "prog2";
13637 @b{project} Main @b{is}
13638
13639    @b{package} Compiler @b{renames} Common.Compiler;
13640
13641 @b{end} Main;
13642 @end group
13643 @end smallexample
13644
13645 @item Finally we need to create a dummy procedure that @code{with}s (either
13646 explicitly or implicitly) all the sources of our two programs.
13647
13648 @end enumerate
13649
13650 @noindent
13651 Now we can build the programs using the command
13652
13653 @smallexample
13654    gnatmake ^-P^/PROJECT_FILE=^main dummy
13655 @end smallexample
13656
13657 @noindent
13658 for the Debug mode, or
13659
13660 @ifclear vms
13661 @smallexample
13662    gnatmake -Pmain -XBUILD=release
13663 @end smallexample
13664 @end ifclear
13665
13666 @ifset vms
13667 @smallexample
13668    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13669 @end smallexample
13670 @end ifset
13671
13672 @noindent
13673 for the Release mode.
13674
13675 @c ********************************
13676 @c * Project File Complete Syntax *
13677 @c ********************************
13678
13679 @node Project File Complete Syntax
13680 @section Project File Complete Syntax
13681
13682 @smallexample
13683 project ::=
13684   context_clause project_declaration
13685
13686 context_clause ::=
13687   @{with_clause@}
13688
13689 with_clause ::=
13690   @b{with} path_name @{ , path_name @} ;
13691
13692 path_name ::=
13693    string_literal
13694
13695 project_declaration ::=
13696   simple_project_declaration | project_extension
13697
13698 simple_project_declaration ::=
13699   @b{project} <project_>simple_name @b{is}
13700     @{declarative_item@}
13701   @b{end} <project_>simple_name;
13702
13703 project_extension ::=
13704   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
13705     @{declarative_item@}
13706   @b{end} <project_>simple_name;
13707
13708 declarative_item ::=
13709   package_declaration |
13710   typed_string_declaration |
13711   other_declarative_item
13712
13713 package_declaration ::=
13714   package_specification | package_renaming
13715
13716 package_specification ::=
13717   @b{package} package_identifier @b{is}
13718     @{simple_declarative_item@}
13719   @b{end} package_identifier ;
13720
13721 package_identifier ::=
13722   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13723   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
13724   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
13725
13726 package_renaming ::==
13727   @b{package} package_identifier @b{renames}
13728        <project_>simple_name.package_identifier ;
13729
13730 typed_string_declaration ::=
13731   @b{type} <typed_string_>_simple_name @b{is}
13732    ( string_literal @{, string_literal@} );
13733
13734 other_declarative_item ::=
13735   attribute_declaration |
13736   typed_variable_declaration |
13737   variable_declaration |
13738   case_construction
13739
13740 attribute_declaration ::=
13741   full_associative_array_declaration |
13742   @b{for} attribute_designator @b{use} expression ;
13743
13744 full_associative_array_declaration ::=
13745   @b{for} <associative_array_attribute_>simple_name @b{use}
13746   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13747
13748 attribute_designator ::=
13749   <simple_attribute_>simple_name |
13750   <associative_array_attribute_>simple_name ( string_literal )
13751
13752 typed_variable_declaration ::=
13753   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
13754
13755 variable_declaration ::=
13756   <variable_>simple_name := expression;
13757
13758 expression ::=
13759   term @{& term@}
13760
13761 term ::=
13762   literal_string |
13763   string_list |
13764   <variable_>name |
13765   external_value |
13766   attribute_reference
13767
13768 string_literal ::=
13769   (same as Ada)
13770
13771 string_list ::=
13772   ( <string_>expression @{ , <string_>expression @} )
13773
13774 external_value ::=
13775   @b{external} ( string_literal [, string_literal] )
13776
13777 attribute_reference ::=
13778   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
13779
13780 attribute_prefix ::=
13781   @b{project} |
13782   <project_>simple_name | package_identifier |
13783   <project_>simple_name . package_identifier
13784
13785 case_construction ::=
13786   @b{case} <typed_variable_>name @b{is}
13787     @{case_item@}
13788   @b{end case} ;
13789
13790 case_item ::=
13791   @b{when} discrete_choice_list =>
13792       @{case_construction | attribute_declaration@}
13793
13794 discrete_choice_list ::=
13795   string_literal @{| string_literal@} |
13796   @b{others}
13797
13798 name ::=
13799   simple_name @{. simple_name@}
13800
13801 simple_name ::=
13802   identifier (same as Ada)
13803
13804 @end smallexample
13805
13806 @node The Cross-Referencing Tools gnatxref and gnatfind
13807 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13808 @findex gnatxref
13809 @findex gnatfind
13810
13811 @noindent
13812 The compiler generates cross-referencing information (unless
13813 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13814 This information indicates where in the source each entity is declared and
13815 referenced. Note that entities in package Standard are not included, but
13816 entities in all other predefined units are included in the output.
13817
13818 Before using any of these two tools, you need to compile successfully your
13819 application, so that GNAT gets a chance to generate the cross-referencing
13820 information.
13821
13822 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13823 information to provide the user with the capability to easily locate the
13824 declaration and references to an entity. These tools are quite similar,
13825 the difference being that @code{gnatfind} is intended for locating
13826 definitions and/or references to a specified entity or entities, whereas
13827 @code{gnatxref} is oriented to generating a full report of all
13828 cross-references.
13829
13830 To use these tools, you must not compile your application using the
13831 @option{-gnatx} switch on the @command{gnatmake} command line
13832 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13833 information will not be generated.
13834
13835 @menu
13836 * gnatxref Switches::
13837 * gnatfind Switches::
13838 * Project Files for gnatxref and gnatfind::
13839 * Regular Expressions in gnatfind and gnatxref::
13840 * Examples of gnatxref Usage::
13841 * Examples of gnatfind Usage::
13842 @end menu
13843
13844 @node gnatxref Switches
13845 @section @code{gnatxref} Switches
13846
13847 @noindent
13848 The command invocation for @code{gnatxref} is:
13849 @smallexample
13850 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13851 @end smallexample
13852
13853 @noindent
13854 where
13855
13856 @table @code
13857 @item sourcefile1, sourcefile2
13858 identifies the source files for which a report is to be generated. The
13859 ``with''ed units will be processed too. You must provide at least one file.
13860
13861 These file names are considered to be regular expressions, so for instance
13862 specifying @file{source*.adb} is the same as giving every file in the current
13863 directory whose name starts with @file{source} and whose extension is
13864 @file{adb}.
13865
13866 You shouldn't specify any directory name, just base names. @command{gnatxref}
13867 and @command{gnatfind} will be able to locate these files by themselves using
13868 the source path. If you specify directories, no result is produced.
13869
13870 @end table
13871
13872 @noindent
13873 The switches can be :
13874 @table @option
13875 @c !sort!
13876 @item ^-a^/ALL_FILES^
13877 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13878 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13879 the read-only files found in the library search path. Otherwise, these files
13880 will be ignored. This option can be used to protect Gnat sources or your own
13881 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13882 much faster, and their output much smaller. Read-only here refers to access
13883 or permissions status in the file system for the current user.
13884
13885 @item -aIDIR
13886 @cindex @option{-aIDIR} (@command{gnatxref})
13887 When looking for source files also look in directory DIR. The order in which
13888 source file search is undertaken is the same as for @command{gnatmake}.
13889
13890 @item -aODIR
13891 @cindex @option{-aODIR} (@command{gnatxref})
13892 When searching for library and object files, look in directory
13893 DIR. The order in which library files are searched is the same as for
13894 @command{gnatmake}.
13895
13896 @item -nostdinc
13897 @cindex @option{-nostdinc} (@command{gnatxref})
13898 Do not look for sources in the system default directory.
13899
13900 @item -nostdlib
13901 @cindex @option{-nostdlib} (@command{gnatxref})
13902 Do not look for library files in the system default directory.
13903
13904 @item --RTS=@var{rts-path}
13905 @cindex @option{--RTS} (@command{gnatxref})
13906 Specifies the default location of the runtime library. Same meaning as the
13907 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13908
13909 @item ^-d^/DERIVED_TYPES^
13910 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13911 If this switch is set @code{gnatxref} will output the parent type
13912 reference for each matching derived types.
13913
13914 @item ^-f^/FULL_PATHNAME^
13915 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13916 If this switch is set, the output file names will be preceded by their
13917 directory (if the file was found in the search path). If this switch is
13918 not set, the directory will not be printed.
13919
13920 @item ^-g^/IGNORE_LOCALS^
13921 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13922 If this switch is set, information is output only for library-level
13923 entities, ignoring local entities. The use of this switch may accelerate
13924 @code{gnatfind} and @code{gnatxref}.
13925
13926 @item -IDIR
13927 @cindex @option{-IDIR} (@command{gnatxref})
13928 Equivalent to @samp{-aODIR -aIDIR}.
13929
13930 @item -pFILE
13931 @cindex @option{-pFILE} (@command{gnatxref})
13932 Specify a project file to use @xref{Project Files}. These project files are
13933 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
13934 project files, you should use gnatxref through the GNAT driver
13935 (@command{gnat xref -Pproject}).
13936
13937 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13938 project file in the current directory.
13939
13940 If a project file is either specified or found by the tools, then the content
13941 of the source directory and object directory lines are added as if they
13942 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13943 and @samp{^-aO^OBJECT_SEARCH^}.
13944 @item ^-u^/UNUSED^
13945 Output only unused symbols. This may be really useful if you give your
13946 main compilation unit on the command line, as @code{gnatxref} will then
13947 display every unused entity and 'with'ed package.
13948
13949 @ifclear vms
13950 @item -v
13951 Instead of producing the default output, @code{gnatxref} will generate a
13952 @file{tags} file that can be used by vi. For examples how to use this
13953 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13954 to the standard output, thus you will have to redirect it to a file.
13955 @end ifclear
13956
13957 @end table
13958
13959 @noindent
13960 All these switches may be in any order on the command line, and may even
13961 appear after the file names. They need not be separated by spaces, thus
13962 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13963 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13964
13965 @node gnatfind Switches
13966 @section @code{gnatfind} Switches
13967
13968 @noindent
13969 The command line for @code{gnatfind} is:
13970
13971 @smallexample
13972 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
13973       [file1 file2 ...]
13974 @end smallexample
13975
13976 @noindent
13977 where
13978
13979 @table @code
13980 @item pattern
13981 An entity will be output only if it matches the regular expression found
13982 in @samp{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13983
13984 Omitting the pattern is equivalent to specifying @samp{*}, which
13985 will match any entity. Note that if you do not provide a pattern, you
13986 have to provide both a sourcefile and a line.
13987
13988 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13989 for matching purposes. At the current time there is no support for
13990 8-bit codes other than Latin-1, or for wide characters in identifiers.
13991
13992 @item sourcefile
13993 @code{gnatfind} will look for references, bodies or declarations
13994 of symbols referenced in @file{sourcefile}, at line @samp{line}
13995 and column @samp{column}. See @ref{Examples of gnatfind Usage}
13996 for syntax examples.
13997
13998 @item line
13999 is a decimal integer identifying the line number containing
14000 the reference to the entity (or entities) to be located.
14001
14002 @item column
14003 is a decimal integer identifying the exact location on the
14004 line of the first character of the identifier for the
14005 entity reference. Columns are numbered from 1.
14006
14007 @item file1 file2 ...
14008 The search will be restricted to these source files. If none are given, then
14009 the search will be done for every library file in the search path.
14010 These file must appear only after the pattern or sourcefile.
14011
14012 These file names are considered to be regular expressions, so for instance
14013 specifying 'source*.adb' is the same as giving every file in the current
14014 directory whose name starts with 'source' and whose extension is 'adb'.
14015
14016 The location of the spec of the entity will always be displayed, even if it
14017 isn't in one of file1, file2,... The occurrences of the entity in the
14018 separate units of the ones given on the command line will also be displayed.
14019
14020 Note that if you specify at least one file in this part, @code{gnatfind} may
14021 sometimes not be able to find the body of the subprograms...
14022
14023 @end table
14024
14025 @noindent
14026 At least one of 'sourcefile' or 'pattern' has to be present on
14027 the command line.
14028
14029 The following switches are available:
14030 @table @option
14031 @c !sort!
14032
14033 @item ^-a^/ALL_FILES^
14034 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
14035 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14036 the read-only files found in the library search path. Otherwise, these files
14037 will be ignored. This option can be used to protect Gnat sources or your own
14038 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14039 much faster, and their output much smaller. Read-only here refers to access
14040 or permission status in the file system for the current user.
14041
14042 @item -aIDIR
14043 @cindex @option{-aIDIR} (@command{gnatfind})
14044 When looking for source files also look in directory DIR. The order in which
14045 source file search is undertaken is the same as for @command{gnatmake}.
14046
14047 @item -aODIR
14048 @cindex @option{-aODIR} (@command{gnatfind})
14049 When searching for library and object files, look in directory
14050 DIR. The order in which library files are searched is the same as for
14051 @command{gnatmake}.
14052
14053 @item -nostdinc
14054 @cindex @option{-nostdinc} (@command{gnatfind})
14055 Do not look for sources in the system default directory.
14056
14057 @item -nostdlib
14058 @cindex @option{-nostdlib} (@command{gnatfind})
14059 Do not look for library files in the system default directory.
14060
14061 @item --RTS=@var{rts-path}
14062 @cindex @option{--RTS} (@command{gnatfind})
14063 Specifies the default location of the runtime library. Same meaning as the
14064 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14065
14066 @item ^-d^/DERIVED_TYPE_INFORMATION^
14067 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
14068 If this switch is set, then @code{gnatfind} will output the parent type
14069 reference for each matching derived types.
14070
14071 @item ^-e^/EXPRESSIONS^
14072 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14073 By default, @code{gnatfind} accept the simple regular expression set for
14074 @samp{pattern}. If this switch is set, then the pattern will be
14075 considered as full Unix-style regular expression.
14076
14077 @item ^-f^/FULL_PATHNAME^
14078 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14079 If this switch is set, the output file names will be preceded by their
14080 directory (if the file was found in the search path). If this switch is
14081 not set, the directory will not be printed.
14082
14083 @item ^-g^/IGNORE_LOCALS^
14084 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14085 If this switch is set, information is output only for library-level
14086 entities, ignoring local entities. The use of this switch may accelerate
14087 @code{gnatfind} and @code{gnatxref}.
14088
14089 @item -IDIR
14090 @cindex @option{-IDIR} (@command{gnatfind})
14091 Equivalent to @samp{-aODIR -aIDIR}.
14092
14093 @item -pFILE
14094 @cindex @option{-pFILE} (@command{gnatfind})
14095 Specify a project file (@pxref{Project Files}) to use.
14096 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14097 project file in the current directory.
14098
14099 If a project file is either specified or found by the tools, then the content
14100 of the source directory and object directory lines are added as if they
14101 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14102 @samp{^-aO^/OBJECT_SEARCH^}.
14103
14104 @item ^-r^/REFERENCES^
14105 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14106 By default, @code{gnatfind} will output only the information about the
14107 declaration, body or type completion of the entities. If this switch is
14108 set, the @code{gnatfind} will locate every reference to the entities in
14109 the files specified on the command line (or in every file in the search
14110 path if no file is given on the command line).
14111
14112 @item ^-s^/PRINT_LINES^
14113 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14114 If this switch is set, then @code{gnatfind} will output the content
14115 of the Ada source file lines were the entity was found.
14116
14117 @item ^-t^/TYPE_HIERARCHY^
14118 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14119 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14120 the specified type. It act like -d option but recursively from parent
14121 type to parent type. When this switch is set it is not possible to
14122 specify more than one file.
14123
14124 @end table
14125
14126 @noindent
14127 All these switches may be in any order on the command line, and may even
14128 appear after the file names. They need not be separated by spaces, thus
14129 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14130 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14131
14132 As stated previously, gnatfind will search in every directory in the
14133 search path. You can force it to look only in the current directory if
14134 you specify @code{*} at the end of the command line.
14135
14136 @node Project Files for gnatxref and gnatfind
14137 @section Project Files for @command{gnatxref} and @command{gnatfind}
14138
14139 @noindent
14140 Project files allow a programmer to specify how to compile its
14141 application, where to find sources, etc.  These files are used
14142 @ifclear vms
14143 primarily by the Glide Ada mode, but they can also be used
14144 @end ifclear
14145 by the two tools
14146 @code{gnatxref} and @code{gnatfind}.
14147
14148 A project file name must end with @file{.gpr}. If a single one is
14149 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14150 extract the information from it. If multiple project files are found, none of
14151 them is read, and you have to use the @samp{-p} switch to specify the one
14152 you want to use.
14153
14154 The following lines can be included, even though most of them have default
14155 values which can be used in most cases.
14156 The lines can be entered in any order in the file.
14157 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14158 each line. If you have multiple instances, only the last one is taken into
14159 account.
14160
14161 @table @code
14162 @item src_dir=DIR
14163 [default: @code{"^./^[]^"}]
14164 specifies a directory where to look for source files. Multiple @code{src_dir}
14165 lines can be specified and they will be searched in the order they
14166 are specified.
14167
14168 @item obj_dir=DIR
14169 [default: @code{"^./^[]^"}]
14170 specifies a directory where to look for object and library files. Multiple
14171 @code{obj_dir} lines can be specified, and they will be searched in the order
14172 they are specified
14173
14174 @item comp_opt=SWITCHES
14175 [default: @code{""}]
14176 creates a variable which can be referred to subsequently by using
14177 the @code{$@{comp_opt@}} notation. This is intended to store the default
14178 switches given to @command{gnatmake} and @command{gcc}.
14179
14180 @item bind_opt=SWITCHES
14181 [default: @code{""}]
14182 creates a variable which can be referred to subsequently by using
14183 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14184 switches given to @command{gnatbind}.
14185
14186 @item link_opt=SWITCHES
14187 [default: @code{""}]
14188 creates a variable which can be referred to subsequently by using
14189 the @samp{$@{link_opt@}} notation. This is intended to store the default
14190 switches given to @command{gnatlink}.
14191
14192 @item main=EXECUTABLE
14193 [default: @code{""}]
14194 specifies the name of the executable for the application. This variable can
14195 be referred to in the following lines by using the @samp{$@{main@}} notation.
14196
14197 @ifset vms
14198 @item comp_cmd=COMMAND
14199 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14200 @end ifset
14201 @ifclear vms
14202 @item comp_cmd=COMMAND
14203 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14204 @end ifclear
14205 specifies the command used to compile a single file in the application.
14206
14207 @ifset vms
14208 @item make_cmd=COMMAND
14209 [default: @code{"GNAT MAKE $@{main@}
14210 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14211 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14212 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14213 @end ifset
14214 @ifclear vms
14215 @item make_cmd=COMMAND
14216 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14217  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14218  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14219 @end ifclear
14220 specifies the command used to recompile the whole application.
14221
14222 @item run_cmd=COMMAND
14223 [default: @code{"$@{main@}"}]
14224 specifies the command used to run the application.
14225
14226 @item debug_cmd=COMMAND
14227 [default: @code{"gdb $@{main@}"}]
14228 specifies the command used to debug the application
14229
14230 @end table
14231
14232 @noindent
14233 @command{gnatxref} and @command{gnatfind} only take into account the
14234 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14235
14236 @node Regular Expressions in gnatfind and gnatxref
14237 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
14238
14239 @noindent
14240 As specified in the section about @command{gnatfind}, the pattern can be a
14241 regular expression. Actually, there are to set of regular expressions
14242 which are recognized by the program :
14243
14244 @table @code
14245 @item globbing patterns
14246 These are the most usual regular expression. They are the same that you
14247 generally used in a Unix shell command line, or in a DOS session.
14248
14249 Here is a more formal grammar :
14250 @smallexample
14251 @group
14252 @iftex
14253 @leftskip=.5cm
14254 @end iftex
14255 regexp ::= term
14256 term   ::= elmt            -- matches elmt
14257 term   ::= elmt elmt       -- concatenation (elmt then elmt)
14258 term   ::= *               -- any string of 0 or more characters
14259 term   ::= ?               -- matches any character
14260 term   ::= [char @{char@}] -- matches any character listed
14261 term   ::= [char - char]   -- matches any character in range
14262 @end group
14263 @end smallexample
14264
14265 @item full regular expression
14266 The second set of regular expressions is much more powerful. This is the
14267 type of regular expressions recognized by utilities such a @file{grep}.
14268
14269 The following is the form of a regular expression, expressed in Ada
14270 reference manual style BNF is as follows
14271
14272 @smallexample
14273 @iftex
14274 @leftskip=.5cm
14275 @end iftex
14276 @group
14277 regexp ::= term @{| term@} -- alternation (term or term ...)
14278
14279 term ::= item @{item@}     -- concatenation (item then item)
14280
14281 item ::= elmt              -- match elmt
14282 item ::= elmt *            -- zero or more elmt's
14283 item ::= elmt +            -- one or more elmt's
14284 item ::= elmt ?            -- matches elmt or nothing
14285 @end group
14286 @group
14287 elmt ::= nschar            -- matches given character
14288 elmt ::= [nschar @{nschar@}]   -- matches any character listed
14289 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14290 elmt ::= [char - char]     -- matches chars in given range
14291 elmt ::= \ char            -- matches given character
14292 elmt ::= .                 -- matches any single character
14293 elmt ::= ( regexp )        -- parens used for grouping
14294
14295 char ::= any character, including special characters
14296 nschar ::= any character except ()[].*+?^^^
14297 @end group
14298 @end smallexample
14299
14300 Following are a few examples :
14301
14302 @table @samp
14303 @item abcde|fghi
14304 will match any of the two strings 'abcde' and 'fghi'.
14305
14306 @item abc*d
14307 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14308
14309 @item [a-z]+
14310 will match any string which has only lowercase characters in it (and at
14311 least one character
14312
14313 @end table
14314 @end table
14315
14316 @node Examples of gnatxref Usage
14317 @section Examples of @code{gnatxref} Usage
14318
14319 @subsection General Usage
14320
14321 @noindent
14322 For the following examples, we will consider the following units :
14323
14324 @smallexample @c ada
14325 @group
14326 @cartouche
14327 main.ads:
14328 1: with Bar;
14329 2: package Main is
14330 3:     procedure Foo (B : in Integer);
14331 4:     C : Integer;
14332 5: private
14333 6:     D : Integer;
14334 7: end Main;
14335
14336 main.adb:
14337 1: package body Main is
14338 2:     procedure Foo (B : in Integer) is
14339 3:     begin
14340 4:        C := B;
14341 5:        D := B;
14342 6:        Bar.Print (B);
14343 7:        Bar.Print (C);
14344 8:     end Foo;
14345 9: end Main;
14346
14347 bar.ads:
14348 1: package Bar is
14349 2:     procedure Print (B : Integer);
14350 3: end bar;
14351 @end cartouche
14352 @end group
14353 @end smallexample
14354
14355 @table @code
14356
14357 @noindent
14358 The first thing to do is to recompile your application (for instance, in
14359 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14360 the cross-referencing information.
14361 You can then issue any of the following commands:
14362
14363 @item gnatxref main.adb
14364 @code{gnatxref} generates cross-reference information for main.adb
14365 and every unit 'with'ed by main.adb.
14366
14367 The output would be:
14368 @smallexample
14369 @iftex
14370 @leftskip=0cm
14371 @end iftex
14372 B                                                      Type: Integer
14373   Decl: bar.ads           2:22
14374 B                                                      Type: Integer
14375   Decl: main.ads          3:20
14376   Body: main.adb          2:20
14377   Ref:  main.adb          4:13     5:13     6:19
14378 Bar                                                    Type: Unit
14379   Decl: bar.ads           1:9
14380   Ref:  main.adb          6:8      7:8
14381        main.ads           1:6
14382 C                                                      Type: Integer
14383   Decl: main.ads          4:5
14384   Modi: main.adb          4:8
14385   Ref:  main.adb          7:19
14386 D                                                      Type: Integer
14387   Decl: main.ads          6:5
14388   Modi: main.adb          5:8
14389 Foo                                                    Type: Unit
14390   Decl: main.ads          3:15
14391   Body: main.adb          2:15
14392 Main                                                    Type: Unit
14393   Decl: main.ads          2:9
14394   Body: main.adb          1:14
14395 Print                                                   Type: Unit
14396   Decl: bar.ads           2:15
14397   Ref:  main.adb          6:12     7:12
14398 @end smallexample
14399
14400 @noindent
14401 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14402 its body is in main.adb, line 1, column 14 and is not referenced any where.
14403
14404 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14405 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14406
14407 @item gnatxref package1.adb package2.ads
14408 @code{gnatxref} will generates cross-reference information for
14409 package1.adb, package2.ads and any other package 'with'ed by any
14410 of these.
14411
14412 @end table
14413
14414 @ifclear vms
14415 @subsection Using gnatxref with vi
14416
14417 @code{gnatxref} can generate a tags file output, which can be used
14418 directly from @file{vi}. Note that the standard version of @file{vi}
14419 will not work properly with overloaded symbols. Consider using another
14420 free implementation of @file{vi}, such as @file{vim}.
14421
14422 @smallexample
14423 $ gnatxref -v gnatfind.adb > tags
14424 @end smallexample
14425
14426 @noindent
14427 will generate the tags file for @code{gnatfind} itself (if the sources
14428 are in the search path!).
14429
14430 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14431 (replacing @i{entity} by whatever you are looking for), and vi will
14432 display a new file with the corresponding declaration of entity.
14433 @end ifclear
14434
14435 @node Examples of gnatfind Usage
14436 @section Examples of @code{gnatfind} Usage
14437
14438 @table @code
14439
14440 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14441 Find declarations for all entities xyz referenced at least once in
14442 main.adb. The references are search in every library file in the search
14443 path.
14444
14445 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14446 switch is set)
14447
14448 The output will look like:
14449 @smallexample
14450 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14451 ^directory/^[directory]^main.adb:24:10: xyz <= body
14452 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14453 @end smallexample
14454
14455 @noindent
14456 that is to say, one of the entities xyz found in main.adb is declared at
14457 line 12 of main.ads (and its body is in main.adb), and another one is
14458 declared at line 45 of foo.ads
14459
14460 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14461 This is the same command as the previous one, instead @code{gnatfind} will
14462 display the content of the Ada source file lines.
14463
14464 The output will look like:
14465
14466 @smallexample
14467 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14468    procedure xyz;
14469 ^directory/^[directory]^main.adb:24:10: xyz <= body
14470    procedure xyz is
14471 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14472    xyz : Integer;
14473 @end smallexample
14474
14475 @noindent
14476 This can make it easier to find exactly the location your are looking
14477 for.
14478
14479 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14480 Find references to all entities containing an x that are
14481 referenced on line 123 of main.ads.
14482 The references will be searched only in main.ads and foo.adb.
14483
14484 @item gnatfind main.ads:123
14485 Find declarations and bodies for all entities that are referenced on
14486 line 123 of main.ads.
14487
14488 This is the same as @code{gnatfind "*":main.adb:123}.
14489
14490 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14491 Find the declaration for the entity referenced at column 45 in
14492 line 123 of file main.adb in directory mydir. Note that it
14493 is usual to omit the identifier name when the column is given,
14494 since the column position identifies a unique reference.
14495
14496 The column has to be the beginning of the identifier, and should not
14497 point to any character in the middle of the identifier.
14498
14499 @end table
14500
14501 @c *********************************
14502 @node The GNAT Pretty-Printer gnatpp
14503 @chapter The GNAT Pretty-Printer @command{gnatpp}
14504 @findex gnatpp
14505 @cindex Pretty-Printer
14506
14507 @noindent
14508 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14509 for source reformatting / pretty-printing.
14510 It takes an Ada source file as input and generates a reformatted
14511 version as output.
14512 You can specify various style directives via switches; e.g.,
14513 identifier case conventions, rules of indentation, and comment layout.
14514
14515 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14516 tree for the input source and thus requires the input to be syntactically and
14517 semantically legal.
14518 If this condition is not met, @command{gnatpp} will terminate with an
14519 error message; no output file will be generated.
14520
14521 If the compilation unit
14522 contained in the input source depends semantically upon units located
14523 outside the current directory, you have to provide the source search path
14524 when invoking @command{gnatpp}, if these units are contained in files with
14525 names that do not follow the GNAT file naming rules, you have to provide
14526 the configuration file describing the corresponding naming scheme;
14527 see the description of the @command{gnatpp}
14528 switches below. Another possibility is to use a project file and to
14529 call @command{gnatpp} through the @command{gnat} driver
14530
14531 The @command{gnatpp} command has the form
14532
14533 @smallexample
14534 $ gnatpp [@var{switches}] @var{filename}
14535 @end smallexample
14536
14537 @noindent
14538 where
14539 @itemize @bullet
14540 @item
14541 @var{switches} is an optional sequence of switches defining such properties as
14542 the formatting rules, the source search path, and the destination for the
14543 output source file
14544
14545 @item
14546 @var{filename} is the name (including the extension) of the source file to
14547 reformat; ``wildcards'' or several file names on the same gnatpp command are
14548 allowed.  The file name may contain path information; it does not have to
14549 follow the GNAT file naming rules
14550 @end itemize
14551
14552 @menu
14553 * Switches for gnatpp::
14554 * Formatting Rules::
14555 @end menu
14556
14557 @node Switches for gnatpp
14558 @section Switches for @command{gnatpp}
14559
14560 @noindent
14561 The following subsections describe the various switches accepted by
14562 @command{gnatpp}, organized by category.
14563
14564 @ifclear vms
14565 You specify a switch by supplying a name and generally also a value.
14566 In many cases the values for a switch with a given name are incompatible with
14567 each other
14568 (for example the switch that controls the casing of a reserved word may have
14569 exactly one value: upper case, lower case, or
14570 mixed case) and thus exactly one such switch can be in effect for an
14571 invocation of @command{gnatpp}.
14572 If more than one is supplied, the last one is used.
14573 However, some values for the same switch are mutually compatible.
14574 You may supply several such switches to @command{gnatpp}, but then
14575 each must be specified in full, with both the name and the value.
14576 Abbreviated forms (the name appearing once, followed by each value) are
14577 not permitted.
14578 For example, to set
14579 the alignment of the assignment delimiter both in declarations and in
14580 assignment statements, you must write @option{-A2A3}
14581 (or @option{-A2 -A3}), but not @option{-A23}.
14582 @end ifclear
14583
14584 @ifset vms
14585 In many cases the set of options for a given qualifier are incompatible with
14586 each other (for example the qualifier that controls the casing of a reserved
14587 word may have exactly one option, which specifies either upper case, lower
14588 case, or mixed case), and thus exactly one such option can be in effect for
14589 an invocation of @command{gnatpp}.
14590 If more than one is supplied, the last one is used.
14591 However, some qualifiers have options that are mutually compatible,
14592 and then you may then supply several such options when invoking
14593 @command{gnatpp}.
14594 @end ifset
14595
14596 In most cases, it is obvious whether or not the
14597 ^values for a switch with a given name^options for a given qualifier^
14598 are compatible with each other.
14599 When the semantics might not be evident, the summaries below explicitly
14600 indicate the effect.
14601
14602 @menu
14603 * Alignment Control::
14604 * Casing Control::
14605 * Construct Layout Control::
14606 * General Text Layout Control::
14607 * Other Formatting Options::
14608 * Setting the Source Search Path::
14609 * Output File Control::
14610 * Other gnatpp Switches::
14611 @end menu
14612
14613 @node Alignment Control
14614 @subsection Alignment Control
14615 @cindex Alignment control in @command{gnatpp}
14616
14617 @noindent
14618 Programs can be easier to read if certain constructs are vertically aligned.
14619 By default all alignments are set ON.
14620 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14621 OFF, and then use one or more of the other
14622 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14623 to activate alignment for specific constructs.
14624
14625 @table @option
14626 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14627
14628 @ifset vms
14629 @item /ALIGN=ON
14630 Set all alignments to ON
14631 @end ifset
14632
14633 @item ^-A0^/ALIGN=OFF^
14634 Set all alignments to OFF
14635
14636 @item ^-A1^/ALIGN=COLONS^
14637 Align @code{:} in declarations
14638
14639 @item ^-A2^/ALIGN=DECLARATIONS^
14640 Align @code{:=} in initializations in declarations
14641
14642 @item ^-A3^/ALIGN=STATEMENTS^
14643 Align @code{:=} in assignment statements
14644
14645 @item ^-A4^/ALIGN=ARROWS^
14646 Align @code{=>} in associations
14647
14648 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
14649 Align @code{at} keywords in the component clauses in record representation clauses
14650 @end table
14651
14652 @noindent
14653 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14654 is allowed.
14655
14656 @node Casing Control
14657 @subsection Casing Control
14658 @cindex Casing control in @command{gnatpp}
14659
14660 @noindent
14661 @command{gnatpp} allows you to specify the casing for reserved words,
14662 pragma names, attribute designators and identifiers.
14663 For identifiers you may define a
14664 general rule for name casing but also override this rule
14665 via a set of dictionary files.
14666
14667 Three types of casing are supported: lower case, upper case, and mixed case.
14668 Lower and upper case are self-explanatory (but since some letters in
14669 Latin1 and other GNAT-supported character sets
14670 exist only in lower-case form, an upper case conversion will have no
14671 effect on them.)
14672 ``Mixed case'' means that the first letter, and also each letter immediately
14673 following an underscore, are converted to their uppercase forms;
14674 all the other letters are converted to their lowercase forms.
14675
14676 @table @option
14677 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14678 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14679 Attribute designators are lower case
14680
14681 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14682 Attribute designators are upper case
14683
14684 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14685 Attribute designators are mixed case (this is the default)
14686
14687 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14688 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14689 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14690 lower case (this is the default)
14691
14692 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14693 Keywords are upper case
14694
14695 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14696 @item ^-nD^/NAME_CASING=AS_DECLARED^
14697 Name casing for defining occurrences are as they appear in the source file
14698 (this is the default)
14699
14700 @item ^-nU^/NAME_CASING=UPPER_CASE^
14701 Names are in upper case
14702
14703 @item ^-nL^/NAME_CASING=LOWER_CASE^
14704 Names are in lower case
14705
14706 @item ^-nM^/NAME_CASING=MIXED_CASE^
14707 Names are in mixed case
14708
14709 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14710 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14711 Pragma names are lower case
14712
14713 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14714 Pragma names are upper case
14715
14716 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14717 Pragma names are mixed case (this is the default)
14718
14719 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14720 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14721 Use @var{file} as a @emph{dictionary file} that defines
14722 the casing for a set of specified names,
14723 thereby overriding the effect on these names by
14724 any explicit or implicit
14725 ^-n^/NAME_CASING^ switch.
14726 To supply more than one dictionary file,
14727 use ^several @option{-D} switches^a list of files as options^.
14728
14729 @noindent
14730 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14731 to define the casing for the Ada predefined names and
14732 the names declared in the GNAT libraries.
14733
14734 @item ^-D-^/SPECIFIC_CASING^
14735 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14736 Do not use the default dictionary file;
14737 instead, use the casing
14738 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14739 dictionary file(s)
14740 @end table
14741
14742 @noindent
14743 The structure of a dictionary file, and details on the conventions
14744 used in the default dictionary file, are defined in @ref{Name Casing}.
14745
14746 The @option{^-D-^/SPECIFIC_CASING^} and
14747 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14748 compatible.
14749
14750 @node Construct Layout Control
14751 @subsection Construct Layout Control
14752 @cindex Layout control in @command{gnatpp}
14753
14754 @noindent
14755 This group of @command{gnatpp} switches controls the layout of comments and
14756 complex syntactic constructs.  See @ref{Formatting Comments} for details
14757 on their effect.
14758
14759 @table @option
14760 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14761 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14762 All the comments remain unchanged
14763
14764 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14765 GNAT-style comment line indentation (this is the default).
14766
14767 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14768 Reference-manual comment line indentation.
14769
14770 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14771 GNAT-style comment beginning
14772
14773 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14774 Reformat comment blocks
14775
14776 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14777 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14778 GNAT-style layout (this is the default)
14779
14780 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14781 Compact layout
14782
14783 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14784 Uncompact layout
14785
14786 @item ^-notab^/NOTABS^
14787 All the VT characters are removed from the comment text. All the HT characters
14788 are expanded with the sequences of space characters to get to the next tab
14789 stops.
14790
14791 @end table
14792
14793 @ifclear vms
14794 @noindent
14795 The @option{-c1} and @option{-c2} switches are incompatible.
14796 The @option{-c3} and @option{-c4} switches are compatible with each other and
14797 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14798 the other comment formatting switches.
14799
14800 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14801 @end ifclear
14802
14803 @ifset vms
14804 @noindent
14805 For the @option{/COMMENTS_LAYOUT} qualifier:
14806 @itemize @bullet
14807 @item
14808 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14809 @item
14810 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14811 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14812 @end itemize
14813
14814 @noindent
14815 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14816 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14817 @end ifset
14818
14819 @node General Text Layout Control
14820 @subsection General Text Layout Control
14821
14822 @noindent
14823 These switches allow control over line length and indentation.
14824
14825 @table @option
14826 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
14827 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14828 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
14829
14830 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
14831 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14832 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
14833
14834 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
14835 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14836 Indentation level for continuation lines (relative to the line being
14837 continued), @i{nnn} from 1 .. 9.
14838 The default
14839 value is one less then the (normal) indentation level, unless the
14840 indentation is set to 1 (in which case the default value for continuation
14841 line indentation is also 1)
14842 @end table
14843
14844 @node Other Formatting Options
14845 @subsection Other Formatting Options
14846
14847 @noindent
14848 These switches control the inclusion of missing end/exit labels, and
14849 the indentation level in @b{case} statements.
14850
14851 @table @option
14852 @item ^-e^/NO_MISSED_LABELS^
14853 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14854 Do not insert missing end/exit labels. An end label is the name of
14855 a construct that may optionally be repeated at the end of the
14856 construct's declaration;
14857 e.g., the names of packages, subprograms, and tasks.
14858 An exit label is the name of a loop that may appear as target
14859 of an exit statement within the loop.
14860 By default, @command{gnatpp} inserts these end/exit labels when
14861 they are absent from the original source. This option suppresses such
14862 insertion, so that the formatted source reflects the original.
14863
14864 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14865 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14866 Insert a Form Feed character after a pragma Page.
14867
14868 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
14869 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14870 Do not use an additional indentation level for @b{case} alternatives
14871 and variants if there are @i{nnn} or more (the default
14872 value is 10).
14873 If @i{nnn} is 0, an additional indentation level is
14874 used for @b{case} alternatives and variants regardless of their number.
14875 @end table
14876
14877 @node Setting the Source Search Path
14878 @subsection Setting the Source Search Path
14879
14880 @noindent
14881 To define the search path for the input source file, @command{gnatpp}
14882 uses the same switches as the GNAT compiler, with the same effects.
14883
14884 @table @option
14885 @item ^-I^/SEARCH=^@var{dir}
14886 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14887 The same as the corresponding gcc switch
14888
14889 @item ^-I-^/NOCURRENT_DIRECTORY^
14890 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14891 The same as the corresponding gcc switch
14892
14893 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14894 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14895 The same as the corresponding gcc switch
14896
14897 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14898 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14899 The same as the corresponding gcc switch
14900
14901 @end table
14902
14903 @node Output File Control
14904 @subsection Output File Control
14905
14906 @noindent
14907 By default the output is sent to the file whose name is obtained by appending
14908 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14909 (if the file with this name already exists, it is unconditionally overwritten).
14910 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14911 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14912 as output file.
14913 The output may be redirected by the following switches:
14914
14915 @table @option
14916 @item ^-pipe^/STANDARD_OUTPUT^
14917 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14918 Send the output to @code{Standard_Output}
14919
14920 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14921 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14922 Write the output into @var{output_file}.
14923 If @var{output_file} already exists, @command{gnatpp} terminates without
14924 reading or processing the input file.
14925
14926 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14927 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14928 Write the output into @var{output_file}, overwriting the existing file
14929 (if one is present).
14930
14931 @item ^-r^/REPLACE^
14932 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14933 Replace the input source file with the reformatted output, and copy the
14934 original input source into the file whose name is obtained by appending the
14935 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14936 If a file with this name already exists, @command{gnatpp} terminates without
14937 reading or processing the input file.
14938
14939 @item ^-rf^/OVERRIDING_REPLACE^
14940 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14941 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14942 already exists, it is overwritten.
14943
14944 @item ^-rnb^/NO_BACKUP^
14945 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
14946 Replace the input source file with the reformatted output without
14947 creating any backup copy of the input source.
14948 @end table
14949
14950 @noindent
14951 Options @option{^-pipe^/STANDARD_OUTPUT^},
14952 @option{^-o^/OUTPUT^} and
14953 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14954 contains only one file to reformat
14955
14956 @node Other gnatpp Switches
14957 @subsection Other @code{gnatpp} Switches
14958
14959 @noindent
14960 The additional @command{gnatpp} switches are defined in this subsection.
14961
14962 @table @option
14963 @item ^-files @var{filename}^/FILES=@var{output_file}^
14964 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14965 Take the argument source files from the specified file. This file should be an
14966 ordinary textual file containing file names separated by spaces or
14967 line breaks. You can use this switch more then once in the same call to
14968 @command{gnatpp}. You also can combine this switch with explicit list of
14969 files.
14970
14971 @item ^-v^/VERBOSE^
14972 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14973 Verbose mode;
14974 @command{gnatpp} generates version information and then
14975 a trace of the actions it takes to produce or obtain the ASIS tree.
14976
14977 @item ^-w^/WARNINGS^
14978 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14979 Warning mode;
14980 @command{gnatpp} generates a warning whenever it can not provide
14981 a required layout in the result source.
14982 @end table
14983
14984 @node Formatting Rules
14985 @section Formatting Rules
14986
14987 @noindent
14988 The following subsections show how @command{gnatpp} treats ``white space'',
14989 comments, program layout, and name casing.
14990 They provide the detailed descriptions of the switches shown above.
14991
14992 @menu
14993 * White Space and Empty Lines::
14994 * Formatting Comments::
14995 * Construct Layout::
14996 * Name Casing::
14997 @end menu
14998
14999 @node White Space and Empty Lines
15000 @subsection White Space and Empty Lines
15001
15002 @noindent
15003 @command{gnatpp} does not have an option to control space characters.
15004 It will add or remove spaces according to the style illustrated by the
15005 examples in the @cite{Ada Reference Manual}.
15006
15007 The only format effectors
15008 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
15009 that will appear in the output file are platform-specific line breaks,
15010 and also format effectors within (but not at the end of) comments.
15011 In particular, each horizontal tab character that is not inside
15012 a comment will be treated as a space and thus will appear in the
15013 output file as zero or more spaces depending on
15014 the reformatting of the line in which it appears.
15015 The only exception is a Form Feed character, which is inserted after a
15016 pragma @code{Page} when @option{-ff} is set.
15017
15018 The output file will contain no lines with trailing ``white space'' (spaces,
15019 format effectors).
15020
15021 Empty lines in the original source are preserved
15022 only if they separate declarations or statements.
15023 In such contexts, a
15024 sequence of two or more empty lines is replaced by exactly one empty line.
15025 Note that a blank line will be removed if it separates two ``comment blocks''
15026 (a comment block is a sequence of whole-line comments).
15027 In order to preserve a visual separation between comment blocks, use an
15028 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
15029 Likewise, if for some reason you wish to have a sequence of empty lines,
15030 use a sequence of empty comments instead.
15031
15032 @node Formatting Comments
15033 @subsection Formatting Comments
15034
15035 @noindent
15036 Comments in Ada code are of two kinds:
15037 @itemize @bullet
15038 @item
15039 a @emph{whole-line comment}, which appears by itself (possibly preceded by
15040 ``white space'') on a line
15041
15042 @item
15043 an @emph{end-of-line comment}, which follows some other Ada lexical element
15044 on the same line.
15045 @end itemize
15046
15047 @noindent
15048 The indentation of a whole-line comment is that of either
15049 the preceding or following line in
15050 the formatted source, depending on switch settings as will be described below.
15051
15052 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
15053 between the end of the preceding Ada lexical element and the beginning
15054 of the comment as appear in the original source,
15055 unless either the comment has to be split to
15056 satisfy the line length limitation, or else the next line contains a
15057 whole line comment that is considered a continuation of this end-of-line
15058 comment (because it starts at the same position).
15059 In the latter two
15060 cases, the start of the end-of-line comment is moved right to the nearest
15061 multiple of the indentation level.
15062 This may result in a ``line overflow'' (the right-shifted comment extending
15063 beyond the maximum line length), in which case the comment is split as
15064 described below.
15065
15066 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15067 (GNAT-style comment line indentation)
15068 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15069 (reference-manual comment line indentation).
15070 With reference-manual style, a whole-line comment is indented as if it
15071 were a declaration or statement at the same place
15072 (i.e., according to the indentation of the preceding line(s)).
15073 With GNAT style, a whole-line comment that is immediately followed by an
15074 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15075 word @b{begin}, is indented based on the construct that follows it.
15076
15077 For example:
15078 @smallexample @c ada
15079 @cartouche
15080 if A then
15081     null;
15082        -- some comment
15083 else
15084    null;
15085 end if;
15086 @end cartouche
15087 @end smallexample
15088
15089 @noindent
15090 Reference-manual indentation produces:
15091
15092 @smallexample @c ada
15093 @cartouche
15094 if A then
15095    null;
15096    --  some comment
15097 else
15098    null;
15099 end if;
15100 @end cartouche
15101 @end smallexample
15102
15103 @noindent
15104 while GNAT-style indentation produces:
15105
15106 @smallexample @c ada
15107 @cartouche
15108 if A then
15109    null;
15110 --  some comment
15111 else
15112    null;
15113 end if;
15114 @end cartouche
15115 @end smallexample
15116
15117 @noindent
15118 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15119 (GNAT style comment beginning) has the following
15120 effect:
15121
15122 @itemize @bullet
15123 @item
15124 For each whole-line comment that does not end with two hyphens,
15125 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15126 to ensure that there are at least two spaces between these hyphens and the
15127 first non-blank character of the comment.
15128 @end itemize
15129
15130 @noindent
15131 For an end-of-line comment, if in the original source the next line is a
15132 whole-line comment that starts at the same position
15133 as the end-of-line comment,
15134 then the whole-line comment (and all whole-line comments
15135 that follow it and that start at the same position)
15136 will start at this position in the output file.
15137
15138 @noindent
15139 That is, if in the original source we have:
15140
15141 @smallexample @c ada
15142 @cartouche
15143 begin
15144 A := B + C;            --  B must be in the range Low1..High1
15145                        --  C must be in the range Low2..High2
15146              --B+C will be in the range Low1+Low2..High1+High2
15147 X := X + 1;
15148 @end cartouche
15149 @end smallexample
15150
15151 @noindent
15152 Then in the formatted source we get
15153
15154 @smallexample @c ada
15155 @cartouche
15156 begin
15157    A := B + C;            --  B must be in the range Low1..High1
15158                           --  C must be in the range Low2..High2
15159    --  B+C will be in the range Low1+Low2..High1+High2
15160    X := X + 1;
15161 @end cartouche
15162 @end smallexample
15163
15164 @noindent
15165 A comment that exceeds the line length limit will be split.
15166 Unless switch
15167 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15168 the line belongs to a reformattable block, splitting the line generates a
15169 @command{gnatpp} warning.
15170 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15171 comments may be reformatted in typical
15172 word processor style (that is, moving words between lines and putting as
15173 many words in a line as possible).
15174
15175 @node Construct Layout
15176 @subsection Construct Layout
15177
15178 @noindent
15179 In several cases the suggested layout in the Ada Reference Manual includes
15180 an extra level of indentation that many programmers prefer to avoid. The
15181 affected cases include:
15182
15183 @itemize @bullet
15184
15185 @item Record type declaration (RM 3.8)
15186
15187 @item Record representation clause (RM 13.5.1)
15188
15189 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
15190
15191 @item Block statement in case if a block has a statement identifier (RM 5.6)
15192 @end itemize
15193
15194 @noindent
15195 In compact mode (when GNAT style layout or compact layout is set),
15196 the pretty printer uses one level of indentation instead
15197 of two. This is achived in the record definition and record representation
15198 clause cases by putting the @code{record} keyword on the same line as the
15199 start of the declaration or representation clause, and in the block and loop
15200 case by putting the block or loop header on the same line as the statement
15201 identifier.
15202
15203 @noindent
15204 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15205 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15206 layout on the one hand, and uncompact layout
15207 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15208 can be illustrated by the following examples:
15209
15210 @iftex
15211 @cartouche
15212 @multitable @columnfractions .5 .5
15213 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15214
15215 @item
15216 @smallexample @c ada
15217 type q is record
15218    a : integer;
15219    b : integer;
15220 end record;
15221 @end smallexample
15222 @tab
15223 @smallexample @c ada
15224 type q is
15225    record
15226       a : integer;
15227       b : integer;
15228    end record;
15229 @end smallexample
15230
15231 @item
15232 @smallexample @c ada
15233 for q use record
15234    a at 0 range  0 .. 31;
15235    b at 4 range  0 .. 31;
15236 end record;
15237 @end smallexample
15238 @tab
15239 @smallexample @c ada
15240 for q use
15241    record
15242       a at 0 range  0 .. 31;
15243       b at 4 range  0 .. 31;
15244    end record;
15245 @end smallexample
15246
15247 @item
15248 @smallexample @c ada
15249 Block : declare
15250    A : Integer := 3;
15251 begin
15252    Proc (A, A);
15253 end Block;
15254 @end smallexample
15255 @tab
15256 @smallexample @c ada
15257 Block :
15258    declare
15259       A : Integer := 3;
15260    begin
15261       Proc (A, A);
15262    end Block;
15263 @end smallexample
15264
15265 @item
15266 @smallexample @c ada
15267 Clear : for J in 1 .. 10 loop
15268    A (J) := 0;
15269 end loop Clear;
15270 @end smallexample
15271 @tab
15272 @smallexample @c ada
15273 Clear :
15274    for J in 1 .. 10 loop
15275       A (J) := 0;
15276    end loop Clear;
15277 @end smallexample
15278 @end multitable
15279 @end cartouche
15280 @end iftex
15281
15282 @ifnottex
15283 @smallexample
15284 @cartouche
15285 GNAT style, compact layout              Uncompact layout
15286
15287 type q is record                        type q is
15288    a : integer;                            record
15289    b : integer;                               a : integer;
15290 end record;                                   b : integer;
15291                                            end record;
15292
15293 for q use record                        for q use
15294    a at 0 range  0 .. 31;                  record
15295    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
15296 end record;                                   b at 4 range  0 .. 31;
15297                                            end record;
15298
15299 Block : declare                         Block :
15300    A : Integer := 3;                       declare
15301 begin                                         A : Integer := 3;
15302    Proc (A, A);                            begin
15303 end Block;                                    Proc (A, A);
15304                                            end Block;
15305
15306 Clear : for J in 1 .. 10 loop           Clear :
15307    A (J) := 0;                             for J in 1 .. 10 loop
15308 end loop Clear;                               A (J) := 0;
15309                                            end loop Clear;
15310 @end cartouche
15311 @end smallexample
15312 @end ifnottex
15313
15314 @noindent
15315 A further difference between GNAT style layout and compact layout is that
15316 GNAT style layout inserts empty lines as separation for
15317 compound statements, return statements and bodies.
15318
15319 @node Name Casing
15320 @subsection Name Casing
15321
15322 @noindent
15323 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15324 the same casing as the corresponding defining identifier.
15325
15326 You control the casing for defining occurrences via the
15327 @option{^-n^/NAME_CASING^} switch.
15328 @ifclear vms
15329 With @option{-nD} (``as declared'', which is the default),
15330 @end ifclear
15331 @ifset vms
15332 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15333 @end ifset
15334 defining occurrences appear exactly as in the source file
15335 where they are declared.
15336 The other ^values for this switch^options for this qualifier^ ---
15337 @option{^-nU^UPPER_CASE^},
15338 @option{^-nL^LOWER_CASE^},
15339 @option{^-nM^MIXED_CASE^} ---
15340 result in
15341 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15342 If @command{gnatpp} changes the casing of a defining
15343 occurrence, it analogously changes the casing of all the
15344 usage occurrences of this name.
15345
15346 If the defining occurrence of a name is not in the source compilation unit
15347 currently being processed by @command{gnatpp}, the casing of each reference to
15348 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15349 switch (subject to the dictionary file mechanism described below).
15350 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15351 had affected the
15352 casing for the defining occurrence of the name.
15353
15354 Some names may need to be spelled with casing conventions that are not
15355 covered by the upper-, lower-, and mixed-case transformations.
15356 You can arrange correct casing by placing such names in a
15357 @emph{dictionary file},
15358 and then supplying a @option{^-D^/DICTIONARY^} switch.
15359 The casing of names from dictionary files overrides
15360 any @option{^-n^/NAME_CASING^} switch.
15361
15362 To handle the casing of Ada predefined names and the names from GNAT libraries,
15363 @command{gnatpp} assumes a default dictionary file.
15364 The name of each predefined entity is spelled with the same casing as is used
15365 for the entity in the @cite{Ada Reference Manual}.
15366 The name of each entity in the GNAT libraries is spelled with the same casing
15367 as is used in the declaration of that entity.
15368
15369 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15370 default dictionary file.
15371 Instead, the casing for predefined and GNAT-defined names will be established
15372 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15373 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15374 will appear as just shown,
15375 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15376 To ensure that even such names are rendered in uppercase,
15377 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15378 (or else, less conveniently, place these names in upper case in a dictionary
15379 file).
15380
15381 A dictionary file is
15382 a plain text file; each line in this file can be either a blank line
15383 (containing only space characters and ASCII.HT characters), an Ada comment
15384 line, or the specification of exactly one @emph{casing schema}.
15385
15386 A casing schema is a string that has the following syntax:
15387
15388 @smallexample
15389 @cartouche
15390   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
15391
15392   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15393 @end cartouche
15394 @end smallexample
15395
15396 @noindent
15397 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15398 @var{identifier} lexical element and the @var{letter_or_digit} category.)
15399
15400 The casing schema string can be followed by white space and/or an Ada-style
15401 comment; any amount of white space is allowed before the string.
15402
15403 If a dictionary file is passed as
15404 @ifclear vms
15405 the value of a @option{-D@var{file}} switch
15406 @end ifclear
15407 @ifset vms
15408 an option to the @option{/DICTIONARY} qualifier
15409 @end ifset
15410 then for every
15411 simple name and every identifier, @command{gnatpp} checks if the dictionary
15412 defines the casing for the name or for some of its parts (the term ``subword''
15413 is used below to denote the part of a name which is delimited by ``_'' or by
15414 the beginning or end of the word and which does not contain any ``_'' inside):
15415
15416 @itemize @bullet
15417 @item
15418 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15419 the casing defined by the dictionary; no subwords are checked for this word
15420
15421 @item
15422 for every subword @command{gnatpp} checks if the dictionary contains the
15423 corresponding string of the form @code{*@var{simple_identifier}*}, and if it does, the
15424 casing of this @var{simple_identifier} is used for this subword
15425
15426 @item
15427 if the whole name does not contain any ``_'' inside, and if for this name
15428 the dictionaty contains two entries - one of the form @var{identifier},
15429 and another - of the form *@var{simple_identifier}*, then the first one
15430 is applied to define the casing of this name
15431
15432 @item
15433 if more than one dictionary file is passed as @command{gnatpp} switches, each
15434 dictionary adds new casing exceptions and overrides all the existing casing
15435 exceptions set by the previous dictionaries
15436
15437 @item
15438 when @command{gnatpp} checks if the word or subword is in the dictionary,
15439 this check is not case sensitive
15440 @end itemize
15441
15442 @noindent
15443 For example, suppose we have the following source to reformat:
15444
15445 @smallexample @c ada
15446 @cartouche
15447 procedure test is
15448    name1 : integer := 1;
15449    name4_name3_name2 : integer := 2;
15450    name2_name3_name4 : Boolean;
15451    name1_var : Float;
15452 begin
15453    name2_name3_name4 := name4_name3_name2 > name1;
15454 end;
15455 @end cartouche
15456 @end smallexample
15457
15458 @noindent
15459 And suppose we have two dictionaries:
15460
15461 @smallexample
15462 @cartouche
15463 @i{dict1:}
15464    NAME1
15465    *NaMe3*
15466    *Name1*
15467 @end cartouche
15468
15469 @cartouche
15470 @i{dict2:}
15471   *NAME3*
15472 @end cartouche
15473 @end smallexample
15474
15475 @noindent
15476 If @command{gnatpp} is called with the following switches:
15477
15478 @smallexample
15479 @ifclear vms
15480 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15481 @end ifclear
15482 @ifset vms
15483 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15484 @end ifset
15485 @end smallexample
15486
15487 @noindent
15488 then we will get the following name casing in the @command{gnatpp} output:
15489
15490 @smallexample @c ada
15491 @cartouche
15492 procedure Test is
15493    NAME1             : Integer := 1;
15494    Name4_NAME3_Name2 : Integer := 2;
15495    Name2_NAME3_Name4 : Boolean;
15496    Name1_Var         : Float;
15497 begin
15498    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
15499 end Test;
15500 @end cartouche
15501 @end smallexample
15502
15503 @c *********************************
15504 @node The GNAT Metric Tool gnatmetric
15505 @chapter The GNAT Metric Tool @command{gnatmetric}
15506 @findex gnatmetric
15507 @cindex Metric tool
15508
15509 @noindent
15510 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15511 for computing various program metrics.
15512 It takes an Ada source file as input and generates a file containing the
15513 metrics data as output. Various switches control which
15514 metrics are computed and output.
15515
15516 @command{gnatmetric} generates and uses the ASIS
15517 tree for the input source and thus requires the input to be syntactically and
15518 semantically legal.
15519 If this condition is not met, @command{gnatmetric} will generate
15520 an error message; no metric information for this file will be
15521 computed and reported.
15522
15523 If the compilation unit contained in the input source depends semantically
15524 upon units in files located outside the current directory, you have to provide
15525 the source search path when invoking @command{gnatmetric}.
15526 If it depends semantically upon units that are contained
15527 in files with names that do not follow the GNAT file naming rules, you have to
15528 provide the configuration file describing the corresponding naming scheme; see
15529 the description of the @command{gnatmetric} switches below.
15530 Alternatively, you may use a project file and invoke @command{gnatmetric}
15531 through the @command{gnat} driver.
15532
15533
15534 The @command{gnatmetric} command has the form
15535
15536 @smallexample
15537 $ gnatmetric [@i{switches}] @{@i{filename}@} [@i{-cargs gcc_switches}]
15538 @end smallexample
15539
15540 @noindent
15541 where
15542 @itemize @bullet
15543 @item
15544 @i{switches} specify the metrics to compute and define the destination for
15545 the output
15546
15547 @item
15548 Each @i{filename} is the name (including the extension) of a source
15549 file to process. ``Wildcards'' are allowed, and
15550 the file name may contain path information.
15551 If no @i{filename} is supplied, then the @i{switches} list must contain
15552 at least one
15553 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15554 Including both a @option{-files} switch and one or more
15555 @i{filename} arguments is permitted.
15556
15557 @item
15558 @i{-cargs gcc_switches} is a list of switches for
15559 @command{gcc}. They will be passed on to all compiler invocations made by
15560 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15561 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15562 and use the @option{-gnatec} switch to set the configuration file.
15563 @end itemize
15564
15565 @menu
15566 * Switches for gnatmetric::
15567 @end menu
15568
15569 @node Switches for gnatmetric
15570 @section Switches for @command{gnatmetric}
15571
15572 @noindent
15573 The following subsections describe the various switches accepted by
15574 @command{gnatmetric}, organized by category.
15575
15576 @menu
15577 * Output Files Control::
15578 * Disable Metrics For Local Units::
15579 * Line Metrics Control::
15580 * Syntax Metrics Control::
15581 * Complexity Metrics Control::
15582 * Other gnatmetric Switches::
15583 @end menu
15584
15585 @node Output Files Control
15586 @subsection Output File Control
15587 @cindex Output file control in @command{gnatmetric}
15588
15589 @noindent
15590 @command{gnatmetric} has two output formats. It can generate a
15591 textual (human-readable) form, and also XML. By default only textual
15592 output is generated.
15593
15594 When generating the output in textual form, @command{gnatmetric} creates
15595 for each Ada source file a corresponding text file
15596 containing the computed metrics. By default, this file
15597 is placed in the same directory as where the source file is located, and
15598 its name is obtained
15599 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
15600 input file.
15601
15602 All the output information generated in XML format is placed in a single
15603 file. By default this file is placed in the current directory and has the
15604 name ^@file{metrix.xml}^@file{METRIX$XML}^.
15605
15606 Some of the computed metrics are summed over the units passed to
15607 @command{gnatmetric}; for example, the total number of lines of code.
15608 By default this information is sent to @file{stdout}, but a file
15609 can be specified with the @option{-og} switch.
15610
15611 The following switches control the @command{gnatmetric} output:
15612
15613 @table @option
15614 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15615 @item ^-x^/XML^
15616 Generate the XML output
15617
15618 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15619 @item ^-nt^/NO_TEXT^
15620 Do not generate the output in text form (implies @option{^-x^/XML^})
15621
15622 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15623 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15624 Put textual files with detailed metrics into @var{output_dir}
15625
15626 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15627 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15628 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15629 in the name of the output file.
15630
15631 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15632 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15633 Put global metrics into @var{file_name}
15634
15635 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15636 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15637 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15638
15639 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15640 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15641 Use ``short'' source file names in the output.  (The @command{gnatmetric}
15642 output includes the name(s) of the Ada source file(s) from which the metrics
15643 are computed.  By default each name includes the absolute path. The
15644 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15645 to exclude all directory information from the file names that are output.)
15646
15647 @end table
15648
15649 @node Disable Metrics For Local Units
15650 @subsection Disable Metrics For Local Units
15651 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15652
15653 @noindent
15654 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15655 one compilation
15656 unit per one source file. It computes line metrics for the whole source
15657 file, and it also computes syntax
15658 and complexity metrics for the file's outermost unit.
15659
15660 By default, @command{gnatmetric} will also compute all metrics for certain
15661 kinds of locally declared program units:
15662
15663 @itemize @bullet
15664 @item
15665 subprogram (and generic subprogram) bodies;
15666
15667 @item
15668 package (and generic package) specifications and bodies;
15669
15670 @item
15671 task object and type specifications and bodies;
15672
15673 @item
15674 protected object and type specifications and bodies.
15675 @end itemize
15676
15677 @noindent
15678 These kinds of entities will be referred to as
15679 @emph{eligible local program units}, or simply @emph{eligible local units},
15680 @cindex Eligible local unit (for @command{gnatmetric})
15681 in the discussion below.
15682
15683 Note that a subprogram declaration, generic instantiation,
15684 or renaming declaration only receives metrics
15685 computation when it appear as the outermost entity
15686 in a source file.
15687
15688 Suppression of metrics computation for eligible local units can be
15689 obtained via the following switch:
15690
15691 @table @option
15692 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15693 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15694 Do not compute detailed metrics for eligible local program units
15695
15696 @end table
15697
15698 @node Line Metrics Control
15699 @subsection Line Metrics Control
15700 @cindex Line metrics control in @command{gnatmetric}
15701
15702 @noindent
15703 For any (legal) source file, and for each of its
15704 eligible local program units, @command{gnatmetric} computes the following
15705 metrics:
15706
15707 @itemize @bullet
15708 @item
15709 the total number of lines;
15710
15711 @item
15712 the total number of code lines (i.e., non-blank lines that are not comments)
15713
15714 @item
15715 the number of comment lines
15716
15717 @item
15718 the number of code lines containing end-of-line comments;
15719
15720 @item
15721 the number of empty lines and lines containing only space characters and/or
15722 format effectors (blank lines)
15723
15724 @end itemize
15725
15726 If @command{gnatmetric} is invoked on more than one source file, it sums the
15727 values of the line metrics for all the files being processed and then
15728 generates the cumulative results.
15729
15730 By default, all the line metrics are computed and reported. You can use the
15731 following switches to select the specific line metrics to be computed and
15732 reported (if any of these parameters is set, only explicitly specified line
15733 metrics are computed).
15734
15735 @table @option
15736 @cindex @option{^-la^/LINES_ALL^} (@command{gnatmetric})
15737 @item ^-la^/LINES_ALL^
15738 The number of all lines
15739
15740 @cindex @option{^-lcode^/CODE_LINES^} (@command{gnatmetric})
15741 @item ^-lcode^/CODE_LINES^
15742 The number of code lines
15743
15744 @cindex @option{^-lcomm^/COMENT_LINES^} (@command{gnatmetric})
15745 @item ^-lcomm^/COMENT_LINES^
15746 The number of comment lines
15747
15748 @cindex @option{^-leol^/MIXED_CODE_COMMENTS^} (@command{gnatmetric})
15749 @item ^-leol^/MIXED_CODE_COMMENTS^
15750 The number of code lines containing
15751 end-of-line comments
15752
15753 @cindex @option{^-lb^/BLANK_LINES^} (@command{gnatmetric})
15754 @item ^-lb^/BLANK_LINES^
15755 The number of blank lines
15756
15757 @end table
15758
15759
15760 @node Syntax Metrics Control
15761 @subsection Syntax Metrics Control
15762 @cindex Syntax metrics control in @command{gnatmetric}
15763
15764 @noindent
15765 @command{gnatmetric} computes various syntactic metrics for the
15766 outermost unit and for each eligible local unit:
15767
15768 @table @emph
15769 @item LSLOC (``Logical Source Lines Of Code'')
15770 The total number of declarations and the total number of statements
15771
15772 @item Maximal static nesting level of inner program units
15773 According to
15774 @cite{Ada 95 Language Reference Manual}, 10.1(1), ``A program unit is either a
15775 package, a task unit, a protected unit, a
15776 protected entry, a generic unit, or an explicitly declared subprogram other
15777 than an enumeration literal.''
15778
15779 @item Maximal nesting level of composite syntactic constructs
15780 This corresponds to the notion of the
15781 maximum nesting level in the GNAT built-in style checks
15782 (@pxref{Style Checking})
15783 @end table
15784
15785 @noindent
15786 For the outermost unit in the file, @command{gnatmetric} additionally computes
15787 the following metrics:
15788
15789 @table @emph
15790 @item Public subprograms
15791 This metric is computed for package specifications. It is the
15792 number of subprograms and generic subprograms declared in the visible
15793 part (including in nested packages, protected objects, and
15794 protected types).
15795
15796 @item All subprograms
15797 This metric is computed for bodies and subunits. The
15798 metric is equal to a total number of subprogram bodies in the compilation
15799 unit.
15800 Neither generic instantiations nor renamings-as-a-body nor body stubs
15801 are counted. Any subprogram body is counted, independently of its nesting
15802 level and enclosing constructs. Generic bodies and bodies of protected
15803 subprograms are counted in the same way as ``usual'' subprogram bodies.
15804
15805 @item Public types
15806 This metric is computed for package specifications and
15807 generic package declarations. It is the total number of types
15808 that can be referenced from outside this compilation unit, plus the
15809 number of types from all the visible parts of all the visible generic packages.
15810 Generic formal types are not counted.  Only types, not subtypes,
15811 are included.
15812
15813 @noindent
15814 Along with the total number of public types, the following
15815 types are counted and reported separately:
15816
15817 @itemize @bullet
15818 @item
15819 Abstract types
15820
15821 @item
15822 Root tagged types (abstract, non-abstract, private, non-private). Type
15823 extensions are @emph{not} counted
15824
15825 @item
15826 Private types (including private extensions)
15827
15828 @item
15829 Task types
15830
15831 @item
15832 Protected types
15833
15834 @end itemize
15835
15836 @item All types
15837 This metric is computed for any compilation unit. It is equal to the total
15838 number of the declarations of different types given in the compilation unit.
15839 The private and the corresponding full type declaration are counted as one
15840 type declaration. Incomplete type declarations and generic formal types
15841 are not counted.
15842 No distinction is made among different kinds of types (abstract,
15843 private etc.); the total number of types is computed and reported.
15844
15845 @end table
15846
15847 @noindent
15848 By default, all the syntax metrics are computed and reported. You can use the
15849 following switches to select specific syntax metrics;
15850 if any of these is set, only the explicitly specified metrics are computed.
15851
15852 @table @option
15853 @cindex @option{^-ed^/DECLARATION_TOTAL^} (@command{gnatmetric})
15854 @item ^-ed^/DECLARATION_TOTAL^
15855 The total number of declarations
15856
15857 @cindex @option{^-es^/STATEMENT_TOTAL^} (@command{gnatmetric})
15858 @item ^-es^/STATEMENT_TOTAL^
15859 The total number of statements
15860
15861 @cindex @option{^-eps^/^} (@command{gnatmetric})
15862 @item ^-eps^/INT_SUBPROGRAMS^
15863 The number of public subprograms in a compilation unit
15864
15865 @cindex @option{^-eas^/SUBPROGRAMS_ALL^} (@command{gnatmetric})
15866 @item ^-eas^/SUBPROGRAMS_ALL^
15867 The number of all the subprograms in a compilation unit
15868
15869 @cindex @option{^-ept^/INT_TYPES^} (@command{gnatmetric})
15870 @item ^-ept^/INT_TYPES^
15871 The number of public types in a compilation unit
15872
15873 @cindex @option{^-eat^/TYPES_ALL^} (@command{gnatmetric})
15874 @item ^-eat^/TYPES_ALL^
15875 The number of all the types in a compilation unit
15876
15877 @cindex @option{^-enu^/PROGRAM_NESTING_MAX^} (@command{gnatmetric})
15878 @item ^-enu^/PROGRAM_NESTING_MAX^
15879 The maximal program unit nesting level
15880
15881 @cindex @option{^-ec^/CONSTRUCT_NESTING_MAX^} (@command{gnatmetric})
15882 @item ^-ec^/CONSTRUCT_NESTING_MAX^
15883 The maximal construct nesting level
15884
15885 @end table
15886
15887 @node Complexity Metrics Control
15888 @subsection Complexity Metrics Control
15889 @cindex Complexity metrics control in @command{gnatmetric}
15890
15891 @noindent
15892 For a program unit that is an executable body (a subprogram body (including
15893 generic bodies), task body, entry body or a package body containing
15894 its own statement sequence ) @command{gnatmetric} computes the following
15895 complexity metrics:
15896
15897 @itemize @bullet
15898 @item
15899 McCabe cyclomatic complexity;
15900
15901 @item
15902 McCabe essential complexity;
15903
15904 @item
15905 maximal loop nesting level
15906
15907 @end itemize
15908
15909 @noindent
15910 The McCabe complexity metrics are defined
15911 in @url{www.mccabe.com/pdf/nist235r.pdf}
15912
15913 According to McCabe, both control statements and short-circuit control forms
15914 should be taken into account when computing cyclomatic complexity. For each
15915 body, we compute three metric values:
15916
15917 @itemize @bullet
15918 @item
15919 the complexity introduced by control
15920 statements only, without taking into account short-circuit forms,
15921
15922 @item
15923 the complexity introduced by short-circuit control forms only, and
15924
15925 @item
15926 the total
15927 cyclomatic complexity, which is the sum of these two values.
15928 @end itemize
15929
15930 @noindent
15931 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
15932 the code in the exception handlers and in all the nested program units.
15933
15934 By default, all the complexity metrics are computed and reported.
15935 For more finely-grained control you can use
15936 the following switches:
15937
15938 @table @option
15939 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15940
15941 @item ^-nocc^/SUPPRESS=CYCLOMATIC_COMPLEXITY^
15942 Do not compute the McCabe Cyclomatic Complexity
15943
15944 @item ^-noec^/SUPPRESS=ESSENTIAL_COMPLEXITY^
15945 Do not compute the Essential Complexity
15946
15947 @item ^-nonl^/SUPPRESS=MAXIMAL_LOOP_NESTING^
15948 Do not compute maximal loop nesting level
15949
15950 @item ^-ne^/SUPPRESS=EXITS_AS_GOTOS^
15951 Do not consider @code{exit} statements as @code{goto}s when
15952 computing Essential Complexity
15953
15954 @end table
15955
15956 @node Other gnatmetric Switches
15957 @subsection Other @code{gnatmetric} Switches
15958
15959 @noindent
15960 Additional @command{gnatmetric} switches are as follows:
15961
15962 @table @option
15963 @item ^-files @var{filename}^/FILES=@var{filename}^
15964 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
15965 Take the argument source files from the specified file. This file should be an
15966 ordinary textual file containing file names separated by spaces or
15967 line breaks. You can use this switch more then once in the same call to
15968 @command{gnatmetric}. You also can combine this switch with
15969 an explicit list of files.
15970
15971 @item ^-v^/VERBOSE^
15972 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
15973 Verbose mode;
15974 @command{gnatmetric} generates version information and then
15975 a trace of sources being procesed.
15976
15977 @item ^-dv^/DEBUG_OUTPUT^
15978 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
15979 Debug mode;
15980 @command{gnatmetric} generates various messages useful to understand what
15981 happens during the metrics computation
15982
15983 @item ^-q^/QUIET^
15984 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
15985 Quiet mode.
15986 @end table
15987
15988 @c ***********************************
15989 @node File Name Krunching Using gnatkr
15990 @chapter File Name Krunching Using @code{gnatkr}
15991 @findex gnatkr
15992
15993 @noindent
15994 This chapter discusses the method used by the compiler to shorten
15995 the default file names chosen for Ada units so that they do not
15996 exceed the maximum length permitted. It also describes the
15997 @code{gnatkr} utility that can be used to determine the result of
15998 applying this shortening.
15999 @menu
16000 * About gnatkr::
16001 * Using gnatkr::
16002 * Krunching Method::
16003 * Examples of gnatkr Usage::
16004 @end menu
16005
16006 @node About gnatkr
16007 @section About @code{gnatkr}
16008
16009 @noindent
16010 The default file naming rule in GNAT
16011 is that the file name must be derived from
16012 the unit name. The exact default rule is as follows:
16013 @itemize @bullet
16014 @item
16015 Take the unit name and replace all dots by hyphens.
16016 @item
16017 If such a replacement occurs in the
16018 second character position of a name, and the first character is
16019 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
16020 ^~ (tilde)^$ (dollar sign)^
16021 instead of a minus.
16022 @end itemize
16023 The reason for this exception is to avoid clashes
16024 with the standard names for children of System, Ada, Interfaces,
16025 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
16026 respectively.
16027
16028 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16029 switch of the compiler activates a ``krunching''
16030 circuit that limits file names to nn characters (where nn is a decimal
16031 integer). For example, using OpenVMS,
16032 where the maximum file name length is
16033 39, the value of nn is usually set to 39, but if you want to generate
16034 a set of files that would be usable if ported to a system with some
16035 different maximum file length, then a different value can be specified.
16036 The default value of 39 for OpenVMS need not be specified.
16037
16038 The @code{gnatkr} utility can be used to determine the krunched name for
16039 a given file, when krunched to a specified maximum length.
16040
16041 @node Using gnatkr
16042 @section Using @code{gnatkr}
16043
16044 @noindent
16045 The @code{gnatkr} command has the form
16046
16047 @ifclear vms
16048 @smallexample
16049 $ gnatkr @var{name} [@var{length}]
16050 @end smallexample
16051 @end ifclear
16052
16053 @ifset vms
16054 @smallexample
16055 $ gnatkr @var{name} /COUNT=nn
16056 @end smallexample
16057 @end ifset
16058
16059 @noindent
16060 @var{name} is the uncrunched file name, derived from the name of the unit
16061 in the standard manner described in the previous section (i.e. in particular
16062 all dots are replaced by hyphens). The file name may or may not have an
16063 extension (defined as a suffix of the form period followed by arbitrary
16064 characters other than period). If an extension is present then it will
16065 be preserved in the output. For example, when krunching @file{hellofile.ads}
16066 to eight characters, the result will be hellofil.ads.
16067
16068 Note: for compatibility with previous versions of @code{gnatkr} dots may
16069 appear in the name instead of hyphens, but the last dot will always be
16070 taken as the start of an extension. So if @code{gnatkr} is given an argument
16071 such as @file{Hello.World.adb} it will be treated exactly as if the first
16072 period had been a hyphen, and for example krunching to eight characters
16073 gives the result @file{hellworl.adb}.
16074
16075 Note that the result is always all lower case (except on OpenVMS where it is
16076 all upper case). Characters of the other case are folded as required.
16077
16078 @var{length} represents the length of the krunched name. The default
16079 when no argument is given is ^8^39^ characters. A length of zero stands for
16080 unlimited, in other words do not chop except for system files where the
16081 impled crunching length is always eight characters.
16082
16083 @noindent
16084 The output is the krunched name. The output has an extension only if the
16085 original argument was a file name with an extension.
16086
16087 @node Krunching Method
16088 @section Krunching Method
16089
16090 @noindent
16091 The initial file name is determined by the name of the unit that the file
16092 contains. The name is formed by taking the full expanded name of the
16093 unit and replacing the separating dots with hyphens and
16094 using ^lowercase^uppercase^
16095 for all letters, except that a hyphen in the second character position is
16096 replaced by a ^tilde^dollar sign^ if the first character is
16097 ^a, i, g, or s^A, I, G, or S^.
16098 The extension is @code{.ads} for a
16099 specification and @code{.adb} for a body.
16100 Krunching does not affect the extension, but the file name is shortened to
16101 the specified length by following these rules:
16102
16103 @itemize @bullet
16104 @item
16105 The name is divided into segments separated by hyphens, tildes or
16106 underscores and all hyphens, tildes, and underscores are
16107 eliminated. If this leaves the name short enough, we are done.
16108
16109 @item
16110 If the name is too long, the longest segment is located (left-most
16111 if there are two of equal length), and shortened by dropping
16112 its last character. This is repeated until the name is short enough.
16113
16114 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16115 to fit the name into 8 characters as required by some operating systems.
16116
16117 @smallexample
16118 our-strings-wide_fixed 22
16119 our strings wide fixed 19
16120 our string  wide fixed 18
16121 our strin   wide fixed 17
16122 our stri    wide fixed 16
16123 our stri    wide fixe  15
16124 our str     wide fixe  14
16125 our str     wid  fixe  13
16126 our str     wid  fix   12
16127 ou  str     wid  fix   11
16128 ou  st      wid  fix   10
16129 ou  st      wi   fix   9
16130 ou  st      wi   fi    8
16131 Final file name: oustwifi.adb
16132 @end smallexample
16133
16134 @item
16135 The file names for all predefined units are always krunched to eight
16136 characters. The krunching of these predefined units uses the following
16137 special prefix replacements:
16138
16139 @table @file
16140 @item ada-
16141 replaced by @file{^a^A^-}
16142
16143 @item gnat-
16144 replaced by @file{^g^G^-}
16145
16146 @item interfaces-
16147 replaced by @file{^i^I^-}
16148
16149 @item system-
16150 replaced by @file{^s^S^-}
16151 @end table
16152
16153 These system files have a hyphen in the second character position. That
16154 is why normal user files replace such a character with a
16155 ^tilde^dollar sign^, to
16156 avoid confusion with system file names.
16157
16158 As an example of this special rule, consider
16159 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16160
16161 @smallexample
16162 ada-strings-wide_fixed 22
16163 a-  strings wide fixed 18
16164 a-  string  wide fixed 17
16165 a-  strin   wide fixed 16
16166 a-  stri    wide fixed 15
16167 a-  stri    wide fixe  14
16168 a-  str     wide fixe  13
16169 a-  str     wid  fixe  12
16170 a-  str     wid  fix   11
16171 a-  st      wid  fix   10
16172 a-  st      wi   fix   9
16173 a-  st      wi   fi    8
16174 Final file name: a-stwifi.adb
16175 @end smallexample
16176 @end itemize
16177
16178 Of course no file shortening algorithm can guarantee uniqueness over all
16179 possible unit names, and if file name krunching is used then it is your
16180 responsibility to ensure that no name clashes occur. The utility
16181 program @code{gnatkr} is supplied for conveniently determining the
16182 krunched name of a file.
16183
16184 @node Examples of gnatkr Usage
16185 @section Examples of @code{gnatkr} Usage
16186
16187 @smallexample
16188 @iftex
16189 @leftskip=0cm
16190 @end iftex
16191 @ifclear vms
16192 $ gnatkr very_long_unit_name.ads      --> velounna.ads
16193 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16194 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16195 $ gnatkr grandparent-parent-child     --> grparchi
16196 @end ifclear
16197 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16198 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16199 @end smallexample
16200
16201 @node Preprocessing Using gnatprep
16202 @chapter Preprocessing Using @code{gnatprep}
16203 @findex gnatprep
16204
16205 @noindent
16206 The @code{gnatprep} utility provides
16207 a simple preprocessing capability for Ada programs.
16208 It is designed for use with GNAT, but is not dependent on any special
16209 features of GNAT.
16210
16211 @menu
16212 * Using gnatprep::
16213 * Switches for gnatprep::
16214 * Form of Definitions File::
16215 * Form of Input Text for gnatprep::
16216 @end menu
16217
16218 @node Using gnatprep
16219 @section Using @code{gnatprep}
16220
16221 @noindent
16222 To call @code{gnatprep} use
16223
16224 @smallexample
16225 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
16226 @end smallexample
16227
16228 @noindent
16229 where
16230 @table @code
16231 @item infile
16232 is the full name of the input file, which is an Ada source
16233 file containing preprocessor directives.
16234
16235 @item outfile
16236 is the full name of the output file, which is an Ada source
16237 in standard Ada form. When used with GNAT, this file name will
16238 normally have an ads or adb suffix.
16239
16240 @item deffile
16241 is the full name of a text file containing definitions of
16242 symbols to be referenced by the preprocessor. This argument is
16243 optional, and can be replaced by the use of the @option{-D} switch.
16244
16245 @item switches
16246 is an optional sequence of switches as described in the next section.
16247 @end table
16248
16249 @node Switches for gnatprep
16250 @section Switches for @code{gnatprep}
16251
16252 @table @option
16253 @c !sort!
16254
16255 @item ^-b^/BLANK_LINES^
16256 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16257 Causes both preprocessor lines and the lines deleted by
16258 preprocessing to be replaced by blank lines in the output source file,
16259 preserving line numbers in the output file.
16260
16261 @item ^-c^/COMMENTS^
16262 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16263 Causes both preprocessor lines and the lines deleted
16264 by preprocessing to be retained in the output source as comments marked
16265 with the special string @code{"--! "}. This option will result in line numbers
16266 being preserved in the output file.
16267
16268 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16269 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16270 Defines a new symbol, associated with value. If no value is given on the
16271 command line, then symbol is considered to be @code{True}. This switch
16272 can be used in place of a definition file.
16273
16274 @ifset vms
16275 @item /REMOVE
16276 @cindex @option{/REMOVE} (@command{gnatprep})
16277 This is the default setting which causes lines deleted by preprocessing
16278 to be entirely removed from the output file.
16279 @end ifset
16280
16281 @item ^-r^/REFERENCE^
16282 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16283 Causes a @code{Source_Reference} pragma to be generated that
16284 references the original input file, so that error messages will use
16285 the file name of this original file. The use of this switch implies
16286 that preprocessor lines are not to be removed from the file, so its
16287 use will force @option{^-b^/BLANK_LINES^} mode if
16288 @option{^-c^/COMMENTS^}
16289 has not been specified explicitly.
16290
16291 Note that if the file to be preprocessed contains multiple units, then
16292 it will be necessary to @code{gnatchop} the output file from
16293 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16294 in the preprocessed file, it will be respected by
16295 @code{gnatchop ^-r^/REFERENCE^}
16296 so that the final chopped files will correctly refer to the original
16297 input source file for @code{gnatprep}.
16298
16299 @item ^-s^/SYMBOLS^
16300 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16301 Causes a sorted list of symbol names and values to be
16302 listed on the standard output file.
16303
16304 @item ^-u^/UNDEFINED^
16305 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16306 Causes undefined symbols to be treated as having the value FALSE in the context
16307 of a preprocessor test. In the absence of this option, an undefined symbol in
16308 a @code{#if} or @code{#elsif} test will be treated as an error.
16309
16310 @end table
16311
16312 @ifclear vms
16313 @noindent
16314 Note: if neither @option{-b} nor @option{-c} is present,
16315 then preprocessor lines and
16316 deleted lines are completely removed from the output, unless -r is
16317 specified, in which case -b is assumed.
16318 @end ifclear
16319
16320 @node Form of Definitions File
16321 @section Form of Definitions File
16322
16323 @noindent
16324 The definitions file contains lines of the form
16325
16326 @smallexample
16327 symbol := value
16328 @end smallexample
16329
16330 @noindent
16331 where symbol is an identifier, following normal Ada (case-insensitive)
16332 rules for its syntax, and value is one of the following:
16333
16334 @itemize @bullet
16335 @item
16336 Empty, corresponding to a null substitution
16337 @item
16338 A string literal using normal Ada syntax
16339 @item
16340 Any sequence of characters from the set
16341 (letters, digits, period, underline).
16342 @end itemize
16343
16344 @noindent
16345 Comment lines may also appear in the definitions file, starting with
16346 the usual @code{--},
16347 and comments may be added to the definitions lines.
16348
16349 @node Form of Input Text for gnatprep
16350 @section Form of Input Text for @code{gnatprep}
16351
16352 @noindent
16353 The input text may contain preprocessor conditional inclusion lines,
16354 as well as general symbol substitution sequences.
16355
16356 The preprocessor conditional inclusion commands have the form
16357
16358 @smallexample
16359 @group
16360 @cartouche
16361 #if @i{expression} [then]
16362    lines
16363 #elsif @i{expression} [then]
16364    lines
16365 #elsif @i{expression} [then]
16366    lines
16367 ...
16368 #else
16369    lines
16370 #end if;
16371 @end cartouche
16372 @end group
16373 @end smallexample
16374
16375 @noindent
16376 In this example, @i{expression} is defined by the following grammar:
16377 @smallexample
16378 @i{expression} ::=  <symbol>
16379 @i{expression} ::=  <symbol> = "<value>"
16380 @i{expression} ::=  <symbol> = <symbol>
16381 @i{expression} ::=  <symbol> 'Defined
16382 @i{expression} ::=  not @i{expression}
16383 @i{expression} ::=  @i{expression} and @i{expression}
16384 @i{expression} ::=  @i{expression} or @i{expression}
16385 @i{expression} ::=  @i{expression} and then @i{expression}
16386 @i{expression} ::=  @i{expression} or else @i{expression}
16387 @i{expression} ::=  ( @i{expression} )
16388 @end smallexample
16389
16390 @noindent
16391 For the first test (@i{expression} ::= <symbol>) the symbol must have
16392 either the value true or false, that is to say the right-hand of the
16393 symbol definition must be one of the (case-insensitive) literals
16394 @code{True} or @code{False}. If the value is true, then the
16395 corresponding lines are included, and if the value is false, they are
16396 excluded.
16397
16398 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16399 the symbol has been defined in the definition file or by a @option{-D}
16400 switch on the command line. Otherwise, the test is false.
16401
16402 The equality tests are case insensitive, as are all the preprocessor lines.
16403
16404 If the symbol referenced is not defined in the symbol definitions file,
16405 then the effect depends on whether or not switch @option{-u}
16406 is specified. If so, then the symbol is treated as if it had the value
16407 false and the test fails. If this switch is not specified, then
16408 it is an error to reference an undefined symbol. It is also an error to
16409 reference a symbol that is defined with a value other than @code{True}
16410 or @code{False}.
16411
16412 The use of the @code{not} operator inverts the sense of this logical test, so
16413 that the lines are included only if the symbol is not defined.
16414 The @code{then} keyword is optional as shown
16415
16416 The @code{#} must be the first non-blank character on a line, but
16417 otherwise the format is free form. Spaces or tabs may appear between
16418 the @code{#} and the keyword. The keywords and the symbols are case
16419 insensitive as in normal Ada code. Comments may be used on a
16420 preprocessor line, but other than that, no other tokens may appear on a
16421 preprocessor line. Any number of @code{elsif} clauses can be present,
16422 including none at all. The @code{else} is optional, as in Ada.
16423
16424 The @code{#} marking the start of a preprocessor line must be the first
16425 non-blank character on the line, i.e. it must be preceded only by
16426 spaces or horizontal tabs.
16427
16428 Symbol substitution outside of preprocessor lines is obtained by using
16429 the sequence
16430
16431 @smallexample
16432 $symbol
16433 @end smallexample
16434
16435 @noindent
16436 anywhere within a source line, except in a comment or within a
16437 string literal. The identifier
16438 following the @code{$} must match one of the symbols defined in the symbol
16439 definition file, and the result is to substitute the value of the
16440 symbol in place of @code{$symbol} in the output file.
16441
16442 Note that although the substitution of strings within a string literal
16443 is not possible, it is possible to have a symbol whose defined value is
16444 a string literal. So instead of setting XYZ to @code{hello} and writing:
16445
16446 @smallexample
16447 Header : String := "$XYZ";
16448 @end smallexample
16449
16450 @noindent
16451 you should set XYZ to @code{"hello"} and write:
16452
16453 @smallexample
16454 Header : String := $XYZ;
16455 @end smallexample
16456
16457 @noindent
16458 and then the substitution will occur as desired.
16459
16460 @ifset vms
16461 @node The GNAT Run-Time Library Builder gnatlbr
16462 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
16463 @findex gnatlbr
16464 @cindex Library builder
16465
16466 @noindent
16467 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
16468 supplied configuration pragmas.
16469
16470 @menu
16471 * Running gnatlbr::
16472 * Switches for gnatlbr::
16473 * Examples of gnatlbr Usage::
16474 @end menu
16475
16476 @node Running gnatlbr
16477 @section Running @code{gnatlbr}
16478
16479 @noindent
16480 The @code{gnatlbr} command has the form
16481
16482 @smallexample
16483 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
16484 @end smallexample
16485
16486 @node Switches for gnatlbr
16487 @section Switches for @code{gnatlbr}
16488
16489 @noindent
16490 @code{gnatlbr} recognizes the following switches:
16491
16492 @table @option
16493 @c !sort!
16494 @item /CREATE=directory
16495 @cindex @code{/CREATE} (@code{gnatlbr})
16496      Create the new run-time library in the specified directory.
16497
16498 @item /SET=directory
16499 @cindex @code{/SET} (@code{gnatlbr})
16500      Make the library in the specified directory the current run-time
16501      library.
16502
16503 @item /DELETE=directory
16504 @cindex @code{/DELETE} (@code{gnatlbr})
16505      Delete the run-time library in the specified directory.
16506
16507 @item /CONFIG=file
16508 @cindex @code{/CONFIG} (@code{gnatlbr})
16509      With /CREATE:
16510      Use the configuration pragmas in the specified file when building
16511      the library.
16512
16513      With /SET:
16514      Use the configuration pragmas in the specified file when compiling.
16515
16516 @end table
16517
16518 @node Examples of gnatlbr Usage
16519 @section Example of @code{gnatlbr} Usage
16520
16521 @smallexample
16522 Contents of VAXFLOAT.ADC:
16523 pragma Float_Representation (VAX_Float);
16524
16525 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
16526
16527 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
16528
16529 @end smallexample
16530 @end ifset
16531
16532 @node The GNAT Library Browser gnatls
16533 @chapter The GNAT Library Browser @code{gnatls}
16534 @findex gnatls
16535 @cindex Library browser
16536
16537 @noindent
16538 @code{gnatls} is a tool that outputs information about compiled
16539 units. It gives the relationship between objects, unit names and source
16540 files. It can also be used to check the source dependencies of a unit
16541 as well as various characteristics.
16542
16543 @menu
16544 * Running gnatls::
16545 * Switches for gnatls::
16546 * Examples of gnatls Usage::
16547 @end menu
16548
16549 @node Running gnatls
16550 @section Running @code{gnatls}
16551
16552 @noindent
16553 The @code{gnatls} command has the form
16554
16555 @smallexample
16556 $ gnatls switches @var{object_or_ali_file}
16557 @end smallexample
16558
16559 @noindent
16560 The main argument is the list of object or @file{ali} files
16561 (@pxref{The Ada Library Information Files})
16562 for which information is requested.
16563
16564 In normal mode, without additional option, @code{gnatls} produces a
16565 four-column listing. Each line represents information for a specific
16566 object. The first column gives the full path of the object, the second
16567 column gives the name of the principal unit in this object, the third
16568 column gives the status of the source and the fourth column gives the
16569 full path of the source representing this unit.
16570 Here is a simple example of use:
16571
16572 @smallexample
16573 $ gnatls *.o
16574 ^./^[]^demo1.o            demo1            DIF demo1.adb
16575 ^./^[]^demo2.o            demo2             OK demo2.adb
16576 ^./^[]^hello.o            h1                OK hello.adb
16577 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
16578 ^./^[]^instr.o            instr             OK instr.adb
16579 ^./^[]^tef.o              tef              DIF tef.adb
16580 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
16581 ^./^[]^tgef.o             tgef             DIF tgef.adb
16582 @end smallexample
16583
16584 @noindent
16585 The first line can be interpreted as follows: the main unit which is
16586 contained in
16587 object file @file{demo1.o} is demo1, whose main source is in
16588 @file{demo1.adb}. Furthermore, the version of the source used for the
16589 compilation of demo1 has been modified (DIF). Each source file has a status
16590 qualifier which can be:
16591
16592 @table @code
16593 @item OK (unchanged)
16594 The version of the source file used for the compilation of the
16595 specified unit corresponds exactly to the actual source file.
16596
16597 @item MOK (slightly modified)
16598 The version of the source file used for the compilation of the
16599 specified unit differs from the actual source file but not enough to
16600 require recompilation. If you use gnatmake with the qualifier
16601 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16602 MOK will not be recompiled.
16603
16604 @item DIF (modified)
16605 No version of the source found on the path corresponds to the source
16606 used to build this object.
16607
16608 @item ??? (file not found)
16609 No source file was found for this unit.
16610
16611 @item HID (hidden,  unchanged version not first on PATH)
16612 The version of the source that corresponds exactly to the source used
16613 for compilation has been found on the path but it is hidden by another
16614 version of the same source that has been modified.
16615
16616 @end table
16617
16618 @node Switches for gnatls
16619 @section Switches for @code{gnatls}
16620
16621 @noindent
16622 @code{gnatls} recognizes the following switches:
16623
16624 @table @option
16625 @c !sort!
16626 @item ^-a^/ALL_UNITS^
16627 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
16628 Consider all units, including those of the predefined Ada library.
16629 Especially useful with @option{^-d^/DEPENDENCIES^}.
16630
16631 @item ^-d^/DEPENDENCIES^
16632 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16633 List sources from which specified units depend on.
16634
16635 @item ^-h^/OUTPUT=OPTIONS^
16636 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16637 Output the list of options.
16638
16639 @item ^-o^/OUTPUT=OBJECTS^
16640 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16641 Only output information about object files.
16642
16643 @item ^-s^/OUTPUT=SOURCES^
16644 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16645 Only output information about source files.
16646
16647 @item ^-u^/OUTPUT=UNITS^
16648 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16649 Only output information about compilation units.
16650
16651 @item ^-files^/FILES^=@var{file}
16652 @cindex @option{^-files^/FILES^} (@code{gnatls})
16653 Take as arguments the files listed in text file @var{file}.
16654 Text file @var{file} may contain empty lines that are ignored.
16655 Each non empty line should contain the name of an existing file.
16656 Several such switches may be specified simultaneously.
16657
16658 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16659 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16660 @itemx ^-I^/SEARCH=^@var{dir}
16661 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
16662 @itemx -nostdinc
16663 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16664 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16665 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16666 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16667 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16668 flags (@pxref{Switches for gnatmake}).
16669
16670 @item --RTS=@var{rts-path}
16671 @cindex @option{--RTS} (@code{gnatls})
16672 Specifies the default location of the runtime library. Same meaning as the
16673 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16674
16675 @item ^-v^/OUTPUT=VERBOSE^
16676 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16677 Verbose mode. Output the complete source, object and project paths. Do not use
16678 the default column layout but instead use long format giving as much as
16679 information possible on each requested units, including special
16680 characteristics such as:
16681
16682 @table @code
16683 @item  Preelaborable
16684 The unit is preelaborable in the Ada 95 sense.
16685
16686 @item No_Elab_Code
16687 No elaboration code has been produced by the compiler for this unit.
16688
16689 @item Pure
16690 The unit is pure in the Ada 95 sense.
16691
16692 @item Elaborate_Body
16693 The unit contains a pragma Elaborate_Body.
16694
16695 @item Remote_Types
16696 The unit contains a pragma Remote_Types.
16697
16698 @item Shared_Passive
16699 The unit contains a pragma Shared_Passive.
16700
16701 @item Predefined
16702 This unit is part of the predefined environment and cannot be modified
16703 by the user.
16704
16705 @item Remote_Call_Interface
16706 The unit contains a pragma Remote_Call_Interface.
16707
16708 @end table
16709
16710 @end table
16711
16712 @node Examples of gnatls Usage
16713 @section Example of @code{gnatls} Usage
16714 @ifclear vms
16715
16716 @noindent
16717 Example of using the verbose switch. Note how the source and
16718 object paths are affected by the -I switch.
16719
16720 @smallexample
16721 $ gnatls -v -I.. demo1.o
16722
16723 GNATLS 5.03w (20041123-34)
16724 Copyright 1997-2004 Free Software Foundation, Inc.
16725
16726 Source Search Path:
16727    <Current_Directory>
16728    ../
16729    /home/comar/local/adainclude/
16730
16731 Object Search Path:
16732    <Current_Directory>
16733    ../
16734    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16735
16736 Project Search Path:
16737    <Current_Directory>
16738    /home/comar/local/lib/gnat/
16739
16740 ./demo1.o
16741    Unit =>
16742      Name   => demo1
16743      Kind   => subprogram body
16744      Flags  => No_Elab_Code
16745      Source => demo1.adb    modified
16746 @end smallexample
16747
16748 @noindent
16749 The following is an example of use of the dependency list.
16750 Note the use of the -s switch
16751 which gives a straight list of source files. This can be useful for
16752 building specialized scripts.
16753
16754 @smallexample
16755 $ gnatls -d demo2.o
16756 ./demo2.o   demo2        OK demo2.adb
16757                          OK gen_list.ads
16758                          OK gen_list.adb
16759                          OK instr.ads
16760                          OK instr-child.ads
16761
16762 $ gnatls -d -s -a demo1.o
16763 demo1.adb
16764 /home/comar/local/adainclude/ada.ads
16765 /home/comar/local/adainclude/a-finali.ads
16766 /home/comar/local/adainclude/a-filico.ads
16767 /home/comar/local/adainclude/a-stream.ads
16768 /home/comar/local/adainclude/a-tags.ads
16769 gen_list.ads
16770 gen_list.adb
16771 /home/comar/local/adainclude/gnat.ads
16772 /home/comar/local/adainclude/g-io.ads
16773 instr.ads
16774 /home/comar/local/adainclude/system.ads
16775 /home/comar/local/adainclude/s-exctab.ads
16776 /home/comar/local/adainclude/s-finimp.ads
16777 /home/comar/local/adainclude/s-finroo.ads
16778 /home/comar/local/adainclude/s-secsta.ads
16779 /home/comar/local/adainclude/s-stalib.ads
16780 /home/comar/local/adainclude/s-stoele.ads
16781 /home/comar/local/adainclude/s-stratt.ads
16782 /home/comar/local/adainclude/s-tasoli.ads
16783 /home/comar/local/adainclude/s-unstyp.ads
16784 /home/comar/local/adainclude/unchconv.ads
16785 @end smallexample
16786 @end ifclear
16787
16788 @ifset vms
16789 @smallexample
16790 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16791
16792 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16793 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16794 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16795 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16796 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16797 demo1.adb
16798 gen_list.ads
16799 gen_list.adb
16800 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16801 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16802 instr.ads
16803 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16804 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16805 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16806 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16807 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16808 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16809 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16810 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16811 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16812 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16813 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16814 @end smallexample
16815 @end ifset
16816
16817 @node Cleaning Up Using gnatclean
16818 @chapter Cleaning Up Using @code{gnatclean}
16819 @findex gnatclean
16820 @cindex Cleaning tool
16821
16822 @noindent
16823 @code{gnatclean} is a tool that allows the deletion of files produced by the
16824 compiler, binder and linker, including ALI files, object files, tree files,
16825 expanded source files, library files, interface copy source files, binder
16826 generated files and executable files.
16827
16828 @menu
16829 * Running gnatclean::
16830 * Switches for gnatclean::
16831 * Examples of gnatclean Usage::
16832 @end menu
16833
16834 @node Running gnatclean
16835 @section Running @code{gnatclean}
16836
16837 @noindent
16838 The @code{gnatclean} command has the form:
16839
16840 @smallexample
16841 $ gnatclean switches @var{names}
16842 @end smallexample
16843
16844 @noindent
16845 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16846 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16847 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16848
16849 @noindent
16850 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16851 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16852 the linker. In informative-only mode, specified by switch
16853 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16854 normal mode is listed, but no file is actually deleted.
16855
16856 @node Switches for gnatclean
16857 @section Switches for @code{gnatclean}
16858
16859 @noindent
16860 @code{gnatclean} recognizes the following switches:
16861
16862 @table @option
16863 @c !sort!
16864 @item ^-c^/COMPILER_FILES_ONLY^
16865 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16866 Only attempt to delete the files produced by the compiler, not those produced
16867 by the binder or the linker. The files that are not to be deleted are library
16868 files, interface copy files, binder generated files and executable files.
16869
16870 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16871 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16872 Indicate that ALI and object files should normally be found in directory
16873 @var{dir}.
16874
16875 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16876 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16877 When using project files, if some errors or warnings are detected during
16878 parsing and verbose mode is not in effect (no use of switch
16879 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16880 file, rather than its simple file name.
16881
16882 @item ^-h^/HELP^
16883 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16884 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16885
16886 @item ^-n^/NODELETE^
16887 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16888 Informative-only mode. Do not delete any files. Output the list of the files
16889 that would have been deleted if this switch was not specified.
16890
16891 @item ^-P^/PROJECT_FILE=^@var{project}
16892 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16893 Use project file @var{project}. Only one such switch can be used.
16894 When cleaning a project file, the files produced by the compilation of the
16895 immediate sources or inherited sources of the project files are to be
16896 deleted. This is not depending on the presence or not of executable names
16897 on the command line.
16898
16899 @item ^-q^/QUIET^
16900 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16901 Quiet output. If there are no error, do not ouuput anything, except in
16902 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16903 (switch ^-n^/NODELETE^).
16904
16905 @item ^-r^/RECURSIVE^
16906 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16907 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16908 clean all imported and extended project files, recursively. If this switch
16909 is not specified, only the files related to the main project file are to be
16910 deleted. This switch has no effect if no project file is specified.
16911
16912 @item ^-v^/VERBOSE^
16913 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16914 Verbose mode.
16915
16916 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16917 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16918 Indicates the verbosity of the parsing of GNAT project files.
16919 @xref{Switches Related to Project Files}.
16920
16921 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16922 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16923 Indicates that external variable @var{name} has the value @var{value}.
16924 The Project Manager will use this value for occurrences of
16925 @code{external(name)} when parsing the project file.
16926 @xref{Switches Related to Project Files}.
16927
16928 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16929 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16930 When searching for ALI and object files, look in directory
16931 @var{dir}.
16932
16933 @item ^-I^/SEARCH=^@var{dir}
16934 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16935 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16936
16937 @item ^-I-^/NOCURRENT_DIRECTORY^
16938 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16939 @cindex Source files, suppressing search
16940 Do not look for ALI or object files in the directory
16941 where @code{gnatclean} was invoked.
16942
16943 @end table
16944
16945 @node Examples of gnatclean Usage
16946 @section Examples of @code{gnatclean} Usage
16947
16948 @ifclear vms
16949 @node GNAT and Libraries
16950 @chapter GNAT and Libraries
16951 @cindex Library, building, installing, using
16952
16953 @noindent
16954 This chapter describes how to build and use libraries with GNAT, and also shows
16955 how to recompile the GNAT run-time library. You should be familiar with the
16956 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
16957 chapter.
16958
16959 @menu
16960 * Introduction to Libraries in GNAT::
16961 * General Ada Libraries::
16962 * Stand-alone Ada Libraries::
16963 * Rebuilding the GNAT Run-Time Library::
16964 @end menu
16965
16966 @node Introduction to Libraries in GNAT
16967 @section Introduction to Libraries in GNAT
16968
16969 @noindent
16970 A library is, conceptually, a collection of objects which does not have its
16971 own main thread of execution, but rather provides certain services to the
16972 applications that use it. A library can be either statically linked with the
16973 application, in which case its code is directly included in the application,
16974 or, on platforms that support it, be dynamically linked, in which case
16975 its code is shared by all applications making use of this library.
16976
16977 GNAT supports both types of libraries.
16978 In the static case, the compiled code can be provided in different ways. The
16979 simplest approach is to provide directly the set of objects resulting from
16980 compilation of the library source files. Alternatively, you can group the
16981 objects into an archive using whatever commands are provided by the operating
16982 system. For the latter case, the objects are grouped into a shared library.
16983
16984 In the GNAT environment, a library has three types of components:
16985 @itemize @bullet
16986 @item
16987 Source files.
16988 @item
16989 @file{ALI} files.
16990 @xref{The Ada Library Information Files}.
16991 @item
16992 Object files, an archive or a shared library.
16993 @end itemize
16994
16995 @noindent
16996 A GNAT library may expose all its source files, which is useful for
16997 documentation purposes. Alternatively, it may expose only the units needed by
16998 an external user to make use of the library. That is to say, the specs
16999 reflecting the library services along with all the units needed to compile
17000 those specs, which can include generic bodies or any body implementing an
17001 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17002 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17003
17004 All compilation units comprising an application, including those in a library,
17005 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17006 computes the elaboration order from the @file{ALI} files and this is why they
17007 constitute a mandatory part of GNAT libraries. Except in the case of
17008 @emph{stand-alone libraries}, where a specific library elaboration routine is
17009 produced independently of the application(s) using the library.
17010
17011 @node General Ada Libraries
17012 @section General Ada Libraries
17013
17014 @menu
17015 * Building a library::
17016 * Installing a library::
17017 * Using a library::
17018 @end menu
17019
17020 @node Building a library
17021 @subsection Building a library
17022
17023 @noindent
17024 The easiest way to build a library is to use the Project Manager,
17025 which supports a special type of project called a @emph{Library Project}
17026 (@pxref{Library Projects}).
17027
17028 A project is considered a library project, when two project-level attributes
17029 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17030 control different aspects of library configuration, additional optional
17031 project-level attributes can be specified:
17032 @table @code
17033 @item Library_Kind
17034 This attribute controls whether the library is to be static or dynamic
17035
17036 @item Library_Version
17037 This attribute specifies the library version; this value is used
17038 during dynamic linking of shared libraries to determine if the currently
17039 installed versions of the binaries are compatible.
17040
17041 @item Library_Options
17042 @item Library_GCC
17043 These attributes specify additional low-level options to be used during
17044 library generation, and redefine the actual application used to generate
17045 library.
17046 @end table
17047
17048 @noindent
17049 The GNAT Project Manager takes full care of the library maintenance task,
17050 including recompilation of the source files for which objects do not exist
17051 or are not up to date, assembly of the library archive, and installation of
17052 the library (i.e., copying associated source, object and @file{ALI} files
17053 to the specified location).
17054
17055 Here is a simple library project file:
17056 @smallexample @c ada
17057 project My_Lib is
17058    for Source_Dirs use ("src1", "src2");
17059    for Object_Dir use "obj";
17060    for Library_Name use "mylib";
17061    for Library_Dir use "lib";
17062    for Library_Kind use "dynamic";
17063 end My_lib;
17064 @end smallexample
17065
17066 @noindent
17067 and the compilation command to build and install the library:
17068
17069 @smallexample @c ada
17070   $ gnatmake -Pmy_lib
17071 @end smallexample
17072
17073 @noindent
17074 It is not entirely trivial to perform manually all the steps required to
17075 produce a library. We recommend that you use the GNAT Project Manager
17076 for this task. In special cases where this is not desired, the necessary
17077 steps are discussed below.
17078
17079 There are various possibilities for compiling the units that make up the
17080 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17081 with a conventional script. For simple libraries, it is also possible to create
17082 a dummy main program which depends upon all the packages that comprise the
17083 interface of the library. This dummy main program can then be given to
17084 @command{gnatmake}, which will ensure that all necessary objects are built.
17085
17086 After this task is accomplished, you should follow the standard procedure
17087 of the underlying operating system to produce the static or shared library.
17088
17089 Here is an example of such a dummy program:
17090 @smallexample @c ada
17091 @group
17092 with My_Lib.Service1;
17093 with My_Lib.Service2;
17094 with My_Lib.Service3;
17095 procedure My_Lib_Dummy is
17096 begin
17097    null;
17098 end;
17099 @end group
17100 @end smallexample
17101
17102 @noindent
17103 Here are the generic commands that will build an archive or a shared library.
17104
17105 @smallexample
17106 # compiling the library
17107 $ gnatmake -c my_lib_dummy.adb
17108
17109 # we don't need the dummy object itself
17110 $ rm my_lib_dummy.o my_lib_dummy.ali
17111
17112 # create an archive with the remaining objects
17113 $ ar rc libmy_lib.a *.o
17114 # some systems may require "ranlib" to be run as well
17115
17116 # or create a shared library
17117 $ gcc -shared -o libmy_lib.so *.o
17118 # some systems may require the code to have been compiled with -fPIC
17119
17120 # remove the object files that are now in the library
17121 $ rm *.o
17122
17123 # Make the ALI files read-only so that gnatmake will not try to
17124 # regenerate the objects that are in the library
17125 $ chmod -w *.ali
17126 @end smallexample
17127
17128 @noindent
17129 Please note that the library must have a name of the form @file{libxxx.a} or
17130 @file{libxxx.so} (or @file{libxxx.dll} on Windows) in order to be accessed by
17131 the directive @option{-lxxx} at link time.
17132
17133 @node Installing a library
17134 @subsection Installing a library
17135
17136 @noindent
17137 If you use project files, library installation is part of the library build
17138 process. Thus no further action is needed in order to make use of the
17139 libraries that are built as part of the general application build. A usable
17140 version of the library is installed in the directory specified by the
17141 @code{Library_Dir} attribute of the library project file.
17142
17143 You may want to install a library in a context different from where the library
17144 is built. This situation arises with third party suppliers, who may want
17145 to distribute a library in binary form where the user is not expected to be
17146 able to recompile the library. The simplest option in this case is to provide
17147 a project file slightly different from the one used to build the library, by
17148 using the @code{externally_built} attribute. For instance, the project
17149 file used to build the library in the previous section can be changed into the
17150 following one when the library is installed:
17151
17152 @smallexample @c projectfile
17153 project My_Lib is
17154    for Source_Dirs use ("src1", "src2");
17155    for Library_Name use "mylib";
17156    for Library_Dir use "lib";
17157    for Library_Kind use "dynamic";
17158    for Externally_Built use "true";
17159 end My_lib;
17160 @end smallexample
17161
17162 @noindent
17163 This project file assumes that the directories @file{src1},
17164 @file{src2}, and @file{lib} exist in
17165 the directory containing the project file. The @code{externally_built}
17166 attribute makes it clear to the GNAT builder that it should not attempt to
17167 recompile any of the units from this library. It allows the library provider to
17168 restrict the source set to the minimum necessary for clients to make use of the
17169 library as described in the first section of this chapter. It is the
17170 responsibility of the library provider to install the necessary sources, ALI
17171 files and libraries in the directories mentioned in the project file. For
17172 convenience, the user's library project file should be installed in a location
17173 that will be searched automatically by the GNAT
17174 builder. These are the directories referenced in the @code{ADA_LIBRARY_PATH}
17175 environment variable (@pxref{Importing Projects}), and also the default GNAT
17176 library location that can be queried with @command{gnatls -v} and is usually of
17177 the form $gnat_install_root/lib/gnat.
17178
17179 When project files are not an option, it is also possible, but not recommended,
17180 to install the library so that the sources needed to use the library are on the
17181 Ada source path and the ALI files & libraries be on the Ada Object path (see
17182 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17183 administrator can place general-purpose libraries in the default compiler
17184 paths, by specifying the libraries' location in the configuration files
17185 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17186 must be located in the GNAT installation tree at the same place as the gcc spec
17187 file. The location of the gcc spec file can be determined as follows:
17188 @smallexample
17189 $ gcc -v
17190 @end smallexample
17191
17192 @noindent
17193 The configuration files mentioned above have a simple format: each line
17194 must contain one unique directory name.
17195 Those names are added to the corresponding path
17196 in their order of appearance in the file. The names can be either absolute
17197 or relative; in the latter case, they are relative to where theses files
17198 are located.
17199
17200 The files @file{ada_source_path} and @file{ada_object_path} might not be
17201 present in a
17202 GNAT installation, in which case, GNAT will look for its run-time library in
17203 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17204 objects and @file{ALI} files). When the files exist, the compiler does not
17205 look in @file{adainclude} and @file{adalib}, and thus the
17206 @file{ada_source_path} file
17207 must contain the location for the GNAT run-time sources (which can simply
17208 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17209 contain the location for the GNAT run-time objects (which can simply
17210 be @file{adalib}).
17211
17212 You can also specify a new default path to the run-time library at compilation
17213 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17214 the run-time library you want your program to be compiled with. This switch is
17215 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17216 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17217
17218 It is possible to install a library before or after the standard GNAT
17219 library, by reordering the lines in the configuration files. In general, a
17220 library must be installed before the GNAT library if it redefines
17221 any part of it.
17222
17223 @node Using a library
17224 @subsection Using a library
17225
17226 @noindent Once again, the project facility greatly simplifies the use of
17227 libraries. In this context, using a library is just a matter of adding a
17228 @code{with} clause in the user project. For instance, to make use of the
17229 library @code{My_Lib} shown in examples in earlier sections, you can
17230 write:
17231
17232 @smallexample @c projectfile
17233 with "my_lib";
17234 project My_Proj is
17235   ...
17236 end My_Proj;
17237 @end smallexample
17238
17239 Even if you have a third-party, non-Ada library, you can still use GNAT's
17240 Project Manager facility to provide a wrapper for it. For example, the
17241 following project, when @code{with}ed by your main project, will link with the
17242 third-party library @file{liba.a}:
17243
17244 @smallexample @c projectfile
17245 @group
17246 project Liba is
17247    for Externally_Built use "true";
17248    for Library_Dir use "lib";
17249    for Library_Name use "a";
17250    for Library_Kind use "static";
17251 end Liba;
17252 @end group
17253 @end smallexample
17254 This is an alternative to the use of @code{pragma Linker_Options}. It is
17255 especially interesting in the context of systems with several interdependant
17256 static libraries where finding a proper linker order is not easy and best be
17257 left to the tools having visibility over project dependancy information.
17258
17259 @noindent
17260 In order to use an Ada library manually, you need to make sure that this
17261 library is on both your source and object path
17262 (see @ref{Search Paths and the Run-Time Library (RTL)}
17263 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17264 in an archive or a shared library, you need to specify the desired
17265 library at link time.
17266
17267 For example, you can use the library @file{mylib} installed in
17268 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17269
17270 @smallexample
17271 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17272   -largs -lmy_lib
17273 @end smallexample
17274
17275 @noindent
17276 This can be expressed more simply:
17277 @smallexample
17278 $ gnatmake my_appl
17279 @end smallexample
17280 @noindent
17281 when the following conditions are met:
17282 @itemize @bullet
17283 @item
17284 @file{/dir/my_lib_src} has been added by the user to the environment
17285 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
17286 @file{ada_source_path}
17287 @item
17288 @file{/dir/my_lib_obj} has been added by the user to the environment
17289 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
17290 @file{ada_object_path}
17291 @item
17292 a pragma @code{Linker_Options} has been added to one of the sources.
17293 For example:
17294
17295 @smallexample @c ada
17296 pragma Linker_Options ("-lmy_lib");
17297 @end smallexample
17298 @end itemize
17299
17300 @node Stand-alone Ada Libraries
17301 @section Stand-alone Ada Libraries
17302 @cindex Stand-alone library, building, using
17303
17304 @menu
17305 * Introduction to Stand-alone Libraries::
17306 * Building a Stand-alone Library::
17307 * Creating a Stand-alone Library to be used in a non-Ada context::
17308 * Restrictions in Stand-alone Libraries::
17309 @end menu
17310
17311 @node Introduction to Stand-alone Libraries
17312 @subsection Introduction to Stand-alone Libraries
17313
17314 @noindent
17315 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17316 necessary code to
17317 elaborate the Ada units that are included in the library. In contrast with
17318 an ordinary library, which consists of all sources, objects and @file{ALI}
17319 files of the
17320 library, a SAL may specify a restricted subset of compilation units
17321 to serve as a library interface. In this case, the fully
17322 self-sufficient set of files will normally consist of an objects
17323 archive, the sources of interface units' specs, and the @file{ALI}
17324 files of interface units.
17325 If an interface spec contains a generic unit or an inlined subprogram,
17326 the body's
17327 source must also be provided; if the units that must be provided in the source
17328 form depend on other units, the source and @file{ALI} files of those must
17329 also be provided.
17330
17331 The main purpose of a SAL is to minimize the recompilation overhead of client
17332 applications when a new version of the library is installed. Specifically,
17333 if the interface sources have not changed, client applications do not need to
17334 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17335 version, controlled by @code{Library_Version} attribute, is not changed,
17336 then the clients do not need to be relinked.
17337
17338 SALs also allow the library providers to minimize the amount of library source
17339 text exposed to the clients.  Such ``information hiding'' might be useful or
17340 necessary for various reasons.
17341
17342 Stand-alone libraries are also well suited to be used in an executable whose
17343 main routine is not written in Ada.
17344
17345 @node Building a Stand-alone Library
17346 @subsection Building a Stand-alone Library
17347
17348 @noindent
17349 GNAT's Project facility provides a simple way of building and installing
17350 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17351 To be a Stand-alone Library Project, in addition to the two attributes
17352 that make a project a Library Project (@code{Library_Name} and
17353 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17354 @code{Library_Interface} must be defined.  For example:
17355
17356 @smallexample @c projectfile
17357 @group
17358    for Library_Dir use "lib_dir";
17359    for Library_Name use "dummy";
17360    for Library_Interface use ("int1", "int1.child");
17361 @end group
17362 @end smallexample
17363
17364 @noindent
17365 Attribute @code{Library_Interface} has a non-empty string list value,
17366 each string in the list designating a unit contained in an immediate source
17367 of the project file.
17368
17369 When a Stand-alone Library is built, first the binder is invoked to build
17370 a package whose name depends on the library name
17371 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17372 This binder-generated package includes initialization and
17373 finalization procedures whose
17374 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17375 in the example
17376 above). The object corresponding to this package is included in the library.
17377
17378 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17379 calling of these procedures if a static SAL is built, or if a shared SAL
17380 is built
17381 with the project-level attribute @code{Library_Auto_Init} set to
17382 @code{"false"}.
17383
17384 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17385 (those that are listed in attribute @code{Library_Interface}) are copied to
17386 the Library Directory. As a consequence, only the Interface Units may be
17387 imported from Ada units outside of the library. If other units are imported,
17388 the binding phase will fail.
17389
17390 The attribute @code{Library_Src_Dir} may be specified for a
17391 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17392 single string value. Its value must be the path (absolute or relative to the
17393 project directory) of an existing directory. This directory cannot be the
17394 object directory or one of the source directories, but it can be the same as
17395 the library directory. The sources of the Interface
17396 Units of the library that are needed by an Ada client of the library will be
17397 copied to the designated directory, called the Interface Copy directory.
17398 These sources include the specs of the Interface Units, but they may also
17399 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17400 are used, or when there is a generic unit in the spec. Before the sources
17401 are copied to the Interface Copy directory, an attempt is made to delete all
17402 files in the Interface Copy directory.
17403
17404 Building stand-alone libraries by hand is somewhat tedious, but for those
17405 occasions when it is necessary here are the steps that you need to perform:
17406 @itemize @bullet
17407 @item
17408 Compile all library sources.
17409
17410 @item
17411 Invoke the binder with the switch @option{-n} (No Ada main program),
17412 with all the @file{ALI} files of the interfaces, and
17413 with the switch @option{-L} to give specific names to the @code{init}
17414 and @code{final} procedures.  For example:
17415 @smallexample
17416   gnatbind -n int1.ali int2.ali -Lsal1
17417 @end smallexample
17418
17419 @item
17420 Compile the binder generated file:
17421 @smallexample
17422   gcc -c b~int2.adb
17423 @end smallexample
17424
17425 @item
17426 Link the dynamic library with all the necessary object files,
17427 indicating to the linker the names of the @code{init} (and possibly
17428 @code{final}) procedures for automatic initialization (and finalization).
17429 The built library should be placed in a directory different from
17430 the object directory.
17431
17432 @item
17433 Copy the @code{ALI} files of the interface to the library directory,
17434 add in this copy an indication that it is an interface to a SAL
17435 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
17436 with letter ``P'') and make the modified copy of the @file{ALI} file
17437 read-only.
17438 @end itemize
17439
17440 @noindent
17441 Using SALs is not different from using other libraries
17442 (see @ref{Using a library}).
17443
17444 @node Creating a Stand-alone Library to be used in a non-Ada context
17445 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17446
17447 @noindent
17448 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17449 a non-Ada context.
17450
17451 The only extra step required is to ensure that library interface subprograms
17452 are compatible with the main program, by means of @code{pragma Export}
17453 or @code{pragma Convention}.
17454
17455 Here is an example of simple library interface for use with C main program:
17456
17457 @smallexample @c ada
17458 package Interface is
17459
17460    procedure Do_Something;
17461    pragma Export (C, Do_Something, "do_something");
17462
17463    procedure Do_Something_Else;
17464    pragma Export (C, Do_Something_Else, "do_something_else");
17465
17466 end Interface;
17467 @end smallexample
17468
17469 @noindent
17470 On the foreign language side, you must provide a ``foreign'' view of the
17471 library interface; remember that it should contain elaboration routines in
17472 addition to interface subprograms.
17473
17474 The example below shows the content of @code{mylib_interface.h} (note
17475 that there is no rule for the naming of this file, any name can be used)
17476 @smallexample
17477 /* the library elaboration procedure */
17478 extern void mylibinit (void);
17479
17480 /* the library finalization procedure */
17481 extern void mylibfinal (void);
17482
17483 /* the interface exported by the library */
17484 extern void do_something (void);
17485 extern void do_something_else (void);
17486 @end smallexample
17487
17488 @noindent
17489 Libraries built as explained above can be used from any program, provided
17490 that the elaboration procedures (named @code{mylibinit} in the previous
17491 example) are called before the library services are used. Any number of
17492 libraries can be used simultaneously, as long as the elaboration
17493 procedure of each library is called.
17494
17495 Below is an example of a C program that uses the @code{mylib} library.
17496
17497 @smallexample
17498 #include "mylib_interface.h"
17499
17500 int
17501 main (void)
17502 @{
17503    /* First, elaborate the library before using it */
17504    mylibinit ();
17505
17506    /* Main program, using the library exported entities */
17507    do_something ();
17508    do_something_else ();
17509
17510    /* Library finalization at the end of the program */
17511    mylibfinal ();
17512    return 0;
17513 @}
17514 @end smallexample
17515
17516 @noindent
17517 Note that invoking any library finalization procedure generated by
17518 @code{gnatbind} shuts down the Ada run-time environment.
17519 Consequently, the
17520 finalization of all Ada libraries must be performed at the end of the program.
17521 No call to these libraries or to the Ada run-time library should be made
17522 after the finalization phase.
17523
17524 @node Restrictions in Stand-alone Libraries
17525 @subsection Restrictions in Stand-alone Libraries
17526
17527 @noindent
17528 The pragmas listed below should be used with caution inside libraries,
17529 as they can create incompatibilities with other Ada libraries:
17530 @itemize @bullet
17531 @item pragma @code{Locking_Policy}
17532 @item pragma @code{Queuing_Policy}
17533 @item pragma @code{Task_Dispatching_Policy}
17534 @item pragma @code{Unreserve_All_Interrupts}
17535 @end itemize
17536
17537 @noindent
17538 When using a library that contains such pragmas, the user must make sure
17539 that all libraries use the same pragmas with the same values. Otherwise,
17540 @code{Program_Error} will
17541 be raised during the elaboration of the conflicting
17542 libraries. The usage of these pragmas and its consequences for the user
17543 should therefore be well documented.
17544
17545 Similarly, the traceback in the exception occurrence mechanism should be
17546 enabled or disabled in a consistent manner across all libraries.
17547 Otherwise, Program_Error will be raised during the elaboration of the
17548 conflicting libraries.
17549
17550 If the @code{Version} or @code{Body_Version}
17551 attributes are used inside a library, then you need to
17552 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17553 libraries, so that version identifiers can be properly computed.
17554 In practice these attributes are rarely used, so this is unlikely
17555 to be a consideration.
17556
17557 @node  Rebuilding the GNAT Run-Time Library
17558 @section Rebuilding the GNAT Run-Time Library
17559 @cindex GNAT Run-Time Library, rebuilding
17560
17561 @noindent
17562 It may be useful to recompile the GNAT library in various contexts, the
17563 most important one being the use of partition-wide configuration pragmas
17564 such as @code{Normalize_Scalars}. A special Makefile called
17565 @code{Makefile.adalib} is provided to that effect and can be found in
17566 the directory containing the GNAT library. The location of this
17567 directory depends on the way the GNAT environment has been installed and can
17568 be determined by means of the command:
17569
17570 @smallexample
17571 $ gnatls -v
17572 @end smallexample
17573
17574 @noindent
17575 The last entry in the object search path usually contains the
17576 gnat library. This Makefile contains its own documentation and in
17577 particular the set of instructions needed to rebuild a new library and
17578 to use it.
17579
17580 @node Using the GNU make Utility
17581 @chapter Using the GNU @code{make} Utility
17582 @findex make
17583
17584 @noindent
17585 This chapter offers some examples of makefiles that solve specific
17586 problems. It does not explain how to write a makefile (see the GNU make
17587 documentation), nor does it try to replace the @command{gnatmake} utility
17588 (@pxref{The GNAT Make Program gnatmake}).
17589
17590 All the examples in this section are specific to the GNU version of
17591 make. Although @code{make} is a standard utility, and the basic language
17592 is the same, these examples use some advanced features found only in
17593 @code{GNU make}.
17594
17595 @menu
17596 * Using gnatmake in a Makefile::
17597 * Automatically Creating a List of Directories::
17598 * Generating the Command Line Switches::
17599 * Overcoming Command Line Length Limits::
17600 @end menu
17601
17602 @node Using gnatmake in a Makefile
17603 @section Using gnatmake in a Makefile
17604 @findex makefile
17605 @cindex GNU make
17606
17607 @noindent
17608 Complex project organizations can be handled in a very powerful way by
17609 using GNU make combined with gnatmake. For instance, here is a Makefile
17610 which allows you to build each subsystem of a big project into a separate
17611 shared library. Such a makefile allows you to significantly reduce the link
17612 time of very big applications while maintaining full coherence at
17613 each step of the build process.
17614
17615 The list of dependencies are handled automatically by
17616 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
17617 the appropriate directories.
17618
17619 Note that you should also read the example on how to automatically
17620 create the list of directories
17621 (@pxref{Automatically Creating a List of Directories})
17622 which might help you in case your project has a lot of subdirectories.
17623
17624 @smallexample
17625 @iftex
17626 @leftskip=0cm
17627 @font@heightrm=cmr8
17628 @heightrm
17629 @end iftex
17630 ## This Makefile is intended to be used with the following directory
17631 ## configuration:
17632 ##  - The sources are split into a series of csc (computer software components)
17633 ##    Each of these csc is put in its own directory.
17634 ##    Their name are referenced by the directory names.
17635 ##    They will be compiled into shared library (although this would also work
17636 ##    with static libraries
17637 ##  - The main program (and possibly other packages that do not belong to any
17638 ##    csc is put in the top level directory (where the Makefile is).
17639 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17640 ##                    \_ second_csc (sources) __ lib (will contain the library)
17641 ##                    \_ ...
17642 ## Although this Makefile is build for shared library, it is easy to modify
17643 ## to build partial link objects instead (modify the lines with -shared and
17644 ## gnatlink below)
17645 ##
17646 ## With this makefile, you can change any file in the system or add any new
17647 ## file, and everything will be recompiled correctly (only the relevant shared
17648 ## objects will be recompiled, and the main program will be re-linked).
17649
17650 # The list of computer software component for your project. This might be
17651 # generated automatically.
17652 CSC_LIST=aa bb cc
17653
17654 # Name of the main program (no extension)
17655 MAIN=main
17656
17657 # If we need to build objects with -fPIC, uncomment the following line
17658 #NEED_FPIC=-fPIC
17659
17660 # The following variable should give the directory containing libgnat.so
17661 # You can get this directory through 'gnatls -v'. This is usually the last
17662 # directory in the Object_Path.
17663 GLIB=...
17664
17665 # The directories for the libraries
17666 # (This macro expands the list of CSC to the list of shared libraries, you
17667 # could simply use the expanded form :
17668 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17669 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17670
17671 $@{MAIN@}: objects $@{LIB_DIR@}
17672     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17673     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17674
17675 objects::
17676     # recompile the sources
17677     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17678
17679 # Note: In a future version of GNAT, the following commands will be simplified
17680 # by a new tool, gnatmlib
17681 $@{LIB_DIR@}:
17682     mkdir -p $@{dir $@@ @}
17683     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17684     cd $@{dir $@@ @}; cp -f ../*.ali .
17685
17686 # The dependencies for the modules
17687 # Note that we have to force the expansion of *.o, since in some cases
17688 # make won't be able to do it itself.
17689 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17690 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17691 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17692
17693 # Make sure all of the shared libraries are in the path before starting the
17694 # program
17695 run::
17696     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17697
17698 clean::
17699     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17700     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17701     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17702     $@{RM@} *.o *.ali $@{MAIN@}
17703 @end smallexample
17704
17705 @node Automatically Creating a List of Directories
17706 @section Automatically Creating a List of Directories
17707
17708 @noindent
17709 In most makefiles, you will have to specify a list of directories, and
17710 store it in a variable. For small projects, it is often easier to
17711 specify each of them by hand, since you then have full control over what
17712 is the proper order for these directories, which ones should be
17713 included...
17714
17715 However, in larger projects, which might involve hundreds of
17716 subdirectories, it might be more convenient to generate this list
17717 automatically.
17718
17719 The example below presents two methods. The first one, although less
17720 general, gives you more control over the list. It involves wildcard
17721 characters, that are automatically expanded by @code{make}. Its
17722 shortcoming is that you need to explicitly specify some of the
17723 organization of your project, such as for instance the directory tree
17724 depth, whether some directories are found in a separate tree,...
17725
17726 The second method is the most general one. It requires an external
17727 program, called @code{find}, which is standard on all Unix systems. All
17728 the directories found under a given root directory will be added to the
17729 list.
17730
17731 @smallexample
17732 @iftex
17733 @leftskip=0cm
17734 @font@heightrm=cmr8
17735 @heightrm
17736 @end iftex
17737 # The examples below are based on the following directory hierarchy:
17738 # All the directories can contain any number of files
17739 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17740 #                       ->  ab
17741 #                       ->  ac
17742 #                ->  b  ->  ba  ->  baa
17743 #                       ->  bb
17744 #                       ->  bc
17745 # This Makefile creates a variable called DIRS, that can be reused any time
17746 # you need this list (see the other examples in this section)
17747
17748 # The root of your project's directory hierarchy
17749 ROOT_DIRECTORY=.
17750
17751 ####
17752 # First method: specify explicitly the list of directories
17753 # This allows you to specify any subset of all the directories you need.
17754 ####
17755
17756 DIRS := a/aa/ a/ab/ b/ba/
17757
17758 ####
17759 # Second method: use wildcards
17760 # Note that the argument(s) to wildcard below should end with a '/'.
17761 # Since wildcards also return file names, we have to filter them out
17762 # to avoid duplicate directory names.
17763 # We thus use make's @code{dir} and @code{sort} functions.
17764 # It sets DIRs to the following value (note that the directories aaa and baa
17765 # are not given, unless you change the arguments to wildcard).
17766 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17767 ####
17768
17769 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17770                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17771
17772 ####
17773 # Third method: use an external program
17774 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17775 # This is the most complete command: it sets DIRs to the following value:
17776 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17777 ####
17778
17779 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17780
17781 @end smallexample
17782
17783 @node Generating the Command Line Switches
17784 @section Generating the Command Line Switches
17785
17786 @noindent
17787 Once you have created the list of directories as explained in the
17788 previous section (@pxref{Automatically Creating a List of Directories}),
17789 you can easily generate the command line arguments to pass to gnatmake.
17790
17791 For the sake of completeness, this example assumes that the source path
17792 is not the same as the object path, and that you have two separate lists
17793 of directories.
17794
17795 @smallexample
17796 # see "Automatically creating a list of directories" to create
17797 # these variables
17798 SOURCE_DIRS=
17799 OBJECT_DIRS=
17800
17801 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17802 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17803
17804 all:
17805         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17806 @end smallexample
17807
17808 @node Overcoming Command Line Length Limits
17809 @section Overcoming Command Line Length Limits
17810
17811 @noindent
17812 One problem that might be encountered on big projects is that many
17813 operating systems limit the length of the command line. It is thus hard to give
17814 gnatmake the list of source and object directories.
17815
17816 This example shows how you can set up environment variables, which will
17817 make @command{gnatmake} behave exactly as if the directories had been
17818 specified on the command line, but have a much higher length limit (or
17819 even none on most systems).
17820
17821 It assumes that you have created a list of directories in your Makefile,
17822 using one of the methods presented in
17823 @ref{Automatically Creating a List of Directories}.
17824 For the sake of completeness, we assume that the object
17825 path (where the ALI files are found) is different from the sources patch.
17826
17827 Note a small trick in the Makefile below: for efficiency reasons, we
17828 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17829 expanded immediately by @code{make}. This way we overcome the standard
17830 make behavior which is to expand the variables only when they are
17831 actually used.
17832
17833 On Windows, if you are using the standard Windows command shell, you must
17834 replace colons with semicolons in the assignments to these variables.
17835
17836 @smallexample
17837 @iftex
17838 @leftskip=0cm
17839 @font@heightrm=cmr8
17840 @heightrm
17841 @end iftex
17842 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
17843 # This is the same thing as putting the -I arguments on the command line.
17844 # (the equivalent of using -aI on the command line would be to define
17845 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
17846 # You can of course have different values for these variables.
17847 #
17848 # Note also that we need to keep the previous values of these variables, since
17849 # they might have been set before running 'make' to specify where the GNAT
17850 # library is installed.
17851
17852 # see "Automatically creating a list of directories" to create these
17853 # variables
17854 SOURCE_DIRS=
17855 OBJECT_DIRS=
17856
17857 empty:=
17858 space:=$@{empty@} $@{empty@}
17859 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17860 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17861 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17862 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
17863 export ADA_INCLUDE_PATH
17864 export ADA_OBJECT_PATH
17865
17866 all:
17867         gnatmake main_unit
17868 @end smallexample
17869 @end ifclear
17870
17871 @node Memory Management Issues
17872 @chapter Memory Management Issues
17873
17874 @noindent
17875 This chapter describes some useful memory pools provided in the GNAT library
17876 and in particular the GNAT Debug Pool facility, which can be used to detect
17877 incorrect uses of access values (including ``dangling references'').
17878 @ifclear vms
17879 It also describes the @command{gnatmem} tool, which can be used to track down
17880 ``memory leaks''.
17881 @end ifclear
17882
17883 @menu
17884 * Some Useful Memory Pools::
17885 * The GNAT Debug Pool Facility::
17886 @ifclear vms
17887 * The gnatmem Tool::
17888 @end ifclear
17889 @end menu
17890
17891 @node Some Useful Memory Pools
17892 @section Some Useful Memory Pools
17893 @findex Memory Pool
17894 @cindex storage, pool
17895
17896 @noindent
17897 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
17898 storage pool. Allocations use the standard system call @code{malloc} while
17899 deallocations use the standard system call @code{free}. No reclamation is
17900 performed when the pool goes out of scope. For performance reasons, the
17901 standard default Ada allocators/deallocators do not use any explicit storage
17902 pools but if they did, they could use this storage pool without any change in
17903 behavior. That is why this storage pool is used  when the user
17904 manages to make the default implicit allocator explicit as in this example:
17905 @smallexample @c ada
17906    type T1 is access Something;
17907     -- no Storage pool is defined for T2
17908    type T2 is access Something_Else;
17909    for T2'Storage_Pool use T1'Storage_Pool;
17910    -- the above is equivalent to
17911    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
17912 @end smallexample
17913
17914 @noindent
17915 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
17916 pool. The allocation strategy is similar to @code{Pool_Local}'s
17917 except that the all
17918 storage allocated with this pool is reclaimed when the pool object goes out of
17919 scope. This pool provides a explicit mechanism similar to the implicit one
17920 provided by several Ada 83 compilers for allocations performed through a local
17921 access type and whose purpose was to reclaim memory when exiting the
17922 scope of a given local access. As an example, the following program does not
17923 leak memory even though it does not perform explicit deallocation:
17924
17925 @smallexample @c ada
17926 with System.Pool_Local;
17927 procedure Pooloc1 is
17928    procedure Internal is
17929       type A is access Integer;
17930       X : System.Pool_Local.Unbounded_Reclaim_Pool;
17931       for A'Storage_Pool use X;
17932       v : A;
17933    begin
17934       for I in  1 .. 50 loop
17935          v := new Integer;
17936       end loop;
17937    end Internal;
17938 begin
17939    for I in  1 .. 100 loop
17940       Internal;
17941    end loop;
17942 end Pooloc1;
17943 @end smallexample
17944
17945 @noindent
17946 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
17947 @code{Storage_Size} is specified for an access type.
17948 The whole storage for the pool is
17949 allocated at once, usually on the stack at the point where the access type is
17950 elaborated. It is automatically reclaimed when exiting the scope where the
17951 access type is defined. This package is not intended to be used directly by the
17952 user and it is implicitly used for each such declaration:
17953
17954 @smallexample @c ada
17955    type T1 is access Something;
17956    for T1'Storage_Size use 10_000;
17957 @end smallexample
17958
17959
17960 @node The GNAT Debug Pool Facility
17961 @section The GNAT Debug Pool Facility
17962 @findex Debug Pool
17963 @cindex storage, pool, memory corruption
17964
17965 @noindent
17966 The use of unchecked deallocation and unchecked conversion can easily
17967 lead to incorrect memory references. The problems generated by such
17968 references are usually difficult to tackle because the symptoms can be
17969 very remote from the origin of the problem. In such cases, it is
17970 very helpful to detect the problem as early as possible. This is the
17971 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17972
17973 In order to use the GNAT specific debugging pool, the user must
17974 associate a debug pool object with each of the access types that may be
17975 related to suspected memory problems. See Ada Reference Manual 13.11.
17976 @smallexample @c ada
17977 type Ptr is access Some_Type;
17978 Pool : GNAT.Debug_Pools.Debug_Pool;
17979 for Ptr'Storage_Pool use Pool;
17980 @end smallexample
17981
17982 @noindent
17983 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17984 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17985 allow the user to redefine allocation and deallocation strategies. They
17986 also provide a checkpoint for each dereference, through the use of
17987 the primitive operation @code{Dereference} which is implicitly called at
17988 each dereference of an access value.
17989
17990 Once an access type has been associated with a debug pool, operations on
17991 values of the type may raise four distinct exceptions,
17992 which correspond to four potential kinds of memory corruption:
17993 @itemize @bullet
17994 @item
17995 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17996 @item
17997 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17998 @item
17999 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18000 @item
18001 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18002 @end itemize
18003
18004 @noindent
18005 For types associated with a Debug_Pool, dynamic allocation is performed using
18006 the standard GNAT allocation routine. References to all allocated chunks of
18007 memory are kept in an internal dictionary. Several deallocation strategies are
18008 provided, whereupon the user can choose to release the memory to the system,
18009 keep it allocated for further invalid access checks, or fill it with an easily
18010 recognizable pattern for debug sessions. The memory pattern is the old IBM
18011 hexadecimal convention: @code{16#DEADBEEF#}.
18012
18013 See the documentation in the file g-debpoo.ads for more information on the
18014 various strategies.
18015
18016 Upon each dereference, a check is made that the access value denotes a
18017 properly allocated memory location. Here is a complete example of use of
18018 @code{Debug_Pools}, that includes typical instances of  memory corruption:
18019 @smallexample @c ada
18020 @iftex
18021 @leftskip=0cm
18022 @end iftex
18023 with Gnat.Io; use Gnat.Io;
18024 with Unchecked_Deallocation;
18025 with Unchecked_Conversion;
18026 with GNAT.Debug_Pools;
18027 with System.Storage_Elements;
18028 with Ada.Exceptions; use Ada.Exceptions;
18029 procedure Debug_Pool_Test is
18030
18031    type T is access Integer;
18032    type U is access all T;
18033
18034    P : GNAT.Debug_Pools.Debug_Pool;
18035    for T'Storage_Pool use P;
18036
18037    procedure Free is new Unchecked_Deallocation (Integer, T);
18038    function UC is new Unchecked_Conversion (U, T);
18039    A, B : aliased T;
18040
18041    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18042
18043 begin
18044    Info (P);
18045    A := new Integer;
18046    B := new Integer;
18047    B := A;
18048    Info (P);
18049    Free (A);
18050    begin
18051       Put_Line (Integer'Image(B.all));
18052    exception
18053       when E : others => Put_Line ("raised: " & Exception_Name (E));
18054    end;
18055    begin
18056       Free (B);
18057    exception
18058       when E : others => Put_Line ("raised: " & Exception_Name (E));
18059    end;
18060    B := UC(A'Access);
18061    begin
18062       Put_Line (Integer'Image(B.all));
18063    exception
18064       when E : others => Put_Line ("raised: " & Exception_Name (E));
18065    end;
18066    begin
18067       Free (B);
18068    exception
18069       when E : others => Put_Line ("raised: " & Exception_Name (E));
18070    end;
18071    Info (P);
18072 end Debug_Pool_Test;
18073 @end smallexample
18074
18075 @noindent
18076 The debug pool mechanism provides the following precise diagnostics on the
18077 execution of this erroneous program:
18078 @smallexample
18079 Debug Pool info:
18080   Total allocated bytes :  0
18081   Total deallocated bytes :  0
18082   Current Water Mark:  0
18083   High Water Mark:  0
18084
18085 Debug Pool info:
18086   Total allocated bytes :  8
18087   Total deallocated bytes :  0
18088   Current Water Mark:  8
18089   High Water Mark:  8
18090
18091 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18092 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18093 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18094 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18095 Debug Pool info:
18096   Total allocated bytes :  8
18097   Total deallocated bytes :  4
18098   Current Water Mark:  4
18099   High Water Mark:  8
18100 @end smallexample
18101
18102 @ifclear vms
18103 @node The gnatmem Tool
18104 @section The @command{gnatmem} Tool
18105 @findex gnatmem
18106
18107 @noindent
18108 The @code{gnatmem} utility monitors dynamic allocation and
18109 deallocation activity in a program, and displays information about
18110 incorrect deallocations and possible sources of memory leaks.
18111 It provides three type of information:
18112 @itemize @bullet
18113 @item
18114 General information concerning memory management, such as the total
18115 number of allocations and deallocations, the amount of allocated
18116 memory and the high water mark, i.e. the largest amount of allocated
18117 memory in the course of program execution.
18118
18119 @item
18120 Backtraces for all incorrect deallocations, that is to say deallocations
18121 which do not correspond to a valid allocation.
18122
18123 @item
18124 Information on each allocation that is potentially the origin of a memory
18125 leak.
18126 @end itemize
18127
18128 @menu
18129 * Running gnatmem::
18130 * Switches for gnatmem::
18131 * Example of gnatmem Usage::
18132 @end menu
18133
18134 @node Running gnatmem
18135 @subsection Running @code{gnatmem}
18136
18137 @noindent
18138 @code{gnatmem} makes use of the output created by the special version of
18139 allocation and deallocation routines that record call information. This
18140 allows to obtain accurate dynamic memory usage history at a minimal cost to
18141 the execution speed. Note however, that @code{gnatmem} is not supported on
18142 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
18143 32-bit Solaris (sparc and x86) and Windows NT/2000/XP (x86).
18144
18145 @noindent
18146 The @code{gnatmem} command has the form
18147
18148 @smallexample
18149    $ gnatmem [switches] user_program
18150 @end smallexample
18151
18152 @noindent
18153 The program must have been linked with the instrumented version of the
18154 allocation and deallocation routines. This is done by linking with the
18155 @file{libgmem.a} library. For correct symbolic backtrace information,
18156 the user program should be compiled with debugging options
18157 @ref{Switches for gcc}. For example to build @file{my_program}:
18158
18159 @smallexample
18160 $ gnatmake -g my_program -largs -lgmem
18161 @end smallexample
18162
18163 @noindent
18164 When running @file{my_program} the file @file{gmem.out} is produced. This file
18165 contains information about all allocations and deallocations done by the
18166 program. It is produced by the instrumented allocations and
18167 deallocations routines and will be used by @code{gnatmem}.
18168
18169 @noindent
18170 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18171 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18172 @code{-i} switch, gnatmem will assume that this file can be found in the
18173 current directory. For example, after you have executed @file{my_program},
18174 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18175
18176 @smallexample
18177 $ gnatmem my_program
18178 @end smallexample
18179
18180 @noindent
18181 This will produce the output with the following format:
18182
18183 *************** debut cc
18184 @smallexample
18185 $ gnatmem my_program
18186
18187 Global information
18188 ------------------
18189    Total number of allocations        :  45
18190    Total number of deallocations      :   6
18191    Final Water Mark (non freed mem)   :  11.29 Kilobytes
18192    High Water Mark                    :  11.40 Kilobytes
18193
18194 .
18195 .
18196 .
18197 Allocation Root # 2
18198 -------------------
18199  Number of non freed allocations    :  11
18200  Final Water Mark (non freed mem)   :   1.16 Kilobytes
18201  High Water Mark                    :   1.27 Kilobytes
18202  Backtrace                          :
18203    my_program.adb:23 my_program.alloc
18204 .
18205 .
18206 .
18207 @end smallexample
18208
18209 The first block of output gives general information. In this case, the
18210 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18211 Unchecked_Deallocation routine occurred.
18212
18213 @noindent
18214 Subsequent paragraphs display  information on all allocation roots.
18215 An allocation root is a specific point in the execution of the program
18216 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18217 construct. This root is represented by an execution backtrace (or subprogram
18218 call stack). By default the backtrace depth for allocations roots is 1, so
18219 that a root corresponds exactly to a source location. The backtrace can
18220 be made deeper, to make the root more specific.
18221
18222 @node Switches for gnatmem
18223 @subsection Switches for @code{gnatmem}
18224
18225 @noindent
18226 @code{gnatmem} recognizes the following switches:
18227
18228 @table @option
18229
18230 @item -q
18231 @cindex @option{-q} (@code{gnatmem})
18232 Quiet. Gives the minimum output needed to identify the origin of the
18233 memory leaks. Omits statistical information.
18234
18235 @item @var{N}
18236 @cindex @var{N} (@code{gnatmem})
18237 N is an integer literal (usually between 1 and 10) which controls the
18238 depth of the backtraces defining allocation root. The default value for
18239 N is 1. The deeper the backtrace, the more precise the localization of
18240 the root. Note that the total number of roots can depend on this
18241 parameter. This parameter must be specified @emph{before} the name of the
18242 executable to be analyzed, to avoid ambiguity.
18243
18244 @item -b n
18245 @cindex @option{-b} (@code{gnatmem})
18246 This switch has the same effect as just depth parameter.
18247
18248 @item -i @var{file}
18249 @cindex @option{-i} (@code{gnatmem})
18250 Do the @code{gnatmem} processing starting from @file{file}, rather than
18251 @file{gmem.out} in the current directory.
18252
18253 @item -m n
18254 @cindex @option{-m} (@code{gnatmem})
18255 This switch causes @code{gnatmem} to mask the allocation roots that have less
18256 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18257 examine even the roots that didn't result in leaks.
18258
18259 @item -s order
18260 @cindex @option{-s} (@code{gnatmem})
18261 This switch causes @code{gnatmem} to sort the allocation roots according to the
18262 specified order of sort criteria, each identified by a single letter. The
18263 currently supported criteria are @code{n, h, w} standing respectively for
18264 number of unfreed allocations, high watermark, and final watermark
18265 corresponding to a specific root. The default order is @code{nwh}.
18266
18267 @end table
18268
18269 @node Example of gnatmem Usage
18270 @subsection Example of @code{gnatmem} Usage
18271
18272 @noindent
18273 The following example shows the use of @code{gnatmem}
18274 on a simple memory-leaking program.
18275 Suppose that we have the following Ada program:
18276
18277 @smallexample @c ada
18278 @group
18279 @cartouche
18280 with Unchecked_Deallocation;
18281 procedure Test_Gm is
18282
18283    type T is array (1..1000) of Integer;
18284    type Ptr is access T;
18285    procedure Free is new Unchecked_Deallocation (T, Ptr);
18286    A : Ptr;
18287
18288    procedure My_Alloc is
18289    begin
18290       A := new T;
18291    end My_Alloc;
18292
18293    procedure My_DeAlloc is
18294       B : Ptr := A;
18295    begin
18296       Free (B);
18297    end My_DeAlloc;
18298
18299 begin
18300    My_Alloc;
18301    for I in 1 .. 5 loop
18302       for J in I .. 5 loop
18303          My_Alloc;
18304       end loop;
18305       My_Dealloc;
18306    end loop;
18307 end;
18308 @end cartouche
18309 @end group
18310 @end smallexample
18311
18312 @noindent
18313 The program needs to be compiled with debugging option and linked with
18314 @code{gmem} library:
18315
18316 @smallexample
18317 $ gnatmake -g test_gm -largs -lgmem
18318 @end smallexample
18319
18320 @noindent
18321 Then we execute the program as usual:
18322
18323 @smallexample
18324 $ test_gm
18325 @end smallexample
18326
18327 @noindent
18328 Then @code{gnatmem} is invoked simply with
18329 @smallexample
18330 $ gnatmem test_gm
18331 @end smallexample
18332
18333 @noindent
18334 which produces the following output (result may vary on different platforms):
18335
18336 @smallexample
18337 Global information
18338 ------------------
18339    Total number of allocations        :  18
18340    Total number of deallocations      :   5
18341    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18342    High Water Mark                    :  56.90 Kilobytes
18343
18344 Allocation Root # 1
18345 -------------------
18346  Number of non freed allocations    :  11
18347  Final Water Mark (non freed mem)   :  42.97 Kilobytes
18348  High Water Mark                    :  46.88 Kilobytes
18349  Backtrace                          :
18350    test_gm.adb:11 test_gm.my_alloc
18351
18352 Allocation Root # 2
18353 -------------------
18354  Number of non freed allocations    :   1
18355  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18356  High Water Mark                    :  10.02 Kilobytes
18357  Backtrace                          :
18358    s-secsta.adb:81 system.secondary_stack.ss_init
18359
18360 Allocation Root # 3
18361 -------------------
18362  Number of non freed allocations    :   1
18363  Final Water Mark (non freed mem)   :  12 Bytes
18364  High Water Mark                    :  12 Bytes
18365  Backtrace                          :
18366    s-secsta.adb:181 system.secondary_stack.ss_init
18367 @end smallexample
18368
18369 @noindent
18370 Note that the GNAT run time contains itself a certain number of
18371 allocations that have no  corresponding deallocation,
18372 as shown here for root #2 and root
18373 #3. This is a normal behavior when the number of non freed allocations
18374 is one, it allocates dynamic data structures that the run time needs for
18375 the complete lifetime of the program. Note also that there is only one
18376 allocation root in the user program with a single line back trace:
18377 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18378 program shows that 'My_Alloc' is called at 2 different points in the
18379 source (line 21 and line 24). If those two allocation roots need to be
18380 distinguished, the backtrace depth parameter can be used:
18381
18382 @smallexample
18383 $ gnatmem 3 test_gm
18384 @end smallexample
18385
18386 @noindent
18387 which will give the following output:
18388
18389 @smallexample
18390 Global information
18391 ------------------
18392    Total number of allocations        :  18
18393    Total number of deallocations      :   5
18394    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18395    High Water Mark                    :  56.90 Kilobytes
18396
18397 Allocation Root # 1
18398 -------------------
18399  Number of non freed allocations    :  10
18400  Final Water Mark (non freed mem)   :  39.06 Kilobytes
18401  High Water Mark                    :  42.97 Kilobytes
18402  Backtrace                          :
18403    test_gm.adb:11 test_gm.my_alloc
18404    test_gm.adb:24 test_gm
18405    b_test_gm.c:52 main
18406
18407 Allocation Root # 2
18408 -------------------
18409  Number of non freed allocations    :   1
18410  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18411  High Water Mark                    :  10.02 Kilobytes
18412  Backtrace                          :
18413    s-secsta.adb:81  system.secondary_stack.ss_init
18414    s-secsta.adb:283 <system__secondary_stack___elabb>
18415    b_test_gm.c:33   adainit
18416
18417 Allocation Root # 3
18418 -------------------
18419  Number of non freed allocations    :   1
18420  Final Water Mark (non freed mem)   :   3.91 Kilobytes
18421  High Water Mark                    :   3.91 Kilobytes
18422  Backtrace                          :
18423    test_gm.adb:11 test_gm.my_alloc
18424    test_gm.adb:21 test_gm
18425    b_test_gm.c:52 main
18426
18427 Allocation Root # 4
18428 -------------------
18429  Number of non freed allocations    :   1
18430  Final Water Mark (non freed mem)   :  12 Bytes
18431  High Water Mark                    :  12 Bytes
18432  Backtrace                          :
18433    s-secsta.adb:181 system.secondary_stack.ss_init
18434    s-secsta.adb:283 <system__secondary_stack___elabb>
18435    b_test_gm.c:33   adainit
18436 @end smallexample
18437
18438 @noindent
18439 The allocation root #1 of the first example has been split in 2 roots #1
18440 and #3 thanks to the more precise associated backtrace.
18441
18442 @end ifclear
18443
18444 @node Creating Sample Bodies Using gnatstub
18445 @chapter Creating Sample Bodies Using @command{gnatstub}
18446 @findex gnatstub
18447
18448 @noindent
18449 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
18450 for library unit declarations.
18451
18452 To create a body stub, @command{gnatstub} has to compile the library
18453 unit declaration. Therefore, bodies can be created only for legal
18454 library units. Moreover, if a library unit depends semantically upon
18455 units located outside the current directory, you have to provide
18456 the source search path when calling @command{gnatstub}, see the description
18457 of @command{gnatstub} switches below.
18458
18459 @menu
18460 * Running gnatstub::
18461 * Switches for gnatstub::
18462 @end menu
18463
18464 @node Running gnatstub
18465 @section Running @command{gnatstub}
18466
18467 @noindent
18468 @command{gnatstub} has the command-line interface of the form
18469
18470 @smallexample
18471 $ gnatstub [switches] filename [directory]
18472 @end smallexample
18473
18474 @noindent
18475 where
18476 @table @emph
18477 @item filename
18478 is the name of the source file that contains a library unit declaration
18479 for which a body must be created. The file name may contain the path
18480 information.
18481 The file name does not have to follow the GNAT file name conventions. If the
18482 name
18483 does not follow GNAT file naming conventions, the name of the body file must
18484 be provided
18485 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
18486 If the file name follows the GNAT file naming
18487 conventions and the name of the body file is not provided,
18488 @command{gnatstub}
18489 creates the name
18490 of the body file from the argument file name by replacing the @file{.ads}
18491 suffix
18492 with the @file{.adb} suffix.
18493
18494 @item directory
18495 indicates the directory in which the body stub is to be placed (the default
18496 is the
18497 current directory)
18498
18499 @item switches
18500 is an optional sequence of switches as described in the next section
18501 @end table
18502
18503 @node Switches for gnatstub
18504 @section Switches for @command{gnatstub}
18505
18506 @table @option
18507 @c !sort!
18508
18509 @item ^-f^/FULL^
18510 @cindex @option{^-f^/FULL^} (@command{gnatstub})
18511 If the destination directory already contains a file with the name of the
18512 body file
18513 for the argument spec file, replace it with the generated body stub.
18514
18515 @item ^-hs^/HEADER=SPEC^
18516 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
18517 Put the comment header (i.e., all the comments preceding the
18518 compilation unit) from the source of the library unit declaration
18519 into the body stub.
18520
18521 @item ^-hg^/HEADER=GENERAL^
18522 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
18523 Put a sample comment header into the body stub.
18524
18525 @ifclear vms
18526 @item -IDIR
18527 @cindex @option{-IDIR} (@command{gnatstub})
18528 @itemx -I-
18529 @cindex @option{-I-} (@command{gnatstub})
18530 @end ifclear
18531 @ifset vms
18532 @item /NOCURRENT_DIRECTORY
18533 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
18534 @end ifset
18535 ^These switches have ^This switch has^ the same meaning as in calls to
18536 @command{gcc}.
18537 ^They define ^It defines ^ the source search path in the call to
18538 @command{gcc} issued
18539 by @command{gnatstub} to compile an argument source file.
18540
18541 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
18542 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
18543 This switch has the same meaning as in calls to @command{gcc}.
18544 It defines the additional configuration file to be passed to the call to
18545 @command{gcc} issued
18546 by @command{gnatstub} to compile an argument source file.
18547
18548 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
18549 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
18550 (@var{n} is a non-negative integer). Set the maximum line length in the
18551 body stub to @var{n}; the default is 79. The maximum value that can be
18552 specified is 32767. Note that in the special case of configuration
18553 pragma files, the maximum is always 32767 regardless of whether or
18554 not this switch appears.
18555
18556 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
18557 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
18558 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18559 the generated body sample to @var{n}.
18560 The default indentation is 3.
18561
18562 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
18563 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
18564 Order local bodies alphabetically. (By default local bodies are ordered
18565 in the same way as the corresponding local specs in the argument spec file.)
18566
18567 @item ^-i^/INDENTATION=^@var{n}
18568 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
18569 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
18570
18571 @item ^-k^/TREE_FILE=SAVE^
18572 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
18573 Do not remove the tree file (i.e., the snapshot of the compiler internal
18574 structures used by @command{gnatstub}) after creating the body stub.
18575
18576 @item ^-l^/LINE_LENGTH=^@var{n}
18577 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
18578 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
18579
18580 @item ^-o^/BODY=^@var{body-name}
18581 @cindex @option{^-o^/BODY^} (@command{gnatstub})
18582 Body file name.  This should be set if the argument file name does not
18583 follow
18584 the GNAT file naming
18585 conventions. If this switch is omitted the default name for the body will be
18586 obtained
18587 from the argument file name according to the GNAT file naming conventions.
18588
18589 @item ^-q^/QUIET^
18590 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
18591 Quiet mode: do not generate a confirmation when a body is
18592 successfully created, and do not generate a message when a body is not
18593 required for an
18594 argument unit.
18595
18596 @item ^-r^/TREE_FILE=REUSE^
18597 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18598 Reuse the tree file (if it exists) instead of creating it.  Instead of
18599 creating the tree file for the library unit declaration, @command{gnatstub}
18600 tries to find it in the current directory and use it for creating
18601 a body. If the tree file is not found, no body is created. This option
18602 also implies @option{^-k^/SAVE^}, whether or not
18603 the latter is set explicitly.
18604
18605 @item ^-t^/TREE_FILE=OVERWRITE^
18606 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18607 Overwrite the existing tree file.  If the current directory already
18608 contains the file which, according to the GNAT file naming rules should
18609 be considered as a tree file for the argument source file,
18610 @command{gnatstub}
18611 will refuse to create the tree file needed to create a sample body
18612 unless this option is set.
18613
18614 @item ^-v^/VERBOSE^
18615 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18616 Verbose mode: generate version information.
18617
18618 @end table
18619
18620 @node Other Utility Programs
18621 @chapter Other Utility Programs
18622
18623 @noindent
18624 This chapter discusses some other utility programs available in the Ada
18625 environment.
18626
18627 @menu
18628 * Using Other Utility Programs with GNAT::
18629 * The External Symbol Naming Scheme of GNAT::
18630 @ifclear vms
18631 * Ada Mode for Glide::
18632 @end ifclear
18633 * Converting Ada Files to html with gnathtml::
18634 * Installing gnathtml::
18635 @ifset vms
18636 * LSE::
18637 * Profiling::
18638 @end ifset
18639 @end menu
18640
18641 @node Using Other Utility Programs with GNAT
18642 @section Using Other Utility Programs with GNAT
18643
18644 @noindent
18645 The object files generated by GNAT are in standard system format and in
18646 particular the debugging information uses this format. This means
18647 programs generated by GNAT can be used with existing utilities that
18648 depend on these formats.
18649
18650 @ifclear vms
18651 In general, any utility program that works with C will also often work with
18652 Ada programs generated by GNAT. This includes software utilities such as
18653 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18654 as Purify.
18655 @end ifclear
18656
18657 @node The External Symbol Naming Scheme of GNAT
18658 @section The External Symbol Naming Scheme of GNAT
18659
18660 @noindent
18661 In order to interpret the output from GNAT, when using tools that are
18662 originally intended for use with other languages, it is useful to
18663 understand the conventions used to generate link names from the Ada
18664 entity names.
18665
18666 All link names are in all lowercase letters. With the exception of library
18667 procedure names, the mechanism used is simply to use the full expanded
18668 Ada name with dots replaced by double underscores. For example, suppose
18669 we have the following package spec:
18670
18671 @smallexample @c ada
18672 @group
18673 @cartouche
18674 package QRS is
18675    MN : Integer;
18676 end QRS;
18677 @end cartouche
18678 @end group
18679 @end smallexample
18680
18681 @noindent
18682 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18683 the corresponding link name is @code{qrs__mn}.
18684 @findex Export
18685 Of course if a @code{pragma Export} is used this may be overridden:
18686
18687 @smallexample @c ada
18688 @group
18689 @cartouche
18690 package Exports is
18691    Var1 : Integer;
18692    pragma Export (Var1, C, External_Name => "var1_name");
18693    Var2 : Integer;
18694    pragma Export (Var2, C, Link_Name => "var2_link_name");
18695 end Exports;
18696 @end cartouche
18697 @end group
18698 @end smallexample
18699
18700 @noindent
18701 In this case, the link name for @var{Var1} is whatever link name the
18702 C compiler would assign for the C function @var{var1_name}. This typically
18703 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18704 system conventions, but other possibilities exist. The link name for
18705 @var{Var2} is @var{var2_link_name}, and this is not operating system
18706 dependent.
18707
18708 @findex _main
18709 One exception occurs for library level procedures. A potential ambiguity
18710 arises between the required name @code{_main} for the C main program,
18711 and the name we would otherwise assign to an Ada library level procedure
18712 called @code{Main} (which might well not be the main program).
18713
18714 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18715 names. So if we have a library level procedure such as
18716
18717 @smallexample @c ada
18718 @group
18719 @cartouche
18720 procedure Hello (S : String);
18721 @end cartouche
18722 @end group
18723 @end smallexample
18724
18725 @noindent
18726 the external name of this procedure will be @var{_ada_hello}.
18727
18728 @ifclear vms
18729 @node Ada Mode for Glide
18730 @section Ada Mode for @code{Glide}
18731 @cindex Ada mode (for Glide)
18732
18733 @noindent
18734 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
18735 user to understand and navigate existing code, and facilitates writing
18736 new code. It furthermore provides some utility functions for easier
18737 integration of standard Emacs features when programming in Ada.
18738
18739 Its general features include:
18740
18741 @itemize @bullet
18742 @item
18743 An Integrated Development Environment with functionality such as the
18744 following
18745
18746 @itemize @bullet
18747 @item
18748 ``Project files'' for configuration-specific aspects
18749 (e.g. directories and compilation options)
18750
18751 @item
18752 Compiling and stepping through error messages.
18753
18754 @item
18755 Running and debugging an applications within Glide.
18756 @end itemize
18757
18758 @item
18759 Pull-down menus
18760
18761 @item
18762 User configurability
18763 @end itemize
18764
18765 Some of the specific Ada mode features are:
18766
18767 @itemize @bullet
18768 @item
18769 Functions for easy and quick stepping through Ada code
18770
18771 @item
18772 Getting cross reference information for identifiers (e.g., finding a
18773 defining occurrence)
18774
18775 @item
18776 Displaying an index menu of types and subprograms, allowing
18777 direct selection for browsing
18778
18779 @item
18780 Automatic color highlighting of the various Ada entities
18781 @end itemize
18782
18783 Glide directly supports writing Ada code, via several facilities:
18784
18785 @itemize @bullet
18786 @item
18787 Switching between spec and body files with possible
18788 autogeneration of body files
18789
18790 @item
18791 Automatic formating of subprogram parameter lists
18792
18793 @item
18794 Automatic indentation according to Ada syntax
18795
18796 @item
18797 Automatic completion of identifiers
18798
18799 @item
18800 Automatic (and configurable) casing of identifiers, keywords, and attributes
18801
18802 @item
18803 Insertion of syntactic templates
18804
18805 @item
18806 Block commenting / uncommenting
18807 @end itemize
18808
18809 @noindent
18810 For more information, please refer to the online documentation
18811 available in the @code{Glide} @result{} @code{Help} menu.
18812 @end ifclear
18813
18814 @node Converting Ada Files to html with gnathtml
18815 @section Converting Ada Files to HTML with @code{gnathtml}
18816
18817 @noindent
18818 This @code{Perl} script allows Ada source files to be browsed using
18819 standard Web browsers. For installation procedure, see the section
18820 @xref{Installing gnathtml}.
18821
18822 Ada reserved keywords are highlighted in a bold font and Ada comments in
18823 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18824 switch to suppress the generation of cross-referencing information, user
18825 defined variables and types will appear in a different color; you will
18826 be able to click on any identifier and go to its declaration.
18827
18828 The command line is as follow:
18829 @smallexample
18830 $ perl gnathtml.pl [switches] ada-files
18831 @end smallexample
18832
18833 @noindent
18834 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18835 an html file for every ada file, and a global file called @file{index.htm}.
18836 This file is an index of every identifier defined in the files.
18837
18838 The available switches are the following ones :
18839
18840 @table @option
18841 @item -83
18842 @cindex @option{-83} (@code{gnathtml})
18843 Only the subset on the Ada 83 keywords will be highlighted, not the full
18844 Ada 95 keywords set.
18845
18846 @item -cc @var{color}
18847 @cindex @option{-cc} (@code{gnathtml})
18848 This option allows you to change the color used for comments. The default
18849 value is green. The color argument can be any name accepted by html.
18850
18851 @item -d
18852 @cindex @option{-d} (@code{gnathtml})
18853 If the ada files depend on some other files (using for instance the
18854 @code{with} command, the latter will also be converted to html.
18855 Only the files in the user project will be converted to html, not the files
18856 in the run-time library itself.
18857
18858 @item -D
18859 @cindex @option{-D} (@code{gnathtml})
18860 This command is the same as @option{-d} above, but @command{gnathtml} will
18861 also look for files in the run-time library, and generate html files for them.
18862
18863 @item -ext @var{extension}
18864 @cindex @option{-ext} (@code{gnathtml})
18865 This option allows you to change the extension of the generated HTML files.
18866 If you do not specify an extension, it will default to @file{htm}.
18867
18868 @item -f
18869 @cindex @option{-f} (@code{gnathtml})
18870 By default, gnathtml will generate html links only for global entities
18871 ('with'ed units, global variables and types,...). If you specify the
18872 @option{-f} on the command line, then links will be generated for local
18873 entities too.
18874
18875 @item -l @var{number}
18876 @cindex @option{-l} (@code{gnathtml})
18877 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
18878 will number the html files every @var{number} line.
18879
18880 @item -I @var{dir}
18881 @cindex @option{-I} (@code{gnathtml})
18882 Specify a directory to search for library files (@file{.ALI} files) and
18883 source files. You can provide several -I switches on the command line,
18884 and the directories will be parsed in the order of the command line.
18885
18886 @item -o @var{dir}
18887 @cindex @option{-o} (@code{gnathtml})
18888 Specify the output directory for html files. By default, gnathtml will
18889 saved the generated html files in a subdirectory named @file{html/}.
18890
18891 @item -p @var{file}
18892 @cindex @option{-p} (@code{gnathtml})
18893 If you are using Emacs and the most recent Emacs Ada mode, which provides
18894 a full Integrated Development Environment for compiling, checking,
18895 running and debugging applications, you may use @file{.gpr} files
18896 to give the directories where Emacs can find sources and object files.
18897
18898 Using this switch, you can tell gnathtml to use these files. This allows
18899 you to get an html version of your application, even if it is spread
18900 over multiple directories.
18901
18902 @item -sc @var{color}
18903 @cindex @option{-sc} (@code{gnathtml})
18904 This option allows you to change the color used for symbol definitions.
18905 The default value is red. The color argument can be any name accepted by html.
18906
18907 @item -t @var{file}
18908 @cindex @option{-t} (@code{gnathtml})
18909 This switch provides the name of a file. This file contains a list of
18910 file names to be converted, and the effect is exactly as though they had
18911 appeared explicitly on the command line. This
18912 is the recommended way to work around the command line length limit on some
18913 systems.
18914
18915 @end table
18916
18917 @node Installing gnathtml
18918 @section Installing @code{gnathtml}
18919
18920 @noindent
18921 @code{Perl} needs to be installed on your machine to run this script.
18922 @code{Perl} is freely available for almost every architecture and
18923 Operating System via the Internet.
18924
18925 On Unix systems, you  may want to modify  the  first line of  the script
18926 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18927 is. The syntax of this line is :
18928 @smallexample
18929 #!full_path_name_to_perl
18930 @end smallexample
18931
18932 @noindent
18933 Alternatively, you may run the script using the following command line:
18934
18935 @smallexample
18936 $ perl gnathtml.pl [switches] files
18937 @end smallexample
18938
18939 @ifset vms
18940 @node LSE
18941 @section LSE
18942 @findex LSE
18943
18944 @noindent
18945 The GNAT distribution provides an Ada 95 template for the Digital Language
18946 Sensitive Editor (LSE), a component of DECset. In order to
18947 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18948
18949 @node Profiling
18950 @section Profiling
18951 @findex PCA
18952
18953 @noindent
18954 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
18955 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18956 the collection phase with the /DEBUG qualifier.
18957
18958 @smallexample
18959 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18960 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18961 $ RUN/DEBUG <PROGRAM_NAME>
18962 @end smallexample
18963 @noindent
18964 @end ifset
18965
18966 @node Running and Debugging Ada Programs
18967 @chapter Running and Debugging Ada Programs
18968 @cindex Debugging
18969
18970 @noindent
18971 This chapter discusses how to debug Ada programs.
18972 @ifset vms
18973 It applies to the Alpha OpenVMS platform;
18974 the debugger for Integrity OpenVMS is scheduled for a subsequent release.
18975 @end ifset
18976
18977 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18978
18979 @enumerate
18980 @item
18981 The illegality may be a violation of the static semantics of Ada. In
18982 that case GNAT diagnoses the constructs in the program that are illegal.
18983 It is then a straightforward matter for the user to modify those parts of
18984 the program.
18985
18986 @item
18987 The illegality may be a violation of the dynamic semantics of Ada. In
18988 that case the program compiles and executes, but may generate incorrect
18989 results, or may terminate abnormally with some exception.
18990
18991 @item
18992 When presented with a program that contains convoluted errors, GNAT
18993 itself may terminate abnormally without providing full diagnostics on
18994 the incorrect user program.
18995 @end enumerate
18996
18997 @menu
18998 * The GNAT Debugger GDB::
18999 * Running GDB::
19000 * Introduction to GDB Commands::
19001 * Using Ada Expressions::
19002 * Calling User-Defined Subprograms::
19003 * Using the Next Command in a Function::
19004 * Ada Exceptions::
19005 * Ada Tasks::
19006 * Debugging Generic Units::
19007 * GNAT Abnormal Termination or Failure to Terminate::
19008 * Naming Conventions for GNAT Source Files::
19009 * Getting Internal Debugging Information::
19010 * Stack Traceback::
19011 @end menu
19012
19013 @cindex Debugger
19014 @findex gdb
19015
19016 @node The GNAT Debugger GDB
19017 @section The GNAT Debugger GDB
19018
19019 @noindent
19020 @code{GDB} is a general purpose, platform-independent debugger that
19021 can be used to debug mixed-language programs compiled with @command{gcc},
19022 and in particular is capable of debugging Ada programs compiled with
19023 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19024 complex Ada data structures.
19025
19026 The manual @cite{Debugging with GDB}
19027 @ifset vms
19028 , located in the GNU:[DOCS] directory,
19029 @end ifset
19030 contains full details on the usage of @code{GDB}, including a section on
19031 its usage on programs. This manual should be consulted for full
19032 details. The section that follows is a brief introduction to the
19033 philosophy and use of @code{GDB}.
19034
19035 When GNAT programs are compiled, the compiler optionally writes debugging
19036 information into the generated object file, including information on
19037 line numbers, and on declared types and variables. This information is
19038 separate from the generated code. It makes the object files considerably
19039 larger, but it does not add to the size of the actual executable that
19040 will be loaded into memory, and has no impact on run-time performance. The
19041 generation of debug information is triggered by the use of the
19042 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
19043 the compilations. It is important to emphasize that the use of these
19044 options does not change the generated code.
19045
19046 The debugging information is written in standard system formats that
19047 are used by many tools, including debuggers and profilers. The format
19048 of the information is typically designed to describe C types and
19049 semantics, but GNAT implements a translation scheme which allows full
19050 details about Ada types and variables to be encoded into these
19051 standard C formats. Details of this encoding scheme may be found in
19052 the file exp_dbug.ads in the GNAT source distribution. However, the
19053 details of this encoding are, in general, of no interest to a user,
19054 since @code{GDB} automatically performs the necessary decoding.
19055
19056 When a program is bound and linked, the debugging information is
19057 collected from the object files, and stored in the executable image of
19058 the program. Again, this process significantly increases the size of
19059 the generated executable file, but it does not increase the size of
19060 the executable program itself. Furthermore, if this program is run in
19061 the normal manner, it runs exactly as if the debug information were
19062 not present, and takes no more actual memory.
19063
19064 However, if the program is run under control of @code{GDB}, the
19065 debugger is activated.  The image of the program is loaded, at which
19066 point it is ready to run.  If a run command is given, then the program
19067 will run exactly as it would have if @code{GDB} were not present. This
19068 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19069 entirely non-intrusive until a breakpoint is encountered.  If no
19070 breakpoint is ever hit, the program will run exactly as it would if no
19071 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19072 the debugging information and can respond to user commands to inspect
19073 variables, and more generally to report on the state of execution.
19074
19075 @c **************
19076 @node Running GDB
19077 @section Running GDB
19078
19079 @noindent
19080 The debugger can be launched directly and simply from @code{glide} or
19081 through its graphical interface: @code{gvd}. It can also be used
19082 directly in text mode. Here is described the basic use of @code{GDB}
19083 in text mode. All the commands described below can be used in the
19084 @code{gvd} console window even though there is usually other more
19085 graphical ways to achieve the same goals.
19086
19087 @ifclear vms
19088 @noindent
19089 The command to run the graphical interface of the debugger is
19090 @smallexample
19091 $ gvd program
19092 @end smallexample
19093 @end ifclear
19094
19095 @noindent
19096 The command to run @code{GDB} in text mode is
19097
19098 @smallexample
19099 $ ^gdb program^$ GDB PROGRAM^
19100 @end smallexample
19101
19102 @noindent
19103 where @code{^program^PROGRAM^} is the name of the executable file. This
19104 activates the debugger and results in a prompt for debugger commands.
19105 The simplest command is simply @code{run}, which causes the program to run
19106 exactly as if the debugger were not present. The following section
19107 describes some of the additional commands that can be given to @code{GDB}.
19108
19109 @c *******************************
19110 @node Introduction to GDB Commands
19111 @section Introduction to GDB Commands
19112
19113 @noindent
19114 @code{GDB} contains a large repertoire of commands. The manual
19115 @cite{Debugging with GDB}
19116 @ifset vms
19117 , located in the GNU:[DOCS] directory,
19118 @end ifset
19119 includes extensive documentation on the use
19120 of these commands, together with examples of their use. Furthermore,
19121 the command @var{help} invoked from within @code{GDB} activates a simple help
19122 facility which summarizes the available commands and their options.
19123 In this section we summarize a few of the most commonly
19124 used commands to give an idea of what @code{GDB} is about. You should create
19125 a simple program with debugging information and experiment with the use of
19126 these @code{GDB} commands on the program as you read through the
19127 following section.
19128
19129 @table @code
19130 @item set args @var{arguments}
19131 The @var{arguments} list above is a list of arguments to be passed to
19132 the program on a subsequent run command, just as though the arguments
19133 had been entered on a normal invocation of the program. The @code{set args}
19134 command is not needed if the program does not require arguments.
19135
19136 @item run
19137 The @code{run} command causes execution of the program to start from
19138 the beginning. If the program is already running, that is to say if
19139 you are currently positioned at a breakpoint, then a prompt will ask
19140 for confirmation that you want to abandon the current execution and
19141 restart.
19142
19143 @item breakpoint @var{location}
19144 The breakpoint command sets a breakpoint, that is to say a point at which
19145 execution will halt and @code{GDB} will await further
19146 commands. @var{location} is
19147 either a line number within a file, given in the format @code{file:linenumber},
19148 or it is the name of a subprogram. If you request that a breakpoint be set on
19149 a subprogram that is overloaded, a prompt will ask you to specify on which of
19150 those subprograms you want to breakpoint. You can also
19151 specify that all of them should be breakpointed. If the program is run
19152 and execution encounters the breakpoint, then the program
19153 stops and @code{GDB} signals that the breakpoint was encountered by
19154 printing the line of code before which the program is halted.
19155
19156 @item breakpoint exception @var{name}
19157 A special form of the breakpoint command which breakpoints whenever
19158 exception @var{name} is raised.
19159 If @var{name} is omitted,
19160 then a breakpoint will occur when any exception is raised.
19161
19162 @item print @var{expression}
19163 This will print the value of the given expression. Most simple
19164 Ada expression formats are properly handled by @code{GDB}, so the expression
19165 can contain function calls, variables, operators, and attribute references.
19166
19167 @item continue
19168 Continues execution following a breakpoint, until the next breakpoint or the
19169 termination of the program.
19170
19171 @item step
19172 Executes a single line after a breakpoint. If the next statement
19173 is a subprogram call, execution continues into (the first statement of)
19174 the called subprogram.
19175
19176 @item next
19177 Executes a single line. If this line is a subprogram call, executes and
19178 returns from the call.
19179
19180 @item list
19181 Lists a few lines around the current source location. In practice, it
19182 is usually more convenient to have a separate edit window open with the
19183 relevant source file displayed. Successive applications of this command
19184 print subsequent lines. The command can be given an argument which is a
19185 line number, in which case it displays a few lines around the specified one.
19186
19187 @item backtrace
19188 Displays a backtrace of the call chain. This command is typically
19189 used after a breakpoint has occurred, to examine the sequence of calls that
19190 leads to the current breakpoint. The display includes one line for each
19191 activation record (frame) corresponding to an active subprogram.
19192
19193 @item up
19194 At a breakpoint, @code{GDB} can display the values of variables local
19195 to the current frame. The command @code{up} can be used to
19196 examine the contents of other active frames, by moving the focus up
19197 the stack, that is to say from callee to caller, one frame at a time.
19198
19199 @item down
19200 Moves the focus of @code{GDB} down from the frame currently being
19201 examined to the frame of its callee (the reverse of the previous command),
19202
19203 @item frame @var{n}
19204 Inspect the frame with the given number. The value 0 denotes the frame
19205 of the current breakpoint, that is to say the top of the call stack.
19206
19207 @end table
19208
19209 The above list is a very short introduction to the commands that
19210 @code{GDB} provides. Important additional capabilities, including conditional
19211 breakpoints, the ability to execute command sequences on a breakpoint,
19212 the ability to debug at the machine instruction level and many other
19213 features are described in detail in @cite{Debugging with GDB}.
19214 Note that most commands can be abbreviated
19215 (for example, c for continue, bt for backtrace).
19216
19217 @node Using Ada Expressions
19218 @section Using Ada Expressions
19219 @cindex Ada expressions
19220
19221 @noindent
19222 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19223 extensions. The philosophy behind the design of this subset is
19224
19225 @itemize @bullet
19226 @item
19227 That @code{GDB} should provide basic literals and access to operations for
19228 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19229 leaving more sophisticated computations to subprograms written into the
19230 program (which therefore may be called from @code{GDB}).
19231
19232 @item
19233 That type safety and strict adherence to Ada language restrictions
19234 are not particularly important to the @code{GDB} user.
19235
19236 @item
19237 That brevity is important to the @code{GDB} user.
19238 @end itemize
19239
19240 Thus, for brevity, the debugger acts as if there were
19241 implicit @code{with} and @code{use} clauses in effect for all user-written
19242 packages, thus making it unnecessary to fully qualify most names with
19243 their packages, regardless of context. Where this causes ambiguity,
19244 @code{GDB} asks the user's intent.
19245
19246 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19247
19248 @node Calling User-Defined Subprograms
19249 @section Calling User-Defined Subprograms
19250
19251 @noindent
19252 An important capability of @code{GDB} is the ability to call user-defined
19253 subprograms while debugging. This is achieved simply by entering
19254 a subprogram call statement in the form:
19255
19256 @smallexample
19257 call subprogram-name (parameters)
19258 @end smallexample
19259
19260 @noindent
19261 The keyword @code{call} can be omitted in the normal case where the
19262 @code{subprogram-name} does not coincide with any of the predefined
19263 @code{GDB} commands.
19264
19265 The effect is to invoke the given subprogram, passing it the
19266 list of parameters that is supplied. The parameters can be expressions and
19267 can include variables from the program being debugged. The
19268 subprogram must be defined
19269 at the library level within your program, and @code{GDB} will call the
19270 subprogram within the environment of your program execution (which
19271 means that the subprogram is free to access or even modify variables
19272 within your program).
19273
19274 The most important use of this facility is in allowing the inclusion of
19275 debugging routines that are tailored to particular data structures
19276 in your program. Such debugging routines can be written to provide a suitably
19277 high-level description of an abstract type, rather than a low-level dump
19278 of its physical layout. After all, the standard
19279 @code{GDB print} command only knows the physical layout of your
19280 types, not their abstract meaning. Debugging routines can provide information
19281 at the desired semantic level and are thus enormously useful.
19282
19283 For example, when debugging GNAT itself, it is crucial to have access to
19284 the contents of the tree nodes used to represent the program internally.
19285 But tree nodes are represented simply by an integer value (which in turn
19286 is an index into a table of nodes).
19287 Using the @code{print} command on a tree node would simply print this integer
19288 value, which is not very useful. But the PN routine (defined in file
19289 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19290 a useful high level representation of the tree node, which includes the
19291 syntactic category of the node, its position in the source, the integers
19292 that denote descendant nodes and parent node, as well as varied
19293 semantic information. To study this example in more detail, you might want to
19294 look at the body of the PN procedure in the stated file.
19295
19296 @node Using the Next Command in a Function
19297 @section Using the Next Command in a Function
19298
19299 @noindent
19300 When you use the @code{next} command in a function, the current source
19301 location will advance to the next statement as usual. A special case
19302 arises in the case of a @code{return} statement.
19303
19304 Part of the code for a return statement is the ``epilog'' of the function.
19305 This is the code that returns to the caller. There is only one copy of
19306 this epilog code, and it is typically associated with the last return
19307 statement in the function if there is more than one return. In some
19308 implementations, this epilog is associated with the first statement
19309 of the function.
19310
19311 The result is that if you use the @code{next} command from a return
19312 statement that is not the last return statement of the function you
19313 may see a strange apparent jump to the last return statement or to
19314 the start of the function. You should simply ignore this odd jump.
19315 The value returned is always that from the first return statement
19316 that was stepped through.
19317
19318 @node Ada Exceptions
19319 @section Breaking on Ada Exceptions
19320 @cindex Exceptions
19321
19322 @noindent
19323 You can set breakpoints that trip when your program raises
19324 selected exceptions.
19325
19326 @table @code
19327 @item break exception
19328 Set a breakpoint that trips whenever (any task in the) program raises
19329 any exception.
19330
19331 @item break exception @var{name}
19332 Set a breakpoint that trips whenever (any task in the) program raises
19333 the exception @var{name}.
19334
19335 @item break exception unhandled
19336 Set a breakpoint that trips whenever (any task in the) program raises an
19337 exception for which there is no handler.
19338
19339 @item info exceptions
19340 @itemx info exceptions @var{regexp}
19341 The @code{info exceptions} command permits the user to examine all defined
19342 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19343 argument, prints out only those exceptions whose name matches @var{regexp}.
19344 @end table
19345
19346 @node Ada Tasks
19347 @section Ada Tasks
19348 @cindex Tasks
19349
19350 @noindent
19351 @code{GDB} allows the following task-related commands:
19352
19353 @table @code
19354 @item info tasks
19355 This command shows a list of current Ada tasks, as in the following example:
19356
19357 @smallexample
19358 @iftex
19359 @leftskip=0cm
19360 @end iftex
19361 (gdb) info tasks
19362   ID       TID P-ID   Thread Pri State                 Name
19363    1   8088000   0   807e000  15 Child Activation Wait main_task
19364    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19365    3   809a800   1   80a4800  15 Child Activation Wait a
19366 *  4   80ae800   3   80b8000  15 Running               c
19367 @end smallexample
19368
19369 @noindent
19370 In this listing, the asterisk before the first task indicates it to be the
19371 currently running task. The first column lists the task ID that is used
19372 to refer to tasks in the following commands.
19373
19374 @item break @var{linespec} task @var{taskid}
19375 @itemx break @var{linespec} task @var{taskid} if @dots{}
19376 @cindex Breakpoints and tasks
19377 These commands are like the @code{break @dots{} thread @dots{}}.
19378 @var{linespec} specifies source lines.
19379
19380 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19381 to specify that you only want @code{GDB} to stop the program when a
19382 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19383 numeric task identifiers assigned by @code{GDB}, shown in the first
19384 column of the @samp{info tasks} display.
19385
19386 If you do not specify @samp{task @var{taskid}} when you set a
19387 breakpoint, the breakpoint applies to @emph{all} tasks of your
19388 program.
19389
19390 You can use the @code{task} qualifier on conditional breakpoints as
19391 well; in this case, place @samp{task @var{taskid}} before the
19392 breakpoint condition (before the @code{if}).
19393
19394 @item task @var{taskno}
19395 @cindex Task switching
19396
19397 This command allows to switch to the task referred by @var{taskno}. In
19398 particular, This allows to browse the backtrace of the specified
19399 task. It is advised to switch back to the original task before
19400 continuing execution otherwise the scheduling of the program may be
19401 perturbated.
19402 @end table
19403
19404 @noindent
19405 For more detailed information on the tasking support,
19406 see @cite{Debugging with GDB}.
19407
19408 @node Debugging Generic Units
19409 @section Debugging Generic Units
19410 @cindex Debugging Generic Units
19411 @cindex Generics
19412
19413 @noindent
19414 GNAT always uses code expansion for generic instantiation. This means that
19415 each time an instantiation occurs, a complete copy of the original code is
19416 made, with appropriate substitutions of formals by actuals.
19417
19418 It is not possible to refer to the original generic entities in
19419 @code{GDB}, but it is always possible to debug a particular instance of
19420 a generic, by using the appropriate expanded names. For example, if we have
19421
19422 @smallexample @c ada
19423 @group
19424 @cartouche
19425 procedure g is
19426
19427    generic package k is
19428       procedure kp (v1 : in out integer);
19429    end k;
19430
19431    package body k is
19432       procedure kp (v1 : in out integer) is
19433       begin
19434          v1 := v1 + 1;
19435       end kp;
19436    end k;
19437
19438    package k1 is new k;
19439    package k2 is new k;
19440
19441    var : integer := 1;
19442
19443 begin
19444    k1.kp (var);
19445    k2.kp (var);
19446    k1.kp (var);
19447    k2.kp (var);
19448 end;
19449 @end cartouche
19450 @end group
19451 @end smallexample
19452
19453 @noindent
19454 Then to break on a call to procedure kp in the k2 instance, simply
19455 use the command:
19456
19457 @smallexample
19458 (gdb) break g.k2.kp
19459 @end smallexample
19460
19461 @noindent
19462 When the breakpoint occurs, you can step through the code of the
19463 instance in the normal manner and examine the values of local variables, as for
19464 other units.
19465
19466 @node GNAT Abnormal Termination or Failure to Terminate
19467 @section GNAT Abnormal Termination or Failure to Terminate
19468 @cindex GNAT Abnormal Termination or Failure to Terminate
19469
19470 @noindent
19471 When presented with programs that contain serious errors in syntax
19472 or semantics,
19473 GNAT may on rare occasions  experience problems in operation, such
19474 as aborting with a
19475 segmentation fault or illegal memory access, raising an internal
19476 exception, terminating abnormally, or failing to terminate at all.
19477 In such cases, you can activate
19478 various features of GNAT that can help you pinpoint the construct in your
19479 program that is the likely source of the problem.
19480
19481 The following strategies are presented in increasing order of
19482 difficulty, corresponding to your experience in using GNAT and your
19483 familiarity with compiler internals.
19484
19485 @enumerate
19486 @item
19487 Run @command{gcc} with the @option{-gnatf}. This first
19488 switch causes all errors on a given line to be reported. In its absence,
19489 only the first error on a line is displayed.
19490
19491 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19492 are encountered, rather than after compilation is terminated. If GNAT
19493 terminates prematurely or goes into an infinite loop, the last error
19494 message displayed may help to pinpoint the culprit.
19495
19496 @item
19497 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19498 mode, @command{gcc} produces ongoing information about the progress of the
19499 compilation and provides the name of each procedure as code is
19500 generated. This switch allows you to find which Ada procedure was being
19501 compiled when it encountered a code generation problem.
19502
19503 @item
19504 @cindex @option{-gnatdc} switch
19505 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19506 switch that does for the front-end what @option{^-v^VERBOSE^} does
19507 for the back end. The system prints the name of each unit,
19508 either a compilation unit or nested unit, as it is being analyzed.
19509 @item
19510 Finally, you can start
19511 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19512 front-end of GNAT, and can be run independently (normally it is just
19513 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19514 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19515 @code{where} command is the first line of attack; the variable
19516 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19517 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19518 which the execution stopped, and @code{input_file name} indicates the name of
19519 the source file.
19520 @end enumerate
19521
19522 @node Naming Conventions for GNAT Source Files
19523 @section Naming Conventions for GNAT Source Files
19524
19525 @noindent
19526 In order to examine the workings of the GNAT system, the following
19527 brief description of its organization may be helpful:
19528
19529 @itemize @bullet
19530 @item
19531 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19532
19533 @item
19534 All files prefixed with @file{^par^PAR^} are components of the parser. The
19535 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
19536 parsing of select statements can be found in @file{par-ch9.adb}.
19537
19538 @item
19539 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19540 numbers correspond to chapters of the Ada standard. For example, all
19541 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19542 addition, some features of the language require sufficient special processing
19543 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19544 dynamic dispatching, etc.
19545
19546 @item
19547 All files prefixed with @file{^exp^EXP^} perform normalization and
19548 expansion of the intermediate representation (abstract syntax tree, or AST).
19549 these files use the same numbering scheme as the parser and semantics files.
19550 For example, the construction of record initialization procedures is done in
19551 @file{exp_ch3.adb}.
19552
19553 @item
19554 The files prefixed with @file{^bind^BIND^} implement the binder, which
19555 verifies the consistency of the compilation, determines an order of
19556 elaboration, and generates the bind file.
19557
19558 @item
19559 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19560 data structures used by the front-end.
19561
19562 @item
19563 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19564 the abstract syntax tree as produced by the parser.
19565
19566 @item
19567 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19568 all entities, computed during semantic analysis.
19569
19570 @item
19571 Library management issues are dealt with in files with prefix
19572 @file{^lib^LIB^}.
19573
19574 @item
19575 @findex Ada
19576 @cindex Annex A
19577 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19578 defined in Annex A.
19579
19580 @item
19581 @findex Interfaces
19582 @cindex Annex B
19583 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19584 defined in Annex B.
19585
19586 @item
19587 @findex System
19588 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19589 both language-defined children and GNAT run-time routines.
19590
19591 @item
19592 @findex GNAT
19593 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19594 general-purpose packages, fully documented in their specifications. All
19595 the other @file{.c} files are modifications of common @command{gcc} files.
19596 @end itemize
19597
19598 @node Getting Internal Debugging Information
19599 @section Getting Internal Debugging Information
19600
19601 @noindent
19602 Most compilers have internal debugging switches and modes. GNAT
19603 does also, except GNAT internal debugging switches and modes are not
19604 secret. A summary and full description of all the compiler and binder
19605 debug flags are in the file @file{debug.adb}. You must obtain the
19606 sources of the compiler to see the full detailed effects of these flags.
19607
19608 The switches that print the source of the program (reconstructed from
19609 the internal tree) are of general interest for user programs, as are the
19610 options to print
19611 the full internal tree, and the entity table (the symbol table
19612 information). The reconstructed source provides a readable version of the
19613 program after the front-end has completed analysis and  expansion,
19614 and is useful when studying the performance of specific constructs.
19615 For example, constraint checks are indicated, complex aggregates
19616 are replaced with loops and assignments, and tasking primitives
19617 are replaced with run-time calls.
19618
19619 @node Stack Traceback
19620 @section Stack Traceback
19621 @cindex traceback
19622 @cindex stack traceback
19623 @cindex stack unwinding
19624
19625 @noindent
19626 Traceback is a mechanism to display the sequence of subprogram calls that
19627 leads to a specified execution point in a program. Often (but not always)
19628 the execution point is an instruction at which an exception has been raised.
19629 This mechanism is also known as @i{stack unwinding} because it obtains
19630 its information by scanning the run-time stack and recovering the activation
19631 records of all active subprograms. Stack unwinding is one of the most
19632 important tools for program debugging.
19633
19634 The first entry stored in traceback corresponds to the deepest calling level,
19635 that is to say the subprogram currently executing the instruction
19636 from which we want to obtain the traceback.
19637
19638 Note that there is no runtime performance penalty when stack traceback
19639 is enabled, and no exception is raised during program execution.
19640
19641 @menu
19642 * Non-Symbolic Traceback::
19643 * Symbolic Traceback::
19644 @end menu
19645
19646 @node Non-Symbolic Traceback
19647 @subsection Non-Symbolic Traceback
19648 @cindex traceback, non-symbolic
19649
19650 @noindent
19651 Note: this feature is not supported on all platforms. See
19652 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19653 platforms.
19654
19655 @menu
19656 * Tracebacks From an Unhandled Exception::
19657 * Tracebacks From Exception Occurrences (non-symbolic)::
19658 * Tracebacks From Anywhere in a Program (non-symbolic)::
19659 @end menu
19660
19661 @node Tracebacks From an Unhandled Exception
19662 @subsubsection Tracebacks From an Unhandled Exception
19663
19664 @noindent
19665 A runtime non-symbolic traceback is a list of addresses of call instructions.
19666 To enable this feature you must use the @option{-E}
19667 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19668 of exception information. You can retrieve this information using the
19669 @code{addr2line} tool.
19670
19671 Here is a simple example:
19672
19673 @smallexample @c ada
19674 @cartouche
19675 procedure STB is
19676
19677    procedure P1 is
19678    begin
19679       raise Constraint_Error;
19680    end P1;
19681
19682    procedure P2 is
19683    begin
19684       P1;
19685    end P2;
19686
19687 begin
19688    P2;
19689 end STB;
19690 @end cartouche
19691 @end smallexample
19692
19693 @smallexample
19694 $ gnatmake stb -bargs -E
19695 $ stb
19696
19697 Execution terminated by unhandled exception
19698 Exception name: CONSTRAINT_ERROR
19699 Message: stb.adb:5
19700 Call stack traceback locations:
19701 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19702 @end smallexample
19703
19704 @noindent
19705 As we see the traceback lists a sequence of addresses for the unhandled
19706 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19707 guess that this exception come from procedure P1. To translate these
19708 addresses into the source lines where the calls appear, the
19709 @code{addr2line} tool, described below, is invaluable. The use of this tool
19710 requires the program to be compiled with debug information.
19711
19712 @smallexample
19713 $ gnatmake -g stb -bargs -E
19714 $ stb
19715
19716 Execution terminated by unhandled exception
19717 Exception name: CONSTRAINT_ERROR
19718 Message: stb.adb:5
19719 Call stack traceback locations:
19720 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19721
19722 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19723    0x4011f1 0x77e892a4
19724
19725 00401373 at d:/stb/stb.adb:5
19726 0040138B at d:/stb/stb.adb:10
19727 0040139C at d:/stb/stb.adb:14
19728 00401335 at d:/stb/b~stb.adb:104
19729 004011C4 at /build/.../crt1.c:200
19730 004011F1 at /build/.../crt1.c:222
19731 77E892A4 in ?? at ??:0
19732 @end smallexample
19733
19734 @noindent
19735 The @code{addr2line} tool has several other useful options:
19736
19737 @table @code
19738 @item --functions
19739 to get the function name corresponding to any location
19740
19741 @item --demangle=gnat
19742 to use the gnat decoding mode for the function names. Note that
19743 for binutils version 2.9.x the option is simply @option{--demangle}.
19744 @end table
19745
19746 @smallexample
19747 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19748    0x40139c 0x401335 0x4011c4 0x4011f1
19749
19750 00401373 in stb.p1 at d:/stb/stb.adb:5
19751 0040138B in stb.p2 at d:/stb/stb.adb:10
19752 0040139C in stb at d:/stb/stb.adb:14
19753 00401335 in main at d:/stb/b~stb.adb:104
19754 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
19755 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
19756 @end smallexample
19757
19758 @noindent
19759 From this traceback we can see that the exception was raised in
19760 @file{stb.adb} at line 5, which was reached from a procedure call in
19761 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19762 which contains the call to the main program.
19763 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19764 and the output will vary from platform to platform.
19765
19766 It is also possible to use @code{GDB} with these traceback addresses to debug
19767 the program. For example, we can break at a given code location, as reported
19768 in the stack traceback:
19769
19770 @smallexample
19771 $ gdb -nw stb
19772 @ifclear vms
19773 @noindent
19774 Furthermore, this feature is not implemented inside Windows DLL. Only
19775 the non-symbolic traceback is reported in this case.
19776 @end ifclear
19777
19778 (gdb) break *0x401373
19779 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19780 @end smallexample
19781
19782 @noindent
19783 It is important to note that the stack traceback addresses
19784 do not change when debug information is included. This is particularly useful
19785 because it makes it possible to release software without debug information (to
19786 minimize object size), get a field report that includes a stack traceback
19787 whenever an internal bug occurs, and then be able to retrieve the sequence
19788 of calls with the same program compiled with debug information.
19789
19790 @node Tracebacks From Exception Occurrences (non-symbolic)
19791 @subsubsection Tracebacks From Exception Occurrences
19792
19793 @noindent
19794 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19795 The stack traceback is attached to the exception information string, and can
19796 be retrieved in an exception handler within the Ada program, by means of the
19797 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19798
19799 @smallexample @c ada
19800 with Ada.Text_IO;
19801 with Ada.Exceptions;
19802
19803 procedure STB is
19804
19805    use Ada;
19806    use Ada.Exceptions;
19807
19808    procedure P1 is
19809       K : Positive := 1;
19810    begin
19811       K := K - 1;
19812    exception
19813       when E : others =>
19814          Text_IO.Put_Line (Exception_Information (E));
19815    end P1;
19816
19817    procedure P2 is
19818    begin
19819       P1;
19820    end P2;
19821
19822 begin
19823    P2;
19824 end STB;
19825 @end smallexample
19826
19827 @noindent
19828 This program will output:
19829
19830 @smallexample
19831 $ stb
19832
19833 Exception name: CONSTRAINT_ERROR
19834 Message: stb.adb:12
19835 Call stack traceback locations:
19836 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19837 @end smallexample
19838
19839 @node Tracebacks From Anywhere in a Program (non-symbolic)
19840 @subsubsection Tracebacks From Anywhere in a Program
19841
19842 @noindent
19843 It is also possible to retrieve a stack traceback from anywhere in a
19844 program. For this you need to
19845 use the @code{GNAT.Traceback} API. This package includes a procedure called
19846 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19847 display procedures described below. It is not necessary to use the
19848 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19849 is invoked explicitly.
19850
19851 @noindent
19852 In the following example we compute a traceback at a specific location in
19853 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19854 convert addresses to strings:
19855
19856 @smallexample @c ada
19857 with Ada.Text_IO;
19858 with GNAT.Traceback;
19859 with GNAT.Debug_Utilities;
19860
19861 procedure STB is
19862
19863    use Ada;
19864    use GNAT;
19865    use GNAT.Traceback;
19866
19867    procedure P1 is
19868       TB  : Tracebacks_Array (1 .. 10);
19869       --  We are asking for a maximum of 10 stack frames.
19870       Len : Natural;
19871       --  Len will receive the actual number of stack frames returned.
19872    begin
19873       Call_Chain (TB, Len);
19874
19875       Text_IO.Put ("In STB.P1 : ");
19876
19877       for K in 1 .. Len loop
19878          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19879          Text_IO.Put (' ');
19880       end loop;
19881
19882       Text_IO.New_Line;
19883    end P1;
19884
19885    procedure P2 is
19886    begin
19887       P1;
19888    end P2;
19889
19890 begin
19891    P2;
19892 end STB;
19893 @end smallexample
19894
19895 @smallexample
19896 $ gnatmake -g stb
19897 $ stb
19898
19899 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19900 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19901 @end smallexample
19902
19903 @noindent
19904 You can then get further information by invoking the @code{addr2line}
19905 tool as described earlier (note that the hexadecimal addresses
19906 need to be specified in C format, with a leading ``0x'').
19907
19908 @node Symbolic Traceback
19909 @subsection Symbolic Traceback
19910 @cindex traceback, symbolic
19911
19912 @noindent
19913 A symbolic traceback is a stack traceback in which procedure names are
19914 associated with each code location.
19915
19916 @noindent
19917 Note that this feature is not supported on all platforms. See
19918 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19919 list of currently supported platforms.
19920
19921 @noindent
19922 Note that the symbolic traceback requires that the program be compiled
19923 with debug information. If it is not compiled with debug information
19924 only the non-symbolic information will be valid.
19925
19926 @menu
19927 * Tracebacks From Exception Occurrences (symbolic)::
19928 * Tracebacks From Anywhere in a Program (symbolic)::
19929 @end menu
19930
19931 @node Tracebacks From Exception Occurrences (symbolic)
19932 @subsubsection Tracebacks From Exception Occurrences
19933
19934 @smallexample @c ada
19935 with Ada.Text_IO;
19936 with GNAT.Traceback.Symbolic;
19937
19938 procedure STB is
19939
19940    procedure P1 is
19941    begin
19942       raise Constraint_Error;
19943    end P1;
19944
19945    procedure P2 is
19946    begin
19947       P1;
19948    end P2;
19949
19950    procedure P3 is
19951    begin
19952       P2;
19953    end P3;
19954
19955 begin
19956    P3;
19957 exception
19958    when E : others =>
19959       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19960 end STB;
19961 @end smallexample
19962
19963 @smallexample
19964 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19965 $ stb
19966
19967 0040149F in stb.p1 at stb.adb:8
19968 004014B7 in stb.p2 at stb.adb:13
19969 004014CF in stb.p3 at stb.adb:18
19970 004015DD in ada.stb at stb.adb:22
19971 00401461 in main at b~stb.adb:168
19972 004011C4 in __mingw_CRTStartup at crt1.c:200
19973 004011F1 in mainCRTStartup at crt1.c:222
19974 77E892A4 in ?? at ??:0
19975 @end smallexample
19976
19977 @noindent
19978 In the above example the ``.\'' syntax in the @command{gnatmake} command
19979 is currently required by @command{addr2line} for files that are in
19980 the current working directory.
19981 Moreover, the exact sequence of linker options may vary from platform
19982 to platform.
19983 The above @option{-largs} section is for Windows platforms. By contrast,
19984 under Unix there is no need for the @option{-largs} section.
19985 Differences across platforms are due to details of linker implementation.
19986
19987 @node Tracebacks From Anywhere in a Program (symbolic)
19988 @subsubsection Tracebacks From Anywhere in a Program
19989
19990 @noindent
19991 It is possible to get a symbolic stack traceback
19992 from anywhere in a program, just as for non-symbolic tracebacks.
19993 The first step is to obtain a non-symbolic
19994 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19995 information. Here is an example:
19996
19997 @smallexample @c ada
19998 with Ada.Text_IO;
19999 with GNAT.Traceback;
20000 with GNAT.Traceback.Symbolic;
20001
20002 procedure STB is
20003
20004    use Ada;
20005    use GNAT.Traceback;
20006    use GNAT.Traceback.Symbolic;
20007
20008    procedure P1 is
20009       TB  : Tracebacks_Array (1 .. 10);
20010       --  We are asking for a maximum of 10 stack frames.
20011       Len : Natural;
20012       --  Len will receive the actual number of stack frames returned.
20013    begin
20014       Call_Chain (TB, Len);
20015       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20016    end P1;
20017
20018    procedure P2 is
20019    begin
20020       P1;
20021    end P2;
20022
20023 begin
20024    P2;
20025 end STB;
20026 @end smallexample
20027
20028 @ifset vms
20029 @node Compatibility with DEC Ada
20030 @chapter Compatibility with DEC Ada
20031 @cindex Compatibility
20032
20033 @noindent
20034 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
20035 OpenVMS Alpha. GNAT achieves a high level of compatibility
20036 with DEC Ada, and it should generally be straightforward to port code
20037 from the DEC Ada environment to GNAT. However, there are a few language
20038 and implementation differences of which the user must be aware. These
20039 differences are discussed in this section. In
20040 addition, the operating environment and command structure for the
20041 compiler are different, and these differences are also discussed.
20042
20043 Note that this discussion addresses specifically the implementation
20044 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
20045 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20046 GNAT always follows the Alpha implementation.
20047
20048 @menu
20049 * Ada 95 Compatibility::
20050 * Differences in the Definition of Package System::
20051 * Language-Related Features::
20052 * The Package STANDARD::
20053 * The Package SYSTEM::
20054 * Tasking and Task-Related Features::
20055 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
20056 * Pragmas and Pragma-Related Features::
20057 * Library of Predefined Units::
20058 * Bindings::
20059 * Main Program Definition::
20060 * Implementation-Defined Attributes::
20061 * Compiler and Run-Time Interfacing::
20062 * Program Compilation and Library Management::
20063 * Input-Output::
20064 * Implementation Limits::
20065 * Tools::
20066 @end menu
20067
20068 @node Ada 95 Compatibility
20069 @section Ada 95 Compatibility
20070
20071 @noindent
20072 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
20073 compiler. Ada 95 is almost completely upwards compatible
20074 with Ada 83, and therefore Ada 83 programs will compile
20075 and run under GNAT with
20076 no changes or only minor changes. The Ada 95 Reference
20077 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
20078 incompatibilities.
20079
20080 GNAT provides the switch /83 on the GNAT COMPILE command,
20081 as well as the pragma ADA_83, to force the compiler to
20082 operate in Ada 83 mode. This mode does not guarantee complete
20083 conformance to Ada 83, but in practice is sufficient to
20084 eliminate most sources of incompatibilities.
20085 In particular, it eliminates the recognition of the
20086 additional Ada 95 keywords, so that their use as identifiers
20087 in Ada83 program is legal, and handles the cases of packages
20088 with optional bodies, and generics that instantiate unconstrained
20089 types without the use of @code{(<>)}.
20090
20091 @node Differences in the Definition of Package System
20092 @section Differences in the Definition of Package System
20093
20094 @noindent
20095 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
20096 implementation-dependent declarations to package System. In normal mode,
20097 GNAT does not take advantage of this permission, and the version of System
20098 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
20099
20100 However, DEC Ada adds an extensive set of declarations to package System,
20101 as fully documented in the DEC Ada manuals. To minimize changes required
20102 for programs that make use of these extensions, GNAT provides the pragma
20103 Extend_System for extending the definition of package System. By using:
20104
20105 @smallexample @c ada
20106 @group
20107 @cartouche
20108 pragma Extend_System (Aux_DEC);
20109 @end cartouche
20110 @end group
20111 @end smallexample
20112
20113 @noindent
20114 The set of definitions in System is extended to include those in package
20115 @code{System.Aux_DEC}.
20116 These definitions are incorporated directly into package
20117 System, as though they had been declared there in the first place. For a
20118 list of the declarations added, see the specification of this package,
20119 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
20120 The pragma Extend_System is a configuration pragma, which means that
20121 it can be placed in the file @file{gnat.adc}, so that it will automatically
20122 apply to all subsequent compilations. See the section on Configuration
20123 Pragmas for further details.
20124
20125 An alternative approach that avoids the use of the non-standard
20126 Extend_System pragma is to add a context clause to the unit that
20127 references these facilities:
20128
20129 @smallexample @c ada
20130 @group
20131 @cartouche
20132 with System.Aux_DEC;
20133 use  System.Aux_DEC;
20134 @end cartouche
20135 @end group
20136 @end smallexample
20137
20138 @noindent
20139 The effect is not quite semantically identical to incorporating
20140 the declarations directly into package @code{System},
20141 but most programs will not notice a difference
20142 unless they use prefix notation (e.g. @code{System.Integer_8})
20143 to reference the
20144 entities directly in package @code{System}.
20145 For units containing such references,
20146 the prefixes must either be removed, or the pragma @code{Extend_System}
20147 must be used.
20148
20149 @node Language-Related Features
20150 @section Language-Related Features
20151
20152 @noindent
20153 The following sections highlight differences in types,
20154 representations of types, operations, alignment, and
20155 related topics.
20156
20157 @menu
20158 * Integer Types and Representations::
20159 * Floating-Point Types and Representations::
20160 * Pragmas Float_Representation and Long_Float::
20161 * Fixed-Point Types and Representations::
20162 * Record and Array Component Alignment::
20163 * Address Clauses::
20164 * Other Representation Clauses::
20165 @end menu
20166
20167 @node Integer Types and Representations
20168 @subsection Integer Types and Representations
20169
20170 @noindent
20171 The set of predefined integer types is identical in DEC Ada and GNAT.
20172 Furthermore the representation of these integer types is also identical,
20173 including the capability of size clauses forcing biased representation.
20174
20175 In addition,
20176 DEC Ada for OpenVMS Alpha systems has defined the
20177 following additional integer types in package System:
20178
20179 @itemize @bullet
20180
20181 @item
20182 INTEGER_8
20183
20184 @item
20185 INTEGER_16
20186
20187 @item
20188 INTEGER_32
20189
20190 @item
20191 INTEGER_64
20192
20193 @item
20194 LARGEST_INTEGER
20195 @end itemize
20196
20197 @noindent
20198 When using GNAT, the first four of these types may be obtained from the
20199 standard Ada 95 package @code{Interfaces}.
20200 Alternatively, by use of the pragma
20201 @code{Extend_System}, identical
20202 declarations can be referenced directly in package @code{System}.
20203 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
20204
20205 @node Floating-Point Types and Representations
20206 @subsection Floating-Point Types and Representations
20207 @cindex Floating-Point types
20208
20209 @noindent
20210 The set of predefined floating-point types is identical in DEC Ada and GNAT.
20211 Furthermore the representation of these floating-point
20212 types is also identical. One important difference is that the default
20213 representation for DEC Ada is VAX_Float, but the default representation
20214 for GNAT is IEEE.
20215
20216 Specific types may be declared to be VAX_Float or IEEE, using the pragma
20217 @code{Float_Representation} as described in the DEC Ada documentation.
20218 For example, the declarations:
20219
20220 @smallexample @c ada
20221 @group
20222 @cartouche
20223 type F_Float is digits 6;
20224 pragma Float_Representation (VAX_Float, F_Float);
20225 @end cartouche
20226 @end group
20227 @end smallexample
20228
20229 @noindent
20230 declare a type F_Float that will be represented in VAX_Float format.
20231 This set of declarations actually appears in System.Aux_DEC, which provides
20232 the full set of additional floating-point declarations provided in
20233 the DEC Ada version of package
20234 System. This and similar declarations may be accessed in a user program
20235 by using pragma @code{Extend_System}. The use of this
20236 pragma, and the related pragma @code{Long_Float} is described in further
20237 detail in the following section.
20238
20239 @node Pragmas Float_Representation and Long_Float
20240 @subsection Pragmas Float_Representation and Long_Float
20241
20242 @noindent
20243 DEC Ada provides the pragma @code{Float_Representation}, which
20244 acts as a program library switch to allow control over
20245 the internal representation chosen for the predefined
20246 floating-point types declared in the package @code{Standard}.
20247 The format of this pragma is as follows:
20248
20249 @smallexample
20250 @group
20251 @cartouche
20252 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
20253 @end cartouche
20254 @end group
20255 @end smallexample
20256
20257 @noindent
20258 This pragma controls the representation of floating-point
20259 types as follows:
20260
20261 @itemize @bullet
20262 @item
20263 @code{VAX_Float} specifies that floating-point
20264 types are represented by default with the VAX hardware types
20265 F-floating, D-floating, G-floating. Note that the H-floating
20266 type is available only on DIGITAL Vax systems, and is not available
20267 in either DEC Ada or GNAT for Alpha systems.
20268
20269 @item
20270 @code{IEEE_Float} specifies that floating-point
20271 types are represented by default with the IEEE single and
20272 double floating-point types.
20273 @end itemize
20274
20275 @noindent
20276 GNAT provides an identical implementation of the pragma
20277 @code{Float_Representation}, except that it functions as a
20278 configuration pragma, as defined by Ada 95. Note that the
20279 notion of configuration pragma corresponds closely to the
20280 DEC Ada notion of a program library switch.
20281
20282 When no pragma is used in GNAT, the default is IEEE_Float, which is different
20283 from DEC Ada 83, where the default is VAX_Float. In addition, the
20284 predefined libraries in GNAT are built using IEEE_Float, so it is not
20285 advisable to change the format of numbers passed to standard library
20286 routines, and if necessary explicit type conversions may be needed.
20287
20288 The use of IEEE_Float is recommended in GNAT since it is more efficient,
20289 and (given that it conforms to an international standard) potentially more
20290 portable. The situation in which VAX_Float may be useful is in interfacing
20291 to existing code and data that expects the use of VAX_Float. There are
20292 two possibilities here. If the requirement for the use of VAX_Float is
20293 localized, then the best approach is to use the predefined VAX_Float
20294 types in package @code{System}, as extended by
20295 @code{Extend_System}. For example, use @code{System.F_Float}
20296 to specify the 32-bit @code{F-Float} format.
20297
20298 Alternatively, if an entire program depends heavily on the use of
20299 the @code{VAX_Float} and in particular assumes that the types in
20300 package @code{Standard} are in @code{Vax_Float} format, then it
20301 may be desirable to reconfigure GNAT to assume Vax_Float by default.
20302 This is done by using the GNAT LIBRARY command to rebuild the library, and
20303 then using the general form of the @code{Float_Representation}
20304 pragma to ensure that this default format is used throughout.
20305 The form of the GNAT LIBRARY command is:
20306
20307 @smallexample
20308 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
20309 @end smallexample
20310
20311 @noindent
20312 where @i{file} contains the new configuration pragmas
20313 and @i{directory} is the directory to be created to contain
20314 the new library.
20315
20316 @noindent
20317 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
20318 to allow control over the internal representation chosen
20319 for the predefined type @code{Long_Float} and for floating-point
20320 type declarations with digits specified in the range 7 .. 15.
20321 The format of this pragma is as follows:
20322
20323 @smallexample @c ada
20324 @cartouche
20325 pragma Long_Float (D_FLOAT | G_FLOAT);
20326 @end cartouche
20327 @end smallexample
20328
20329 @node Fixed-Point Types and Representations
20330 @subsection Fixed-Point Types and Representations
20331
20332 @noindent
20333 On DEC Ada for OpenVMS Alpha systems, rounding is
20334 away from zero for both positive and negative numbers.
20335 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
20336
20337 On GNAT for OpenVMS Alpha, the results of operations
20338 on fixed-point types are in accordance with the Ada 95
20339 rules. In particular, results of operations on decimal
20340 fixed-point types are truncated.
20341
20342 @node Record and Array Component Alignment
20343 @subsection Record and Array Component Alignment
20344
20345 @noindent
20346 On DEC Ada for OpenVMS Alpha, all non composite components
20347 are aligned on natural boundaries. For example, 1-byte
20348 components are aligned on byte boundaries, 2-byte
20349 components on 2-byte boundaries, 4-byte components on 4-byte
20350 byte boundaries, and so on. The OpenVMS Alpha hardware
20351 runs more efficiently with naturally aligned data.
20352
20353 ON GNAT for OpenVMS Alpha, alignment rules are compatible
20354 with DEC Ada for OpenVMS Alpha.
20355
20356 @node Address Clauses
20357 @subsection Address Clauses
20358
20359 @noindent
20360 In DEC Ada and GNAT, address clauses are supported for
20361 objects and imported subprograms.
20362 The predefined type @code{System.Address} is a private type
20363 in both compilers, with the same representation (it is simply
20364 a machine pointer). Addition, subtraction, and comparison
20365 operations are available in the standard Ada 95 package
20366 @code{System.Storage_Elements}, or in package @code{System}
20367 if it is extended to include @code{System.Aux_DEC} using a
20368 pragma @code{Extend_System} as previously described.
20369
20370 Note that code that with's both this extended package @code{System}
20371 and the package @code{System.Storage_Elements} should not @code{use}
20372 both packages, or ambiguities will result. In general it is better
20373 not to mix these two sets of facilities. The Ada 95 package was
20374 designed specifically to provide the kind of features that DEC Ada
20375 adds directly to package @code{System}.
20376
20377 GNAT is compatible with DEC Ada in its handling of address
20378 clauses, except for some limitations in
20379 the form of address clauses for composite objects with
20380 initialization. Such address clauses are easily replaced
20381 by the use of an explicitly-defined constant as described
20382 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
20383 of declarations:
20384
20385 @smallexample @c ada
20386 @cartouche
20387 X, Y : Integer := Init_Func;
20388 Q : String (X .. Y) := "abc";
20389 ...
20390 for Q'Address use Compute_Address;
20391 @end cartouche
20392 @end smallexample
20393
20394 @noindent
20395 will be rejected by GNAT, since the address cannot be computed at the time
20396 that Q is declared. To achieve the intended effect, write instead:
20397
20398 @smallexample @c ada
20399 @group
20400 @cartouche
20401 X, Y : Integer := Init_Func;
20402 Q_Address : constant Address := Compute_Address;
20403 Q : String (X .. Y) := "abc";
20404 ...
20405 for Q'Address use Q_Address;
20406 @end cartouche
20407 @end group
20408 @end smallexample
20409
20410 @noindent
20411 which will be accepted by GNAT (and other Ada 95 compilers), and is also
20412 backwards compatible with Ada 83. A fuller description of the restrictions
20413 on address specifications is found in the GNAT Reference Manual.
20414
20415 @node Other Representation Clauses
20416 @subsection Other Representation Clauses
20417
20418 @noindent
20419 GNAT supports in a compatible manner all the representation
20420 clauses supported by DEC Ada. In addition, it
20421 supports representation clause forms that are new in Ada 95
20422 including COMPONENT_SIZE and SIZE clauses for objects.
20423
20424 @node The Package STANDARD
20425 @section The Package STANDARD
20426
20427 @noindent
20428 The package STANDARD, as implemented by DEC Ada, is fully
20429 described in the Reference Manual for the Ada Programming
20430 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
20431 Language Reference Manual. As implemented by GNAT, the
20432 package STANDARD is described in the Ada 95 Reference
20433 Manual.
20434
20435 In addition, DEC Ada supports the Latin-1 character set in
20436 the type CHARACTER. GNAT supports the Latin-1 character set
20437 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
20438 the type WIDE_CHARACTER.
20439
20440 The floating-point types supported by GNAT are those
20441 supported by DEC Ada, but defaults are different, and are controlled by
20442 pragmas. See @ref{Floating-Point Types and Representations} for details.
20443
20444 @node The Package SYSTEM
20445 @section The Package SYSTEM
20446
20447 @noindent
20448 DEC Ada provides a system-specific version of the package
20449 SYSTEM for each platform on which the language ships.
20450 For the complete specification of the package SYSTEM, see
20451 Appendix F of the DEC Ada Language Reference Manual.
20452
20453 On DEC Ada, the package SYSTEM includes the following conversion functions:
20454 @itemize @bullet
20455 @item TO_ADDRESS(INTEGER)
20456
20457 @item  TO_ADDRESS(UNSIGNED_LONGWORD)
20458
20459 @item  TO_ADDRESS(universal_integer)
20460
20461 @item  TO_INTEGER(ADDRESS)
20462
20463 @item  TO_UNSIGNED_LONGWORD(ADDRESS)
20464
20465 @item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
20466                  functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
20467 @end itemize
20468
20469 @noindent
20470 By default, GNAT supplies a version of SYSTEM that matches
20471 the definition given in the Ada 95 Reference Manual.
20472 This
20473 is a subset of the DIGITAL system definitions, which is as
20474 close as possible to the original definitions. The only difference
20475 is that the definition of SYSTEM_NAME is different:
20476
20477 @smallexample @c ada
20478 @group
20479 @cartouche
20480 type Name is (SYSTEM_NAME_GNAT);
20481 System_Name : constant Name := SYSTEM_NAME_GNAT;
20482 @end cartouche
20483 @end group
20484 @end smallexample
20485
20486 @noindent
20487 Also, GNAT adds the new Ada 95 declarations for
20488 BIT_ORDER and DEFAULT_BIT_ORDER.
20489
20490 However, the use of the following pragma causes GNAT
20491 to extend the definition of package SYSTEM so that it
20492 encompasses the full set of DIGITAL-specific extensions,
20493 including the functions listed above:
20494
20495 @smallexample @c ada
20496 @cartouche
20497 pragma Extend_System (Aux_DEC);
20498 @end cartouche
20499 @end smallexample
20500
20501 @noindent
20502 The pragma Extend_System is a configuration pragma that
20503 is most conveniently placed in the @file{gnat.adc} file. See the
20504 GNAT Reference Manual for further details.
20505
20506 DEC Ada does not allow the recompilation of the package
20507 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
20508 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
20509 the package SYSTEM. On OpenVMS Alpha systems, the pragma
20510 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
20511 its single argument.
20512
20513 GNAT does permit the recompilation of package SYSTEM using
20514 a special switch (@option{-gnatg}) and this switch can be used if
20515 it is necessary to modify the definitions in SYSTEM. GNAT does
20516 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
20517 or MEMORY_SIZE by any other means.
20518
20519 On GNAT systems, the pragma SYSTEM_NAME takes the
20520 enumeration literal SYSTEM_NAME_GNAT.
20521
20522 The definitions provided by the use of
20523
20524 @smallexample @c ada
20525 pragma Extend_System (AUX_Dec);
20526 @end smallexample
20527
20528 @noindent
20529 are virtually identical to those provided by the DEC Ada 83 package
20530 System. One important difference is that the name of the TO_ADDRESS
20531 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
20532 See the GNAT Reference manual for a discussion of why this change was
20533 necessary.
20534
20535 @noindent
20536 The version of TO_ADDRESS taking a universal integer argument is in fact
20537 an extension to Ada 83 not strictly compatible with the reference manual.
20538 In GNAT, we are constrained to be exactly compatible with the standard,
20539 and this means we cannot provide this capability. In DEC Ada 83, the
20540 point of this definition is to deal with a call like:
20541
20542 @smallexample @c ada
20543 TO_ADDRESS (16#12777#);
20544 @end smallexample
20545
20546 @noindent
20547 Normally, according to the Ada 83 standard, one would expect this to be
20548 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
20549 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
20550 definition using universal_integer takes precedence.
20551
20552 In GNAT, since the version with universal_integer cannot be supplied, it is
20553 not possible to be 100% compatible. Since there are many programs using
20554 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
20555 to change the name of the function in the UNSIGNED_LONGWORD case, so the
20556 declarations provided in the GNAT version of AUX_Dec are:
20557
20558 @smallexample @c ada
20559 function To_Address (X : Integer) return Address;
20560 pragma Pure_Function (To_Address);
20561
20562 function To_Address_Long (X : Unsigned_Longword) return Address;
20563 pragma Pure_Function (To_Address_Long);
20564 @end smallexample
20565
20566 @noindent
20567 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
20568 change the name to TO_ADDRESS_LONG.
20569
20570 @node Tasking and Task-Related Features
20571 @section Tasking and Task-Related Features
20572
20573 @noindent
20574 The concepts relevant to a comparison of tasking on GNAT
20575 and on DEC Ada for OpenVMS Alpha systems are discussed in
20576 the following sections.
20577
20578 For detailed information on concepts related to tasking in
20579 DEC Ada, see the DEC Ada Language Reference Manual and the
20580 relevant run-time reference manual.
20581
20582 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
20583 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
20584
20585 @noindent
20586 On OpenVMS Alpha systems, each Ada task (except a passive
20587 task) is implemented as a single stream of execution
20588 that is created and managed by the kernel. On these
20589 systems, DEC Ada tasking support is based on DECthreads,
20590 an implementation of the POSIX standard for threads.
20591
20592 Although tasks are implemented as threads, all tasks in
20593 an Ada program are part of the same process. As a result,
20594 resources such as open files and virtual memory can be
20595 shared easily among tasks. Having all tasks in one process
20596 allows better integration with the programming environment
20597 (the shell and the debugger, for example).
20598
20599 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
20600 code that calls DECthreads routines can be used together.
20601 The interaction between Ada tasks and DECthreads routines
20602 can have some benefits. For example when on OpenVMS Alpha,
20603 DEC Ada can call C code that is already threaded.
20604 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
20605 and Ada tasks are mapped to threads.
20606
20607 @menu
20608 * Assigning Task IDs::
20609 * Task IDs and Delays::
20610 * Task-Related Pragmas::
20611 * Scheduling and Task Priority::
20612 * The Task Stack::
20613 * External Interrupts::
20614 @end menu
20615
20616 @node Assigning Task IDs
20617 @subsection Assigning Task IDs
20618
20619 @noindent
20620 The DEC Ada Run-Time Library always assigns %TASK 1 to
20621 the environment task that executes the main program. On
20622 OpenVMS Alpha systems, %TASK 0 is often used for tasks
20623 that have been created but are not yet activated.
20624
20625 On OpenVMS Alpha systems, task IDs are assigned at
20626 activation. On GNAT systems, task IDs are also assigned at
20627 task creation but do not have the same form or values as
20628 task ID values in DEC Ada. There is no null task, and the
20629 environment task does not have a specific task ID value.
20630
20631 @node Task IDs and Delays
20632 @subsection Task IDs and Delays
20633
20634 @noindent
20635 On OpenVMS Alpha systems, tasking delays are implemented
20636 using Timer System Services. The Task ID is used for the
20637 identification of the timer request (the REQIDT parameter).
20638 If Timers are used in the application take care not to use
20639 0 for the identification, because cancelling such a timer
20640 will cancel all timers and may lead to unpredictable results.
20641
20642 @node Task-Related Pragmas
20643 @subsection Task-Related Pragmas
20644
20645 @noindent
20646 Ada supplies the pragma TASK_STORAGE, which allows
20647 specification of the size of the guard area for a task
20648 stack. (The guard area forms an area of memory that has no
20649 read or write access and thus helps in the detection of
20650 stack overflow.) On OpenVMS Alpha systems, if the pragma
20651 TASK_STORAGE specifies a value of zero, a minimal guard
20652 area is created. In the absence of a pragma TASK_STORAGE, a default guard
20653 area is created.
20654
20655 GNAT supplies the following task-related pragmas:
20656
20657 @itemize @bullet
20658 @item  TASK_INFO
20659
20660               This pragma appears within a task definition and
20661               applies to the task in which it appears. The argument
20662               must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
20663
20664 @item  TASK_STORAGE
20665
20666               GNAT implements pragma TASK_STORAGE in the same way as
20667               DEC Ada.
20668               Both DEC Ada and GNAT supply the pragmas PASSIVE,
20669               SUPPRESS, and VOLATILE.
20670 @end itemize
20671 @node Scheduling and Task Priority
20672 @subsection Scheduling and Task Priority
20673
20674 @noindent
20675 DEC Ada implements the Ada language requirement that
20676 when two tasks are eligible for execution and they have
20677 different priorities, the lower priority task does not
20678 execute while the higher priority task is waiting. The DEC
20679 Ada Run-Time Library keeps a task running until either the
20680 task is suspended or a higher priority task becomes ready.
20681
20682 On OpenVMS Alpha systems, the default strategy is round-
20683 robin with preemption. Tasks of equal priority take turns
20684 at the processor. A task is run for a certain period of
20685 time and then placed at the rear of the ready queue for
20686 its priority level.
20687
20688 DEC Ada provides the implementation-defined pragma TIME_SLICE,
20689 which can be used to enable or disable round-robin
20690 scheduling of tasks with the same priority.
20691 See the relevant DEC Ada run-time reference manual for
20692 information on using the pragmas to control DEC Ada task
20693 scheduling.
20694
20695 GNAT follows the scheduling rules of Annex D (real-time
20696 Annex) of the Ada 95 Reference Manual. In general, this
20697 scheduling strategy is fully compatible with DEC Ada
20698 although it provides some additional constraints (as
20699 fully documented in Annex D).
20700 GNAT implements time slicing control in a manner compatible with
20701 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
20702 to the DEC Ada 83 pragma of the same name.
20703 Note that it is not possible to mix GNAT tasking and
20704 DEC Ada 83 tasking in the same program, since the two run times are
20705 not compatible.
20706
20707 @node The Task Stack
20708 @subsection The Task Stack
20709
20710 @noindent
20711 In DEC Ada, a task stack is allocated each time a
20712 non passive task is activated. As soon as the task is
20713 terminated, the storage for the task stack is deallocated.
20714 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
20715 a default stack size is used. Also, regardless of the size
20716 specified, some additional space is allocated for task
20717 management purposes. On OpenVMS Alpha systems, at least
20718 one page is allocated.
20719
20720 GNAT handles task stacks in a similar manner. According to
20721 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
20722 an alternative method for controlling the task stack size.
20723 The specification of the attribute T'STORAGE_SIZE is also
20724 supported in a manner compatible with DEC Ada.
20725
20726 @node External Interrupts
20727 @subsection External Interrupts
20728
20729 @noindent
20730 On DEC Ada, external interrupts can be associated with task entries.
20731 GNAT is compatible with DEC Ada in its handling of external interrupts.
20732
20733 @node Pragmas and Pragma-Related Features
20734 @section Pragmas and Pragma-Related Features
20735
20736 @noindent
20737 Both DEC Ada and GNAT supply all language-defined pragmas
20738 as specified by the Ada 83 standard. GNAT also supplies all
20739 language-defined pragmas specified in the Ada 95 Reference Manual.
20740 In addition, GNAT implements the implementation-defined pragmas
20741 from DEC Ada 83.
20742
20743 @itemize @bullet
20744 @item  AST_ENTRY
20745
20746 @item  COMMON_OBJECT
20747
20748 @item  COMPONENT_ALIGNMENT
20749
20750 @item  EXPORT_EXCEPTION
20751
20752 @item  EXPORT_FUNCTION
20753
20754 @item  EXPORT_OBJECT
20755
20756 @item  EXPORT_PROCEDURE
20757
20758 @item  EXPORT_VALUED_PROCEDURE
20759
20760 @item  FLOAT_REPRESENTATION
20761
20762 @item  IDENT
20763
20764 @item  IMPORT_EXCEPTION
20765
20766 @item  IMPORT_FUNCTION
20767
20768 @item  IMPORT_OBJECT
20769
20770 @item  IMPORT_PROCEDURE
20771
20772 @item  IMPORT_VALUED_PROCEDURE
20773
20774 @item  INLINE_GENERIC
20775
20776 @item  INTERFACE_NAME
20777
20778 @item  LONG_FLOAT
20779
20780 @item  MAIN_STORAGE
20781
20782 @item  PASSIVE
20783
20784 @item  PSET_OBJECT
20785
20786 @item  SHARE_GENERIC
20787
20788 @item  SUPPRESS_ALL
20789
20790 @item  TASK_STORAGE
20791
20792 @item  TIME_SLICE
20793
20794 @item  TITLE
20795 @end itemize
20796
20797 @noindent
20798 These pragmas are all fully implemented, with the exception of @code{Title},
20799 @code{Passive}, and @code{Share_Generic}, which are
20800 recognized, but which have no
20801 effect in GNAT. The effect of @code{Passive} may be obtained by the
20802 use of protected objects in Ada 95. In GNAT, all generics are inlined.
20803
20804 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
20805 a separate subprogram specification which must appear before the
20806 subprogram body.
20807
20808 GNAT also supplies a number of implementation-defined pragmas as follows:
20809 @itemize @bullet
20810 @item  C_PASS_BY_COPY
20811
20812 @item  EXTEND_SYSTEM
20813
20814 @item  SOURCE_FILE_NAME
20815
20816 @item  UNSUPPRESS
20817
20818 @item  WARNINGS
20819
20820 @item  ABORT_DEFER
20821
20822 @item  ADA_83
20823
20824 @item  ADA_95
20825
20826 @item  ADA_05
20827
20828 @item  ANNOTATE
20829
20830 @item  ASSERT
20831
20832 @item  CPP_CLASS
20833
20834 @item  CPP_CONSTRUCTOR
20835
20836 @item  CPP_DESTRUCTOR
20837
20838 @item  CPP_VIRTUAL
20839
20840 @item  CP_VTABLE
20841
20842 @item  DEBUG
20843
20844 @item  LINKER_ALIAS
20845
20846 @item  LINKER_SECTION
20847
20848 @item  MACHINE_ATTRIBUTE
20849
20850 @item  NO_RETURN
20851
20852 @item  PURE_FUNCTION
20853
20854 @item  SOURCE_REFERENCE
20855
20856 @item  TASK_INFO
20857
20858 @item  UNCHECKED_UNION
20859
20860 @item  UNIMPLEMENTED_UNIT
20861
20862 @item  UNIVERSAL_DATA
20863
20864 @item  WEAK_EXTERNAL
20865 @end itemize
20866
20867 @noindent
20868 For full details on these GNAT implementation-defined pragmas, see
20869 the GNAT Reference Manual.
20870
20871 @menu
20872 * Restrictions on the Pragma INLINE::
20873 * Restrictions on the Pragma INTERFACE::
20874 * Restrictions on the Pragma SYSTEM_NAME::
20875 @end menu
20876
20877 @node Restrictions on the Pragma INLINE
20878 @subsection Restrictions on the Pragma INLINE
20879
20880 @noindent
20881 DEC Ada applies the following restrictions to the pragma INLINE:
20882 @itemize @bullet
20883 @item  Parameters cannot be a task type.
20884
20885 @item  Function results cannot be task types, unconstrained
20886 array types, or unconstrained types with discriminants.
20887
20888 @item  Bodies cannot declare the following:
20889 @itemize @bullet
20890 @item  Subprogram body or stub (imported subprogram is allowed)
20891
20892 @item  Tasks
20893
20894 @item  Generic declarations
20895
20896 @item  Instantiations
20897
20898 @item  Exceptions
20899
20900 @item  Access types (types derived from access types allowed)
20901
20902 @item  Array or record types
20903
20904 @item  Dependent tasks
20905
20906 @item  Direct recursive calls of subprogram or containing
20907 subprogram, directly or via a renaming
20908
20909 @end itemize
20910 @end itemize
20911
20912 @noindent
20913 In GNAT, the only restriction on pragma INLINE is that the
20914 body must occur before the call if both are in the same
20915 unit, and the size must be appropriately small. There are
20916 no other specific restrictions which cause subprograms to
20917 be incapable of being inlined.
20918
20919 @node  Restrictions on the Pragma INTERFACE
20920 @subsection  Restrictions on the Pragma INTERFACE
20921
20922 @noindent
20923 The following lists and describes the restrictions on the
20924 pragma INTERFACE on DEC Ada and GNAT:
20925 @itemize @bullet
20926 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
20927 Default is the default on OpenVMS Alpha systems.
20928
20929 @item  Parameter passing: Language specifies default
20930 mechanisms but can be overridden with an EXPORT pragma.
20931
20932 @itemize @bullet
20933 @item  Ada: Use internal Ada rules.
20934
20935 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
20936 record or task type. Result cannot be a string, an
20937 array, or a record.
20938
20939 @item  Fortran: Parameters cannot be a task. Result cannot
20940 be a string, an array, or a record.
20941 @end itemize
20942 @end itemize
20943
20944 @noindent
20945 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
20946 record parameters for all languages.
20947
20948 @node  Restrictions on the Pragma SYSTEM_NAME
20949 @subsection  Restrictions on the Pragma SYSTEM_NAME
20950
20951 @noindent
20952 For DEC Ada for OpenVMS Alpha, the enumeration literal
20953 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
20954 literal for the type NAME is SYSTEM_NAME_GNAT.
20955
20956 @node  Library of Predefined Units
20957 @section  Library of Predefined Units
20958
20959 @noindent
20960 A library of predefined units is provided as part of the
20961 DEC Ada and GNAT implementations. DEC Ada does not provide
20962 the package MACHINE_CODE but instead recommends importing
20963 assembler code.
20964
20965 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
20966 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20967 version. During GNAT installation, the DEC Ada Predefined
20968 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
20969 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
20970 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
20971 for details.
20972
20973 The GNAT RTL is contained in
20974 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
20975 the default search path is set up to find DECLIB units in preference
20976 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
20977 for example).
20978
20979 However, it is possible to change the default so that the
20980 reverse is true, or even to mix them using child package
20981 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
20982 is the package name, and the Ada units are available in the
20983 standard manner defined for Ada 95, that is to say as Ada.xxx. To
20984 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
20985 appropriately. For example, to change the default to use the Ada95
20986 versions do:
20987
20988 @smallexample
20989 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
20990                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20991 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
20992                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20993 @end smallexample
20994
20995 @menu
20996 * Changes to DECLIB::
20997 @end menu
20998
20999 @node Changes to DECLIB
21000 @subsection Changes to DECLIB
21001
21002 @noindent
21003 The changes made to the DEC Ada predefined library for GNAT and Ada 95
21004 compatibility are minor and include the following:
21005
21006 @itemize @bullet
21007 @item  Adjusting the location of pragmas and record representation
21008 clauses to obey Ada 95 rules
21009
21010 @item  Adding the proper notation to generic formal parameters
21011 that take unconstrained types in instantiation
21012
21013 @item  Adding pragma ELABORATE_BODY to package specifications
21014 that have package bodies not otherwise allowed
21015
21016 @item  Occurrences of the identifier @code{"PROTECTED"} are renamed to
21017 @code{"PROTECTD"}.
21018 Currently these are found only in the STARLET package spec.
21019 @end itemize
21020
21021 @noindent
21022 None of the above changes is visible to users.
21023
21024 @node Bindings
21025 @section Bindings
21026
21027 @noindent
21028 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
21029 @itemize @bullet
21030
21031 @item  Command Language Interpreter (CLI interface)
21032
21033 @item  DECtalk Run-Time Library (DTK interface)
21034
21035 @item  Librarian utility routines (LBR interface)
21036
21037 @item  General Purpose Run-Time Library (LIB interface)
21038
21039 @item  Math Run-Time Library (MTH interface)
21040
21041 @item  National Character Set Run-Time Library (NCS interface)
21042
21043 @item  Compiled Code Support Run-Time Library (OTS interface)
21044
21045 @item  Parallel Processing Run-Time Library (PPL interface)
21046
21047 @item  Screen Management Run-Time Library (SMG interface)
21048
21049 @item  Sort Run-Time Library (SOR interface)
21050
21051 @item  String Run-Time Library (STR interface)
21052
21053 @item STARLET System Library
21054 @findex Starlet
21055
21056 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
21057
21058 @item  X Windows Toolkit (XT interface)
21059
21060 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
21061 @end itemize
21062
21063 @noindent
21064 GNAT provides implementations of these DEC bindings in the DECLIB directory.
21065
21066 The X/Motif bindings used to build DECLIB are whatever versions are in the
21067 DEC Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21068 The build script will
21069 automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt},
21070 and @code{X_Lib}
21071 causing the default X/Motif sharable image libraries to be linked in. This
21072 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21073 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21074
21075 It may be necessary to edit these options files to update or correct the
21076 library names if, for example, the newer X/Motif bindings from
21077 @file{ADA$EXAMPLES}
21078 had been (previous to installing GNAT) copied and renamed to supersede the
21079 default @file{ADA$PREDEFINED} versions.
21080
21081 @menu
21082 * Shared Libraries and Options Files::
21083 * Interfaces to C::
21084 @end menu
21085
21086 @node Shared Libraries and Options Files
21087 @subsection Shared Libraries and Options Files
21088
21089 @noindent
21090 When using the DEC Ada
21091 predefined X and Motif bindings, the linking with their sharable images is
21092 done automatically by @command{GNAT LINK}.
21093 When using other X and Motif bindings, you need
21094 to add the corresponding sharable images to the command line for
21095 @code{GNAT LINK}. When linking with shared libraries, or with
21096 @file{.OPT} files, you must
21097 also add them to the command line for @command{GNAT LINK}.
21098
21099 A shared library to be used with GNAT is built in the same way as other
21100 libraries under VMS. The VMS Link command can be used in standard fashion.
21101
21102 @node Interfaces to C
21103 @subsection Interfaces to C
21104
21105 @noindent
21106 DEC Ada
21107 provides the following Ada types and operations:
21108
21109 @itemize @bullet
21110 @item C types package (C_TYPES)
21111
21112 @item C strings (C_TYPES.NULL_TERMINATED)
21113
21114 @item Other_types (SHORT_INT)
21115 @end itemize
21116
21117 @noindent
21118 Interfacing to C with GNAT, one can use the above approach
21119 described for DEC Ada or the facilities of Annex B of
21120 the Ada 95 Reference Manual (packages INTERFACES.C,
21121 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
21122 information, see the section ``Interfacing to C'' in the
21123 @cite{GNAT Reference Manual}.
21124
21125 The @option{-gnatF} qualifier forces default and explicit
21126 @code{External_Name} parameters in pragmas Import and Export
21127 to be uppercased for compatibility with the default behavior
21128 of Compaq C. The qualifier has no effect on @code{Link_Name} parameters.
21129
21130 @node Main Program Definition
21131 @section Main Program Definition
21132
21133 @noindent
21134 The following section discusses differences in the
21135 definition of main programs on DEC Ada and GNAT.
21136 On DEC Ada, main programs are defined to meet the
21137 following conditions:
21138 @itemize @bullet
21139 @item  Procedure with no formal parameters (returns 0 upon
21140        normal completion)
21141
21142 @item  Procedure with no formal parameters (returns 42 when
21143        unhandled exceptions are raised)
21144
21145 @item  Function with no formal parameters whose returned value
21146        is of a discrete type
21147
21148 @item  Procedure with one OUT formal of a discrete type for
21149        which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
21150
21151 @end itemize
21152
21153 @noindent
21154 When declared with the pragma EXPORT_VALUED_PROCEDURE,
21155 a main function or main procedure returns a discrete
21156 value whose size is less than 64 bits (32 on VAX systems),
21157 the value is zero- or sign-extended as appropriate.
21158 On GNAT, main programs are defined as follows:
21159 @itemize @bullet
21160 @item  Must be a non-generic, parameter-less subprogram that
21161 is either a procedure or function returning an Ada
21162 STANDARD.INTEGER (the predefined type)
21163
21164 @item  Cannot be a generic subprogram or an instantiation of a
21165 generic subprogram
21166 @end itemize
21167
21168 @node Implementation-Defined Attributes
21169 @section Implementation-Defined Attributes
21170
21171 @noindent
21172 GNAT provides all DEC Ada implementation-defined
21173 attributes.
21174
21175 @node Compiler and Run-Time Interfacing
21176 @section Compiler and Run-Time Interfacing
21177
21178 @noindent
21179 DEC Ada provides the following ways to pass options to the linker
21180 (ACS LINK):
21181 @itemize @bullet
21182 @item  /WAIT and /SUBMIT qualifiers
21183
21184 @item  /COMMAND qualifier
21185
21186 @item  /[NO]MAP qualifier
21187
21188 @item  /OUTPUT=file-spec
21189
21190 @item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
21191 @end itemize
21192
21193 @noindent
21194 To pass options to the linker, GNAT provides the following
21195 switches:
21196
21197 @itemize @bullet
21198 @item   @option{/EXECUTABLE=exec-name}
21199
21200 @item   @option{/VERBOSE qualifier}
21201
21202 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers
21203 @end itemize
21204
21205 @noindent
21206 For more information on these switches, see
21207 @ref{Switches for gnatlink}.
21208 In DEC Ada, the command-line switch @option{/OPTIMIZE} is available
21209 to control optimization. DEC Ada also supplies the
21210 following pragmas:
21211 @itemize @bullet
21212 @item  @code{OPTIMIZE}
21213
21214 @item  @code{INLINE}
21215
21216 @item  @code{INLINE_GENERIC}
21217
21218 @item  @code{SUPPRESS_ALL}
21219
21220 @item  @code{PASSIVE}
21221 @end itemize
21222
21223 @noindent
21224 In GNAT, optimization is controlled strictly by command
21225 line parameters, as described in the corresponding section of this guide.
21226 The DIGITAL pragmas for control of optimization are
21227 recognized but ignored.
21228
21229 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
21230 the default is that optimization is turned on.
21231
21232 @node Program Compilation and Library Management
21233 @section Program Compilation and Library Management
21234
21235 @noindent
21236 DEC Ada and GNAT provide a comparable set of commands to
21237 build programs. DEC Ada also provides a program library,
21238 which is a concept that does not exist on GNAT. Instead,
21239 GNAT provides directories of sources that are compiled as
21240 needed.
21241
21242 The following table summarizes
21243 the DEC Ada commands and provides
21244 equivalent GNAT commands. In this table, some GNAT
21245 equivalents reflect the fact that GNAT does not use the
21246 concept of a program library. Instead, it uses a model
21247 in which collections of source and object files are used
21248 in a manner consistent with other languages like C and
21249 Fortran. Therefore, standard system file commands are used
21250 to manipulate these elements. Those GNAT commands are marked with
21251 an asterisk.
21252 Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards.
21253
21254 @need 1500
21255 @multitable @columnfractions .35 .65
21256
21257 @item @emph{DEC Ada Command}
21258 @tab @emph{GNAT Equivalent / Description}
21259
21260 @item @command{ADA}
21261 @tab @command{GNAT COMPILE}@*
21262 Invokes the compiler to compile one or more Ada source files.
21263
21264 @item @command{ACS ATTACH}@*
21265 @tab [No equivalent]@*
21266 Switches control of terminal from current process running the program
21267 library manager.
21268
21269 @item @command{ACS CHECK}
21270 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21271 Forms the execution closure of one
21272 or more compiled units and checks completeness and currency.
21273
21274 @item @command{ACS COMPILE}
21275 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21276 Forms the execution closure of one or
21277 more specified units, checks completeness and currency,
21278 identifies units that have revised source files, compiles same,
21279 and recompiles units that are or will become obsolete.
21280 Also completes incomplete generic instantiations.
21281
21282 @item @command{ACS COPY FOREIGN}
21283 @tab Copy (*)@*
21284 Copies a foreign object file into the program library as a
21285 library unit body.
21286
21287 @item @command{ACS COPY UNIT}
21288 @tab Copy (*)@*
21289 Copies a compiled unit from one program library to another.
21290
21291 @item @command{ACS CREATE LIBRARY}
21292 @tab Create /directory (*)@*
21293 Creates a program library.
21294
21295 @item @command{ACS CREATE SUBLIBRARY}
21296 @tab Create /directory (*)@*
21297 Creates a program sublibrary.
21298
21299 @item @command{ACS DELETE LIBRARY}
21300 @tab @*
21301 Deletes a program library and its contents.
21302
21303 @item @command{ACS DELETE SUBLIBRARY}
21304 @tab @*
21305 Deletes a program sublibrary and its contents.
21306
21307 @item @command{ACS DELETE UNIT}
21308 @tab Delete file (*)@*
21309 On OpenVMS systems, deletes one or more compiled units from
21310 the current program library.
21311
21312 @item @command{ACS DIRECTORY}
21313 @tab Directory (*)@*
21314 On OpenVMS systems, lists units contained in the current
21315 program library.
21316
21317 @item @command{ACS ENTER FOREIGN}
21318 @tab Copy (*)@*
21319 Allows the import of a foreign body as an Ada library
21320 specification and enters a reference to a pointer.
21321
21322 @item @command{ACS ENTER UNIT}
21323 @tab Copy (*)@*
21324 Enters a reference (pointer) from the current program library to
21325 a unit compiled into another program library.
21326
21327 @item @command{ACS EXIT}
21328 @tab [No equivalent]@*
21329 Exits from the program library manager.
21330
21331 @item @command{ACS EXPORT}
21332 @tab Copy (*)@*
21333 Creates an object file that contains system-specific object code
21334 for one or more units. With GNAT, object files can simply be copied
21335 into the desired directory.
21336
21337 @item @command{ACS EXTRACT SOURCE}
21338 @tab Copy (*)@*
21339 Allows access to the copied source file for each Ada compilation unit
21340
21341 @item @command{ACS HELP}
21342 @tab @command{HELP GNAT}@*
21343 Provides online help.
21344
21345 @item @command{ACS LINK}
21346 @tab @command{GNAT LINK}@*
21347 Links an object file containing Ada units into an executable file.
21348
21349 @item @command{ACS LOAD}
21350 @tab Copy (*)@*
21351 Loads (partially compiles) Ada units into the program library.
21352 Allows loading a program from a collection of files into a library
21353 without knowing the relationship among units.
21354
21355 @item @command{ACS MERGE}
21356 @tab Copy (*)@*
21357 Merges into the current program library, one or more units from
21358 another library where they were modified.
21359
21360 @item @command{ACS RECOMPILE}
21361 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21362 Recompiles from   external or copied source files any obsolete
21363 unit in the closure. Also, completes any incomplete generic
21364 instantiations.
21365
21366 @item @command{ACS REENTER}
21367 @tab @command{GNAT MAKE}@*
21368 Reenters current references to units compiled after last entered
21369 with the @command{ACS ENTER UNIT} command.
21370
21371 @item @command{ACS SET LIBRARY}
21372 @tab Set default (*)@*
21373 Defines a program library to be the compilation context as well
21374 as the target library for compiler output and commands in general.
21375
21376 @item @command{ACS SET PRAGMA}
21377 @tab Edit @file{gnat.adc} (*)@*
21378 Redefines specified  values of the library characteristics
21379 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21380 and @code{Float_Representation}.
21381
21382 @item @command{ACS SET SOURCE}
21383 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21384 Defines the source file search list for the @command{ACS COMPILE} command.
21385
21386 @item @command{ACS SHOW LIBRARY}
21387 @tab Directory (*)@*
21388 Lists information about one or more program libraries.
21389
21390 @item @command{ACS SHOW PROGRAM}
21391 @tab [No equivalent]@*
21392 Lists information about the execution closure of one or
21393 more units in the program library.
21394
21395 @item @command{ACS SHOW SOURCE}
21396 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21397 Shows the source file search used when compiling units.
21398
21399 @item @command{ACS SHOW VERSION}
21400 @tab Compile with @option{VERBOSE} option
21401 Displays the version number of the compiler and program library
21402 manager used.
21403
21404 @item @command{ACS SPAWN}
21405 @tab [No equivalent]@*
21406 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21407 command).
21408
21409 @item @command{ACS VERIFY}
21410 @tab [No equivalent]@*
21411 Performs a series of consistency checks on a program library to
21412 determine whether the library structure and library files are in
21413 valid form.
21414 @end multitable
21415
21416 @noindent
21417
21418 @node Input-Output
21419 @section Input-Output
21420
21421 @noindent
21422 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
21423 Management Services (RMS) to perform operations on
21424 external files.
21425
21426 @noindent
21427 DEC Ada and GNAT predefine an identical set of input-
21428 output packages. To make the use of the
21429 generic TEXT_IO operations more convenient, DEC Ada
21430 provides predefined library packages that instantiate the
21431 integer and floating-point operations for the predefined
21432 integer and floating-point types as shown in the following table.
21433
21434 @multitable @columnfractions .45 .55
21435 @item @emph{Package Name} @tab Instantiation
21436
21437 @item @code{INTEGER_TEXT_IO}
21438 @tab @code{INTEGER_IO(INTEGER)}
21439
21440 @item @code{SHORT_INTEGER_TEXT_IO}
21441 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21442
21443 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21444 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21445
21446 @item @code{FLOAT_TEXT_IO}
21447 @tab @code{FLOAT_IO(FLOAT)}
21448
21449 @item @code{LONG_FLOAT_TEXT_IO}
21450 @tab @code{FLOAT_IO(LONG_FLOAT)}
21451 @end multitable
21452
21453 @noindent
21454 The DEC Ada predefined packages and their operations
21455 are implemented using OpenVMS Alpha files and input-
21456 output facilities. DEC Ada supports asynchronous input-
21457 output on OpenVMS Alpha. Familiarity with the following is
21458 recommended:
21459 @itemize @bullet
21460 @item  RMS file organizations and access methods
21461
21462 @item  OpenVMS file specifications and directories
21463
21464 @item  OpenVMS File Definition Language (FDL)
21465 @end itemize
21466
21467 @noindent
21468 GNAT provides I/O facilities that are completely
21469 compatible with DEC Ada. The distribution includes the
21470 standard DEC Ada versions of all I/O packages, operating
21471 in a manner compatible with DEC Ada. In particular, the
21472 following packages are by default the DEC Ada (Ada 83)
21473 versions of these packages rather than the renamings
21474 suggested in annex J of the Ada 95 Reference Manual:
21475 @itemize @bullet
21476 @item  @code{TEXT_IO}
21477
21478 @item  @code{SEQUENTIAL_IO}
21479
21480 @item  @code{DIRECT_IO}
21481 @end itemize
21482
21483 @noindent
21484 The use of the standard Ada 95 syntax for child packages (for
21485 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
21486 packages, as defined in the Ada 95 Reference Manual.
21487 GNAT provides DIGITAL-compatible predefined instantiations
21488 of the @code{TEXT_IO} packages, and also
21489 provides the standard predefined instantiations required
21490 by the Ada 95 Reference Manual.
21491
21492 For further information on how GNAT interfaces to the file
21493 system or how I/O is implemented in programs written in
21494 mixed languages, see the chapter ``Implementation of the
21495 Standard I/O'' in the @cite{GNAT Reference Manual}.
21496 This chapter covers the following:
21497 @itemize @bullet
21498 @item  Standard I/O packages
21499
21500 @item  @code{FORM} strings
21501
21502 @item  @code{ADA.DIRECT_IO}
21503
21504 @item  @code{ADA.SEQUENTIAL_IO}
21505
21506 @item  @code{ADA.TEXT_IO}
21507
21508 @item  Stream pointer positioning
21509
21510 @item  Reading and writing non-regular files
21511
21512 @item  @code{GET_IMMEDIATE}
21513
21514 @item  Treating @code{TEXT_IO} files as streams
21515
21516 @item  Shared files
21517
21518 @item  Open modes
21519 @end itemize
21520
21521 @node Implementation Limits
21522 @section Implementation Limits
21523
21524 @noindent
21525 The following table lists implementation limits for DEC Ada
21526 and GNAT systems.
21527 @multitable @columnfractions .60 .20 .20
21528 @sp 1
21529 @item  @emph{Compilation Parameter}
21530 @tab   @emph{DEC Ada}
21531 @tab   @emph{GNAT}
21532 @sp 1
21533
21534 @item  In a subprogram or entry  declaration, maximum number of
21535        formal parameters that are of an unconstrained record type
21536 @tab   32
21537 @tab   No set limit
21538 @sp 1
21539
21540 @item  Maximum identifier length (number of characters)
21541 @tab   255
21542 @tab   255
21543 @sp 1
21544
21545 @item  Maximum number of characters in a source line
21546 @tab   255
21547 @tab   255
21548 @sp 1
21549
21550 @item  Maximum collection size   (number of bytes)
21551 @tab   2**31-1
21552 @tab   2**31-1
21553 @sp 1
21554
21555 @item  Maximum number of discriminants for a record type
21556 @tab   245
21557 @tab   No set limit
21558 @sp 1
21559
21560 @item  Maximum number of formal parameters in an entry or
21561        subprogram declaration
21562 @tab   246
21563 @tab    No set limit
21564 @sp 1
21565
21566 @item  Maximum number of dimensions in an array type
21567 @tab   255
21568 @tab   No set limit
21569 @sp 1
21570
21571 @item  Maximum number of library  units and subunits in a compilation.
21572 @tab   4095
21573 @tab   No set limit
21574 @sp 1
21575
21576 @item  Maximum number of library units and subunits in an execution.
21577 @tab   16383
21578 @tab   No set limit
21579 @sp 1
21580
21581 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21582        or @code{PSECT_OBJECT}
21583 @tab   32757
21584 @tab   No set limit
21585 @sp 1
21586
21587 @item  Maximum number of enumeration literals in an enumeration type
21588        definition
21589 @tab   65535
21590 @tab   No set limit
21591 @sp 1
21592
21593 @item  Maximum number of lines in a source file
21594 @tab   65534
21595 @tab   No set limit
21596 @sp 1
21597
21598 @item  Maximum number of bits in any object
21599 @tab   2**31-1
21600 @tab   2**31-1
21601 @sp 1
21602
21603 @item  Maximum size of the static portion of a stack frame (approximate)
21604 @tab   2**31-1
21605 @tab   2**31-1
21606 @end multitable
21607
21608 @node  Tools
21609 @section Tools
21610
21611 @end ifset
21612
21613 @c **************************************
21614 @node Platform-Specific Information for the Run-Time Libraries
21615 @appendix Platform-Specific Information for the Run-Time Libraries
21616 @cindex Tasking and threads libraries
21617 @cindex Threads libraries and tasking
21618 @cindex Run-time libraries (platform-specific information)
21619
21620 @noindent
21621 The GNAT run-time implementation may vary with respect to both the
21622 underlying threads library and the exception handling scheme.
21623 For threads support, one or more of the following are supplied:
21624 @itemize @bullet
21625 @item @b{native threads library}, a binding to the thread package from
21626 the underlying operating system
21627
21628 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21629 POSIX thread package
21630 @end itemize
21631
21632 @noindent
21633 For exception handling, either or both of two models are supplied:
21634 @itemize @bullet
21635 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21636 Most programs should experience a substantial speed improvement by
21637 being compiled with a ZCX run-time.
21638 This is especially true for
21639 tasking applications or applications with many exception handlers.}
21640 @cindex Zero-Cost Exceptions
21641 @cindex ZCX (Zero-Cost Exceptions)
21642 which uses binder-generated tables that
21643 are interrogated at run time to locate a handler
21644
21645 @item @b{setjmp / longjmp} (``SJLJ''),
21646 @cindex setjmp/longjmp Exception Model
21647 @cindex SJLJ (setjmp/longjmp Exception Model)
21648 which uses dynamically-set data to establish
21649 the set of handlers
21650 @end itemize
21651
21652 @noindent
21653 This appendix summarizes which combinations of threads and exception support
21654 are supplied on various GNAT platforms.
21655 It then shows how to select a particular library either
21656 permanently or temporarily,
21657 explains the properties of (and tradeoffs among) the various threads
21658 libraries, and provides some additional
21659 information about several specific platforms.
21660
21661 @menu
21662 * Summary of Run-Time Configurations::
21663 * Specifying a Run-Time Library::
21664 * Choosing the Scheduling Policy::
21665 * Solaris-Specific Considerations::
21666 * IRIX-Specific Considerations::
21667 * Linux-Specific Considerations::
21668 * AIX-Specific Considerations::
21669 @end menu
21670
21671 @node Summary of Run-Time Configurations
21672 @section Summary of Run-Time Configurations
21673
21674 @multitable @columnfractions .30 .70
21675 @item @b{alpha-openvms}
21676 @item @code{@ @ }@i{rts-native (default)}
21677 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21678 @item @code{@ @ @ @ }Exceptions @tab ZCX
21679 @*
21680 @item @b{pa-hpux}
21681 @item @code{@ @ }@i{rts-native (default)}
21682 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
21683 @item @code{@ @ @ @ }Exceptions @tab ZCX
21684 @*
21685 @item @code{@ @ }@i{rts-sjlj}
21686 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
21687 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21688 @*
21689 @item @b{sparc-solaris}  @tab
21690 @item @code{@ @ }@i{rts-native (default)}
21691 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21692 @item @code{@ @ @ @ }Exceptions @tab ZCX
21693 @*
21694 @item @code{@ @ }@i{rts-m64}
21695 @item @code{@ @ @ @ }Tasking     @tab native Solaris threads library
21696 @item @code{@ @ @ @ }Exceptions  @tab ZCX
21697 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
21698 @item    @tab Use only on Solaris 8 or later.
21699 @item    @tab @xref{Building and Debugging 64-bit Applications}, for details.
21700 @*
21701 @item @code{@ @ }@i{rts-pthread}
21702 @item @code{@ @ @ @ }Tasking    @tab pthreads library
21703 @item @code{@ @ @ @ }Exceptions @tab ZCX
21704 @*
21705 @item @code{@ @ }@i{rts-sjlj}
21706 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21707 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21708 @*
21709 @item @b{x86-linux}
21710 @item @code{@ @ }@i{rts-native (default)}
21711 @item @code{@ @ @ @ }Tasking    @tab pthread library
21712 @item @code{@ @ @ @ }Exceptions @tab ZCX
21713 @*
21714 @item @code{@ @ }@i{rts-sjlj}
21715 @item @code{@ @ @ @ }Tasking    @tab pthread library
21716 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21717 @*
21718 @item @b{x86-windows}
21719 @item @code{@ @ }@i{rts-native (default)}
21720 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21721 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21722 @*
21723 @end multitable
21724
21725 @node Specifying a Run-Time Library
21726 @section Specifying a Run-Time Library
21727
21728 @noindent
21729 The @file{adainclude} subdirectory containing the sources of the GNAT
21730 run-time library, and the @file{adalib} subdirectory containing the
21731 @file{ALI} files and the static and/or shared GNAT library, are located
21732 in the gcc target-dependent area:
21733
21734 @smallexample
21735 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21736 @end smallexample
21737
21738 @noindent
21739 As indicated above, on some platforms several run-time libraries are supplied.
21740 These libraries are installed in the target dependent area and
21741 contain a complete source and binary subdirectory. The detailed description
21742 below explains the differences between the different libraries in terms of
21743 their thread support.
21744
21745 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21746 This default run time is selected by the means of soft links.
21747 For example on x86-linux:
21748
21749 @smallexample
21750 @group
21751  $(target-dir)
21752      |
21753      +--- adainclude----------+
21754      |                        |
21755      +--- adalib-----------+  |
21756      |                     |  |
21757      +--- rts-native       |  |
21758      |    |                |  |
21759      |    +--- adainclude <---+
21760      |    |                |
21761      |    +--- adalib <----+
21762      |
21763      +--- rts-sjlj
21764           |
21765           +--- adainclude
21766           |
21767           +--- adalib
21768 @end group
21769 @end smallexample
21770
21771 @noindent
21772 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21773 these soft links can be modified with the following commands:
21774
21775 @smallexample
21776 $ cd $target
21777 $ rm -f adainclude adalib
21778 $ ln -s rts-sjlj/adainclude adainclude
21779 $ ln -s rts-sjlj/adalib adalib
21780 @end smallexample
21781
21782 @noindent
21783 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21784 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21785 @file{$target/ada_object_path}.
21786
21787 Selecting another run-time library temporarily can be
21788 achieved by the regular mechanism for GNAT object or source path selection:
21789
21790 @itemize @bullet
21791 @item
21792 Set the environment variables:
21793
21794 @smallexample
21795 $ ADA_INCLUDE_PATH=$target/rts-sjlj/adainclude:$ADA_INCLUDE_PATH
21796 $ ADA_OBJECTS_PATH=$target/rts-sjlj/adalib:$ADA_OBJECTS_PATH
21797 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
21798 @end smallexample
21799
21800 @item
21801 Use @option{-aI$target/rts-sjlj/adainclude}
21802 and @option{-aO$target/rts-sjlj/adalib}
21803 on the @command{gnatmake} command line
21804
21805 @item
21806 Use the switch @option{--RTS}; e.g., @option{--RTS=sjlj}
21807 @cindex @option{--RTS} option
21808 @end itemize
21809
21810 @node Choosing the Scheduling Policy
21811 @section Choosing the Scheduling Policy
21812
21813 @noindent
21814 When using a POSIX threads implementation, you have a choice of several
21815 scheduling policies: @code{SCHED_FIFO},
21816 @cindex @code{SCHED_FIFO} scheduling policy
21817 @code{SCHED_RR}
21818 @cindex @code{SCHED_RR} scheduling policy
21819 and @code{SCHED_OTHER}.
21820 @cindex @code{SCHED_OTHER} scheduling policy
21821 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21822 or @code{SCHED_RR} requires special (e.g., root) privileges.
21823
21824 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21825 @code{SCHED_FIFO},
21826 @cindex @code{SCHED_FIFO} scheduling policy
21827 you can use one of the following:
21828
21829 @itemize @bullet
21830 @item
21831 @code{pragma Time_Slice (0.0)}
21832 @cindex pragma Time_Slice
21833 @item
21834 the corresponding binder option @option{-T0}
21835 @cindex @option{-T0} option
21836 @item
21837 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21838 @cindex pragma Task_Dispatching_Policy
21839 @end itemize
21840
21841 @noindent
21842 To specify @code{SCHED_RR},
21843 @cindex @code{SCHED_RR} scheduling policy
21844 you should use @code{pragma Time_Slice} with a
21845 value greater than @code{0.0}, or else use the corresponding @option{-T}
21846 binder option.
21847
21848 @node Solaris-Specific Considerations
21849 @section Solaris-Specific Considerations
21850 @cindex Solaris Sparc threads libraries
21851
21852 @noindent
21853 This section addresses some topics related to the various threads libraries
21854 on Sparc Solaris and then provides some information on building and
21855 debugging 64-bit applications.
21856
21857 @menu
21858 * Solaris Threads Issues::
21859 * Building and Debugging 64-bit Applications::
21860 @end menu
21861
21862 @node Solaris Threads Issues
21863 @subsection Solaris Threads Issues
21864
21865 @noindent
21866 GNAT under Solaris comes with an alternate tasking run-time library
21867 based on POSIX threads --- @emph{rts-pthread}.
21868 @cindex rts-pthread threads library
21869 This run-time library has the advantage of being mostly shared across all
21870 POSIX-compliant thread implementations, and it also provides under
21871 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21872 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21873 and @code{PTHREAD_PRIO_PROTECT}
21874 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21875 semantics that can be selected using the predefined pragma
21876 @code{Locking_Policy}
21877 @cindex pragma Locking_Policy (under rts-pthread)
21878 with respectively
21879 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21880 @cindex @code{Inheritance_Locking} (under rts-pthread)
21881 @cindex @code{Ceiling_Locking} (under rts-pthread)
21882
21883 As explained above, the native run-time library is based on the Solaris thread
21884 library (@code{libthread}) and is the default library.
21885
21886 When the Solaris threads library is used (this is the default), programs
21887 compiled with GNAT can automatically take advantage of
21888 and can thus execute on multiple processors.
21889 The user can alternatively specify a processor on which the program should run
21890 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21891 is made by
21892 setting the environment variable @code{GNAT_PROCESSOR}
21893 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21894 to one of the following:
21895
21896 @table @code
21897 @item -2
21898 Use the default configuration (run the program on all
21899          available processors) - this is the same as having
21900          @code{GNAT_PROCESSOR} unset
21901
21902 @item -1
21903 Let the run-time implementation choose one processor and run the program on
21904          that processor
21905
21906 @item 0 .. Last_Proc
21907 Run the program on the specified processor.
21908   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21909 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21910 @end table
21911
21912 @node Building and Debugging 64-bit Applications
21913 @subsection Building and Debugging 64-bit Applications
21914
21915 @noindent
21916 In a 64-bit application, all the sources involved must be compiled with the
21917 @option{-m64} command-line option, and a specific GNAT library (compiled with
21918 this option) is required.
21919 The easiest way to build a 64bit application is to add
21920 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
21921
21922 To debug these applications, a special version of gdb called @command{gdb64}
21923 needs to be used.
21924
21925 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
21926 amounts to:
21927
21928 @smallexample
21929      $ gnatmake -m64 -g --RTS=m64 hello.adb
21930      $ gdb64 hello
21931 @end smallexample
21932
21933 In addition, the following capabilities are not supported when using the
21934 @option{-m64} option:
21935
21936 @table @code
21937 @item -fstack-check does not work together with -m64.
21938 Any application combining these options crashes at startup time.
21939
21940 @item Call-chain backtrace computation does not work with -m64.
21941 Thus the gnatbind switch -E is not supported.
21942 @end table
21943
21944 @node IRIX-Specific Considerations
21945 @section IRIX-Specific Considerations
21946 @cindex IRIX thread library
21947
21948 @noindent
21949 On SGI IRIX, the thread library depends on which compiler is used.
21950 The @emph{o32 ABI} compiler comes with a run-time library based on the
21951 user-level @code{athread}
21952 library. Thus kernel-level capabilities such as nonblocking system
21953 calls or time slicing can only be achieved reliably by specifying different
21954 @code{sprocs} via the pragma @code{Task_Info}
21955 @cindex pragma Task_Info (and IRIX threads)
21956 and the
21957 @code{System.Task_Info} package.
21958 @cindex @code{System.Task_Info} package (and IRIX threads)
21959 See the @cite{GNAT Reference Manual} for further information.
21960
21961 The @emph{n32 ABI} compiler comes with a run-time library based on the
21962 kernel POSIX threads and thus does not have the limitations mentioned above.
21963
21964 @node Linux-Specific Considerations
21965 @section Linux-Specific Considerations
21966 @cindex Linux threads libraries
21967
21968 @noindent
21969 The default thread library under GNU/Linux has the following disadvantages
21970 compared to other native thread libraries:
21971
21972 @itemize @bullet
21973 @item The size of the task's stack is limited to 2 megabytes.
21974 @item  The signal model is not POSIX compliant, which means that to send a
21975   signal to the process, you need to send the signal to all threads,
21976   e.g. by using @code{killpg()}.
21977 @end itemize
21978
21979 @node AIX-Specific Considerations
21980 @section AIX-Specific Considerations
21981 @cindex AIX resolver library
21982
21983 @noindent
21984 On AIX, the resolver library initializes some internal structure on
21985 the first call to @code{get*by*} functions, which are used to implement
21986 @code{GNAT.Sockets.Get_Host_By_Name} and
21987 @code{GNAT.Sockets.Get_Host_By_Addrss}.
21988 If such initialization occurs within an Ada task, and the stack size for
21989 the task is the default size, a stack overflow may occur.
21990
21991 To avoid this overflow, the user should either ensure that the first call
21992 to @code{GNAT.Sockets.Get_Host_By_Name} or
21993 @code{GNAT.Sockets.Get_Host_By_Addrss}
21994 occurs in the environment task, or use @code{pragma Storage_Size} to
21995 specify a sufficiently large size for the stack of the task that contains
21996 this call.
21997
21998 @c *******************************
21999 @node Example of Binder Output File
22000 @appendix Example of Binder Output File
22001
22002 @noindent
22003 This Appendix displays the source code for @command{gnatbind}'s output
22004 file generated for a simple ``Hello World'' program.
22005 Comments have been added for clarification purposes.
22006
22007 @smallexample @c adanocomment
22008 @iftex
22009 @leftskip=0cm
22010 @end iftex
22011 --  The package is called Ada_Main unless this name is actually used
22012 --  as a unit name in the partition, in which case some other unique
22013 --  name is used.
22014
22015 with System;
22016 package ada_main is
22017
22018    Elab_Final_Code : Integer;
22019    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22020
22021    --  The main program saves the parameters (argument count,
22022    --  argument values, environment pointer) in global variables
22023    --  for later access by other units including
22024    --  Ada.Command_Line.
22025
22026    gnat_argc : Integer;
22027    gnat_argv : System.Address;
22028    gnat_envp : System.Address;
22029
22030    --  The actual variables are stored in a library routine. This
22031    --  is useful for some shared library situations, where there
22032    --  are problems if variables are not in the library.
22033
22034    pragma Import (C, gnat_argc);
22035    pragma Import (C, gnat_argv);
22036    pragma Import (C, gnat_envp);
22037
22038    --  The exit status is similarly an external location
22039
22040    gnat_exit_status : Integer;
22041    pragma Import (C, gnat_exit_status);
22042
22043    GNAT_Version : constant String :=
22044                     "GNAT Version: 3.15w (20010315)";
22045    pragma Export (C, GNAT_Version, "__gnat_version");
22046
22047    --  This is the generated adafinal routine that performs
22048    --  finalization at the end of execution. In the case where
22049    --  Ada is the main program, this main program makes a call
22050    --  to adafinal at program termination.
22051
22052    procedure adafinal;
22053    pragma Export (C, adafinal, "adafinal");
22054
22055    --  This is the generated adainit routine that performs
22056    --  initialization at the start of execution. In the case
22057    --  where Ada is the main program, this main program makes
22058    --  a call to adainit at program startup.
22059
22060    procedure adainit;
22061    pragma Export (C, adainit, "adainit");
22062
22063    --  This routine is called at the start of execution. It is
22064    --  a dummy routine that is used by the debugger to breakpoint
22065    --  at the start of execution.
22066
22067    procedure Break_Start;
22068    pragma Import (C, Break_Start, "__gnat_break_start");
22069
22070    --  This is the actual generated main program (it would be
22071    --  suppressed if the no main program switch were used). As
22072    --  required by standard system conventions, this program has
22073    --  the external name main.
22074
22075    function main
22076      (argc : Integer;
22077       argv : System.Address;
22078       envp : System.Address)
22079       return Integer;
22080    pragma Export (C, main, "main");
22081
22082    --  The following set of constants give the version
22083    --  identification values for every unit in the bound
22084    --  partition. This identification is computed from all
22085    --  dependent semantic units, and corresponds to the
22086    --  string that would be returned by use of the
22087    --  Body_Version or Version attributes.
22088
22089    type Version_32 is mod 2 ** 32;
22090    u00001 : constant Version_32 := 16#7880BEB3#;
22091    u00002 : constant Version_32 := 16#0D24CBD0#;
22092    u00003 : constant Version_32 := 16#3283DBEB#;
22093    u00004 : constant Version_32 := 16#2359F9ED#;
22094    u00005 : constant Version_32 := 16#664FB847#;
22095    u00006 : constant Version_32 := 16#68E803DF#;
22096    u00007 : constant Version_32 := 16#5572E604#;
22097    u00008 : constant Version_32 := 16#46B173D8#;
22098    u00009 : constant Version_32 := 16#156A40CF#;
22099    u00010 : constant Version_32 := 16#033DABE0#;
22100    u00011 : constant Version_32 := 16#6AB38FEA#;
22101    u00012 : constant Version_32 := 16#22B6217D#;
22102    u00013 : constant Version_32 := 16#68A22947#;
22103    u00014 : constant Version_32 := 16#18CC4A56#;
22104    u00015 : constant Version_32 := 16#08258E1B#;
22105    u00016 : constant Version_32 := 16#367D5222#;
22106    u00017 : constant Version_32 := 16#20C9ECA4#;
22107    u00018 : constant Version_32 := 16#50D32CB6#;
22108    u00019 : constant Version_32 := 16#39A8BB77#;
22109    u00020 : constant Version_32 := 16#5CF8FA2B#;
22110    u00021 : constant Version_32 := 16#2F1EB794#;
22111    u00022 : constant Version_32 := 16#31AB6444#;
22112    u00023 : constant Version_32 := 16#1574B6E9#;
22113    u00024 : constant Version_32 := 16#5109C189#;
22114    u00025 : constant Version_32 := 16#56D770CD#;
22115    u00026 : constant Version_32 := 16#02F9DE3D#;
22116    u00027 : constant Version_32 := 16#08AB6B2C#;
22117    u00028 : constant Version_32 := 16#3FA37670#;
22118    u00029 : constant Version_32 := 16#476457A0#;
22119    u00030 : constant Version_32 := 16#731E1B6E#;
22120    u00031 : constant Version_32 := 16#23C2E789#;
22121    u00032 : constant Version_32 := 16#0F1BD6A1#;
22122    u00033 : constant Version_32 := 16#7C25DE96#;
22123    u00034 : constant Version_32 := 16#39ADFFA2#;
22124    u00035 : constant Version_32 := 16#571DE3E7#;
22125    u00036 : constant Version_32 := 16#5EB646AB#;
22126    u00037 : constant Version_32 := 16#4249379B#;
22127    u00038 : constant Version_32 := 16#0357E00A#;
22128    u00039 : constant Version_32 := 16#3784FB72#;
22129    u00040 : constant Version_32 := 16#2E723019#;
22130    u00041 : constant Version_32 := 16#623358EA#;
22131    u00042 : constant Version_32 := 16#107F9465#;
22132    u00043 : constant Version_32 := 16#6843F68A#;
22133    u00044 : constant Version_32 := 16#63305874#;
22134    u00045 : constant Version_32 := 16#31E56CE1#;
22135    u00046 : constant Version_32 := 16#02917970#;
22136    u00047 : constant Version_32 := 16#6CCBA70E#;
22137    u00048 : constant Version_32 := 16#41CD4204#;
22138    u00049 : constant Version_32 := 16#572E3F58#;
22139    u00050 : constant Version_32 := 16#20729FF5#;
22140    u00051 : constant Version_32 := 16#1D4F93E8#;
22141    u00052 : constant Version_32 := 16#30B2EC3D#;
22142    u00053 : constant Version_32 := 16#34054F96#;
22143    u00054 : constant Version_32 := 16#5A199860#;
22144    u00055 : constant Version_32 := 16#0E7F912B#;
22145    u00056 : constant Version_32 := 16#5760634A#;
22146    u00057 : constant Version_32 := 16#5D851835#;
22147
22148    --  The following Export pragmas export the version numbers
22149    --  with symbolic names ending in B (for body) or S
22150    --  (for spec) so that they can be located in a link. The
22151    --  information provided here is sufficient to track down
22152    --  the exact versions of units used in a given build.
22153
22154    pragma Export (C, u00001, "helloB");
22155    pragma Export (C, u00002, "system__standard_libraryB");
22156    pragma Export (C, u00003, "system__standard_libraryS");
22157    pragma Export (C, u00004, "adaS");
22158    pragma Export (C, u00005, "ada__text_ioB");
22159    pragma Export (C, u00006, "ada__text_ioS");
22160    pragma Export (C, u00007, "ada__exceptionsB");
22161    pragma Export (C, u00008, "ada__exceptionsS");
22162    pragma Export (C, u00009, "gnatS");
22163    pragma Export (C, u00010, "gnat__heap_sort_aB");
22164    pragma Export (C, u00011, "gnat__heap_sort_aS");
22165    pragma Export (C, u00012, "systemS");
22166    pragma Export (C, u00013, "system__exception_tableB");
22167    pragma Export (C, u00014, "system__exception_tableS");
22168    pragma Export (C, u00015, "gnat__htableB");
22169    pragma Export (C, u00016, "gnat__htableS");
22170    pragma Export (C, u00017, "system__exceptionsS");
22171    pragma Export (C, u00018, "system__machine_state_operationsB");
22172    pragma Export (C, u00019, "system__machine_state_operationsS");
22173    pragma Export (C, u00020, "system__machine_codeS");
22174    pragma Export (C, u00021, "system__storage_elementsB");
22175    pragma Export (C, u00022, "system__storage_elementsS");
22176    pragma Export (C, u00023, "system__secondary_stackB");
22177    pragma Export (C, u00024, "system__secondary_stackS");
22178    pragma Export (C, u00025, "system__parametersB");
22179    pragma Export (C, u00026, "system__parametersS");
22180    pragma Export (C, u00027, "system__soft_linksB");
22181    pragma Export (C, u00028, "system__soft_linksS");
22182    pragma Export (C, u00029, "system__stack_checkingB");
22183    pragma Export (C, u00030, "system__stack_checkingS");
22184    pragma Export (C, u00031, "system__tracebackB");
22185    pragma Export (C, u00032, "system__tracebackS");
22186    pragma Export (C, u00033, "ada__streamsS");
22187    pragma Export (C, u00034, "ada__tagsB");
22188    pragma Export (C, u00035, "ada__tagsS");
22189    pragma Export (C, u00036, "system__string_opsB");
22190    pragma Export (C, u00037, "system__string_opsS");
22191    pragma Export (C, u00038, "interfacesS");
22192    pragma Export (C, u00039, "interfaces__c_streamsB");
22193    pragma Export (C, u00040, "interfaces__c_streamsS");
22194    pragma Export (C, u00041, "system__file_ioB");
22195    pragma Export (C, u00042, "system__file_ioS");
22196    pragma Export (C, u00043, "ada__finalizationB");
22197    pragma Export (C, u00044, "ada__finalizationS");
22198    pragma Export (C, u00045, "system__finalization_rootB");
22199    pragma Export (C, u00046, "system__finalization_rootS");
22200    pragma Export (C, u00047, "system__finalization_implementationB");
22201    pragma Export (C, u00048, "system__finalization_implementationS");
22202    pragma Export (C, u00049, "system__string_ops_concat_3B");
22203    pragma Export (C, u00050, "system__string_ops_concat_3S");
22204    pragma Export (C, u00051, "system__stream_attributesB");
22205    pragma Export (C, u00052, "system__stream_attributesS");
22206    pragma Export (C, u00053, "ada__io_exceptionsS");
22207    pragma Export (C, u00054, "system__unsigned_typesS");
22208    pragma Export (C, u00055, "system__file_control_blockS");
22209    pragma Export (C, u00056, "ada__finalization__list_controllerB");
22210    pragma Export (C, u00057, "ada__finalization__list_controllerS");
22211
22212    -- BEGIN ELABORATION ORDER
22213    -- ada (spec)
22214    -- gnat (spec)
22215    -- gnat.heap_sort_a (spec)
22216    -- gnat.heap_sort_a (body)
22217    -- gnat.htable (spec)
22218    -- gnat.htable (body)
22219    -- interfaces (spec)
22220    -- system (spec)
22221    -- system.machine_code (spec)
22222    -- system.parameters (spec)
22223    -- system.parameters (body)
22224    -- interfaces.c_streams (spec)
22225    -- interfaces.c_streams (body)
22226    -- system.standard_library (spec)
22227    -- ada.exceptions (spec)
22228    -- system.exception_table (spec)
22229    -- system.exception_table (body)
22230    -- ada.io_exceptions (spec)
22231    -- system.exceptions (spec)
22232    -- system.storage_elements (spec)
22233    -- system.storage_elements (body)
22234    -- system.machine_state_operations (spec)
22235    -- system.machine_state_operations (body)
22236    -- system.secondary_stack (spec)
22237    -- system.stack_checking (spec)
22238    -- system.soft_links (spec)
22239    -- system.soft_links (body)
22240    -- system.stack_checking (body)
22241    -- system.secondary_stack (body)
22242    -- system.standard_library (body)
22243    -- system.string_ops (spec)
22244    -- system.string_ops (body)
22245    -- ada.tags (spec)
22246    -- ada.tags (body)
22247    -- ada.streams (spec)
22248    -- system.finalization_root (spec)
22249    -- system.finalization_root (body)
22250    -- system.string_ops_concat_3 (spec)
22251    -- system.string_ops_concat_3 (body)
22252    -- system.traceback (spec)
22253    -- system.traceback (body)
22254    -- ada.exceptions (body)
22255    -- system.unsigned_types (spec)
22256    -- system.stream_attributes (spec)
22257    -- system.stream_attributes (body)
22258    -- system.finalization_implementation (spec)
22259    -- system.finalization_implementation (body)
22260    -- ada.finalization (spec)
22261    -- ada.finalization (body)
22262    -- ada.finalization.list_controller (spec)
22263    -- ada.finalization.list_controller (body)
22264    -- system.file_control_block (spec)
22265    -- system.file_io (spec)
22266    -- system.file_io (body)
22267    -- ada.text_io (spec)
22268    -- ada.text_io (body)
22269    -- hello (body)
22270    -- END ELABORATION ORDER
22271
22272 end ada_main;
22273
22274 --  The following source file name pragmas allow the generated file
22275 --  names to be unique for different main programs. They are needed
22276 --  since the package name will always be Ada_Main.
22277
22278 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22279 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22280
22281 --  Generated package body for Ada_Main starts here
22282
22283 package body ada_main is
22284
22285    --  The actual finalization is performed by calling the
22286    --  library routine in System.Standard_Library.Adafinal
22287
22288    procedure Do_Finalize;
22289    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22290
22291    -------------
22292    -- adainit --
22293    -------------
22294
22295 @findex adainit
22296    procedure adainit is
22297
22298       --  These booleans are set to True once the associated unit has
22299       --  been elaborated. It is also used to avoid elaborating the
22300       --  same unit twice.
22301
22302       E040 : Boolean;
22303       pragma Import (Ada, E040, "interfaces__c_streams_E");
22304
22305       E008 : Boolean;
22306       pragma Import (Ada, E008, "ada__exceptions_E");
22307
22308       E014 : Boolean;
22309       pragma Import (Ada, E014, "system__exception_table_E");
22310
22311       E053 : Boolean;
22312       pragma Import (Ada, E053, "ada__io_exceptions_E");
22313
22314       E017 : Boolean;
22315       pragma Import (Ada, E017, "system__exceptions_E");
22316
22317       E024 : Boolean;
22318       pragma Import (Ada, E024, "system__secondary_stack_E");
22319
22320       E030 : Boolean;
22321       pragma Import (Ada, E030, "system__stack_checking_E");
22322
22323       E028 : Boolean;
22324       pragma Import (Ada, E028, "system__soft_links_E");
22325
22326       E035 : Boolean;
22327       pragma Import (Ada, E035, "ada__tags_E");
22328
22329       E033 : Boolean;
22330       pragma Import (Ada, E033, "ada__streams_E");
22331
22332       E046 : Boolean;
22333       pragma Import (Ada, E046, "system__finalization_root_E");
22334
22335       E048 : Boolean;
22336       pragma Import (Ada, E048, "system__finalization_implementation_E");
22337
22338       E044 : Boolean;
22339       pragma Import (Ada, E044, "ada__finalization_E");
22340
22341       E057 : Boolean;
22342       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22343
22344       E055 : Boolean;
22345       pragma Import (Ada, E055, "system__file_control_block_E");
22346
22347       E042 : Boolean;
22348       pragma Import (Ada, E042, "system__file_io_E");
22349
22350       E006 : Boolean;
22351       pragma Import (Ada, E006, "ada__text_io_E");
22352
22353       --  Set_Globals is a library routine that stores away the
22354       --  value of the indicated set of global values in global
22355       --  variables within the library.
22356
22357       procedure Set_Globals
22358         (Main_Priority            : Integer;
22359          Time_Slice_Value         : Integer;
22360          WC_Encoding              : Character;
22361          Locking_Policy           : Character;
22362          Queuing_Policy           : Character;
22363          Task_Dispatching_Policy  : Character;
22364          Adafinal                 : System.Address;
22365          Unreserve_All_Interrupts : Integer;
22366          Exception_Tracebacks     : Integer);
22367 @findex __gnat_set_globals
22368       pragma Import (C, Set_Globals, "__gnat_set_globals");
22369
22370       --  SDP_Table_Build is a library routine used to build the
22371       --  exception tables. See unit Ada.Exceptions in files
22372       --  a-except.ads/adb for full details of how zero cost
22373       --  exception handling works. This procedure, the call to
22374       --  it, and the two following tables are all omitted if the
22375       --  build is in longjmp/setjump exception mode.
22376
22377 @findex SDP_Table_Build
22378 @findex Zero Cost Exceptions
22379       procedure SDP_Table_Build
22380         (SDP_Addresses   : System.Address;
22381          SDP_Count       : Natural;
22382          Elab_Addresses  : System.Address;
22383          Elab_Addr_Count : Natural);
22384       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22385
22386       --  Table of Unit_Exception_Table addresses. Used for zero
22387       --  cost exception handling to build the top level table.
22388
22389       ST : aliased constant array (1 .. 23) of System.Address := (
22390         Hello'UET_Address,
22391         Ada.Text_Io'UET_Address,
22392         Ada.Exceptions'UET_Address,
22393         Gnat.Heap_Sort_A'UET_Address,
22394         System.Exception_Table'UET_Address,
22395         System.Machine_State_Operations'UET_Address,
22396         System.Secondary_Stack'UET_Address,
22397         System.Parameters'UET_Address,
22398         System.Soft_Links'UET_Address,
22399         System.Stack_Checking'UET_Address,
22400         System.Traceback'UET_Address,
22401         Ada.Streams'UET_Address,
22402         Ada.Tags'UET_Address,
22403         System.String_Ops'UET_Address,
22404         Interfaces.C_Streams'UET_Address,
22405         System.File_Io'UET_Address,
22406         Ada.Finalization'UET_Address,
22407         System.Finalization_Root'UET_Address,
22408         System.Finalization_Implementation'UET_Address,
22409         System.String_Ops_Concat_3'UET_Address,
22410         System.Stream_Attributes'UET_Address,
22411         System.File_Control_Block'UET_Address,
22412         Ada.Finalization.List_Controller'UET_Address);
22413
22414       --  Table of addresses of elaboration routines. Used for
22415       --  zero cost exception handling to make sure these
22416       --  addresses are included in the top level procedure
22417       --  address table.
22418
22419       EA : aliased constant array (1 .. 23) of System.Address := (
22420         adainit'Code_Address,
22421         Do_Finalize'Code_Address,
22422         Ada.Exceptions'Elab_Spec'Address,
22423         System.Exceptions'Elab_Spec'Address,
22424         Interfaces.C_Streams'Elab_Spec'Address,
22425         System.Exception_Table'Elab_Body'Address,
22426         Ada.Io_Exceptions'Elab_Spec'Address,
22427         System.Stack_Checking'Elab_Spec'Address,
22428         System.Soft_Links'Elab_Body'Address,
22429         System.Secondary_Stack'Elab_Body'Address,
22430         Ada.Tags'Elab_Spec'Address,
22431         Ada.Tags'Elab_Body'Address,
22432         Ada.Streams'Elab_Spec'Address,
22433         System.Finalization_Root'Elab_Spec'Address,
22434         Ada.Exceptions'Elab_Body'Address,
22435         System.Finalization_Implementation'Elab_Spec'Address,
22436         System.Finalization_Implementation'Elab_Body'Address,
22437         Ada.Finalization'Elab_Spec'Address,
22438         Ada.Finalization.List_Controller'Elab_Spec'Address,
22439         System.File_Control_Block'Elab_Spec'Address,
22440         System.File_Io'Elab_Body'Address,
22441         Ada.Text_Io'Elab_Spec'Address,
22442         Ada.Text_Io'Elab_Body'Address);
22443
22444    --  Start of processing for adainit
22445
22446    begin
22447
22448       --  Call SDP_Table_Build to build the top level procedure
22449       --  table for zero cost exception handling (omitted in
22450       --  longjmp/setjump mode).
22451
22452       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22453
22454       --  Call Set_Globals to record various information for
22455       --  this partition.  The values are derived by the binder
22456       --  from information stored in the ali files by the compiler.
22457
22458 @findex __gnat_set_globals
22459       Set_Globals
22460         (Main_Priority            => -1,
22461          --  Priority of main program, -1 if no pragma Priority used
22462
22463          Time_Slice_Value         => -1,
22464          --  Time slice from Time_Slice pragma, -1 if none used
22465
22466          WC_Encoding              => 'b',
22467          --  Wide_Character encoding used, default is brackets
22468
22469          Locking_Policy           => ' ',
22470          --  Locking_Policy used, default of space means not
22471          --  specified, otherwise it is the first character of
22472          --  the policy name.
22473
22474          Queuing_Policy           => ' ',
22475          --  Queuing_Policy used, default of space means not
22476          --  specified, otherwise it is the first character of
22477          --  the policy name.
22478
22479          Task_Dispatching_Policy  => ' ',
22480          --  Task_Dispatching_Policy used, default of space means
22481          --  not specified, otherwise first character of the
22482          --  policy name.
22483
22484          Adafinal                 => System.Null_Address,
22485          --  Address of Adafinal routine, not used anymore
22486
22487          Unreserve_All_Interrupts => 0,
22488          --  Set true if pragma Unreserve_All_Interrupts was used
22489
22490          Exception_Tracebacks     => 0);
22491          --  Indicates if exception tracebacks are enabled
22492
22493       Elab_Final_Code := 1;
22494
22495       --  Now we have the elaboration calls for all units in the partition.
22496       --  The Elab_Spec and Elab_Body attributes generate references to the
22497       --  implicit elaboration procedures generated by the compiler for
22498       --  each unit that requires elaboration.
22499
22500       if not E040 then
22501          Interfaces.C_Streams'Elab_Spec;
22502       end if;
22503       E040 := True;
22504       if not E008 then
22505          Ada.Exceptions'Elab_Spec;
22506       end if;
22507       if not E014 then
22508          System.Exception_Table'Elab_Body;
22509          E014 := True;
22510       end if;
22511       if not E053 then
22512          Ada.Io_Exceptions'Elab_Spec;
22513          E053 := True;
22514       end if;
22515       if not E017 then
22516          System.Exceptions'Elab_Spec;
22517          E017 := True;
22518       end if;
22519       if not E030 then
22520          System.Stack_Checking'Elab_Spec;
22521       end if;
22522       if not E028 then
22523          System.Soft_Links'Elab_Body;
22524          E028 := True;
22525       end if;
22526       E030 := True;
22527       if not E024 then
22528          System.Secondary_Stack'Elab_Body;
22529          E024 := True;
22530       end if;
22531       if not E035 then
22532          Ada.Tags'Elab_Spec;
22533       end if;
22534       if not E035 then
22535          Ada.Tags'Elab_Body;
22536          E035 := True;
22537       end if;
22538       if not E033 then
22539          Ada.Streams'Elab_Spec;
22540          E033 := True;
22541       end if;
22542       if not E046 then
22543          System.Finalization_Root'Elab_Spec;
22544       end if;
22545       E046 := True;
22546       if not E008 then
22547          Ada.Exceptions'Elab_Body;
22548          E008 := True;
22549       end if;
22550       if not E048 then
22551          System.Finalization_Implementation'Elab_Spec;
22552       end if;
22553       if not E048 then
22554          System.Finalization_Implementation'Elab_Body;
22555          E048 := True;
22556       end if;
22557       if not E044 then
22558          Ada.Finalization'Elab_Spec;
22559       end if;
22560       E044 := True;
22561       if not E057 then
22562          Ada.Finalization.List_Controller'Elab_Spec;
22563       end if;
22564       E057 := True;
22565       if not E055 then
22566          System.File_Control_Block'Elab_Spec;
22567          E055 := True;
22568       end if;
22569       if not E042 then
22570          System.File_Io'Elab_Body;
22571          E042 := True;
22572       end if;
22573       if not E006 then
22574          Ada.Text_Io'Elab_Spec;
22575       end if;
22576       if not E006 then
22577          Ada.Text_Io'Elab_Body;
22578          E006 := True;
22579       end if;
22580
22581       Elab_Final_Code := 0;
22582    end adainit;
22583
22584    --------------
22585    -- adafinal --
22586    --------------
22587
22588 @findex adafinal
22589    procedure adafinal is
22590    begin
22591       Do_Finalize;
22592    end adafinal;
22593
22594    ----------
22595    -- main --
22596    ----------
22597
22598    --  main is actually a function, as in the ANSI C standard,
22599    --  defined to return the exit status. The three parameters
22600    --  are the argument count, argument values and environment
22601    --  pointer.
22602
22603 @findex Main Program
22604    function main
22605      (argc : Integer;
22606       argv : System.Address;
22607       envp : System.Address)
22608       return Integer
22609    is
22610       --  The initialize routine performs low level system
22611       --  initialization using a standard library routine which
22612       --  sets up signal handling and performs any other
22613       --  required setup. The routine can be found in file
22614       --  a-init.c.
22615
22616 @findex __gnat_initialize
22617       procedure initialize;
22618       pragma Import (C, initialize, "__gnat_initialize");
22619
22620       --  The finalize routine performs low level system
22621       --  finalization using a standard library routine. The
22622       --  routine is found in file a-final.c and in the standard
22623       --  distribution is a dummy routine that does nothing, so
22624       --  really this is a hook for special user finalization.
22625
22626 @findex __gnat_finalize
22627       procedure finalize;
22628       pragma Import (C, finalize, "__gnat_finalize");
22629
22630       --  We get to the main program of the partition by using
22631       --  pragma Import because if we try to with the unit and
22632       --  call it Ada style, then not only do we waste time
22633       --  recompiling it, but also, we don't really know the right
22634       --  switches (e.g. identifier character set) to be used
22635       --  to compile it.
22636
22637       procedure Ada_Main_Program;
22638       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22639
22640    --  Start of processing for main
22641
22642    begin
22643       --  Save global variables
22644
22645       gnat_argc := argc;
22646       gnat_argv := argv;
22647       gnat_envp := envp;
22648
22649       --  Call low level system initialization
22650
22651       Initialize;
22652
22653       --  Call our generated Ada initialization routine
22654
22655       adainit;
22656
22657       --  This is the point at which we want the debugger to get
22658       --  control
22659
22660       Break_Start;
22661
22662       --  Now we call the main program of the partition
22663
22664       Ada_Main_Program;
22665
22666       --  Perform Ada finalization
22667
22668       adafinal;
22669
22670       --  Perform low level system finalization
22671
22672       Finalize;
22673
22674       --  Return the proper exit status
22675       return (gnat_exit_status);
22676    end;
22677
22678 --  This section is entirely comments, so it has no effect on the
22679 --  compilation of the Ada_Main package. It provides the list of
22680 --  object files and linker options, as well as some standard
22681 --  libraries needed for the link. The gnatlink utility parses
22682 --  this b~hello.adb file to read these comment lines to generate
22683 --  the appropriate command line arguments for the call to the
22684 --  system linker. The BEGIN/END lines are used for sentinels for
22685 --  this parsing operation.
22686
22687 --  The exact file names will of course depend on the environment,
22688 --  host/target and location of files on the host system.
22689
22690 @findex Object file list
22691 -- BEGIN Object file/option list
22692    --   ./hello.o
22693    --   -L./
22694    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22695    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22696 -- END Object file/option list
22697
22698 end ada_main;
22699 @end smallexample
22700
22701 @noindent
22702 The Ada code in the above example is exactly what is generated by the
22703 binder. We have added comments to more clearly indicate the function
22704 of each part of the generated @code{Ada_Main} package.
22705
22706 The code is standard Ada in all respects, and can be processed by any
22707 tools that handle Ada. In particular, it is possible to use the debugger
22708 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22709 suppose that for reasons that you do not understand, your program is crashing
22710 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22711 you can place a breakpoint on the call:
22712
22713 @smallexample @c ada
22714 Ada.Text_Io'Elab_Body;
22715 @end smallexample
22716
22717 @noindent
22718 and trace the elaboration routine for this package to find out where
22719 the problem might be (more usually of course you would be debugging
22720 elaboration code in your own application).
22721
22722 @node Elaboration Order Handling in GNAT
22723 @appendix Elaboration Order Handling in GNAT
22724 @cindex Order of elaboration
22725 @cindex Elaboration control
22726
22727 @menu
22728 * Elaboration Code in Ada 95::
22729 * Checking the Elaboration Order in Ada 95::
22730 * Controlling the Elaboration Order in Ada 95::
22731 * Controlling Elaboration in GNAT - Internal Calls::
22732 * Controlling Elaboration in GNAT - External Calls::
22733 * Default Behavior in GNAT - Ensuring Safety::
22734 * Treatment of Pragma Elaborate::
22735 * Elaboration Issues for Library Tasks::
22736 * Mixing Elaboration Models::
22737 * What to Do If the Default Elaboration Behavior Fails::
22738 * Elaboration for Access-to-Subprogram Values::
22739 * Summary of Procedures for Elaboration Control::
22740 * Other Elaboration Order Considerations::
22741 @end menu
22742
22743 @noindent
22744 This chapter describes the handling of elaboration code in Ada 95 and
22745 in GNAT, and discusses how the order of elaboration of program units can
22746 be controlled in GNAT, either automatically or with explicit programming
22747 features.
22748
22749 @node Elaboration Code in Ada 95
22750 @section Elaboration Code in Ada 95
22751
22752 @noindent
22753 Ada 95 provides rather general mechanisms for executing code at elaboration
22754 time, that is to say before the main program starts executing. Such code arises
22755 in three contexts:
22756
22757 @table @asis
22758 @item Initializers for variables.
22759 Variables declared at the library level, in package specs or bodies, can
22760 require initialization that is performed at elaboration time, as in:
22761 @smallexample @c ada
22762 @cartouche
22763 Sqrt_Half : Float := Sqrt (0.5);
22764 @end cartouche
22765 @end smallexample
22766
22767 @item Package initialization code
22768 Code in a @code{BEGIN-END} section at the outer level of a package body is
22769 executed as part of the package body elaboration code.
22770
22771 @item Library level task allocators
22772 Tasks that are declared using task allocators at the library level
22773 start executing immediately and hence can execute at elaboration time.
22774 @end table
22775
22776 @noindent
22777 Subprogram calls are possible in any of these contexts, which means that
22778 any arbitrary part of the program may be executed as part of the elaboration
22779 code. It is even possible to write a program which does all its work at
22780 elaboration time, with a null main program, although stylistically this
22781 would usually be considered an inappropriate way to structure
22782 a program.
22783
22784 An important concern arises in the context of elaboration code:
22785 we have to be sure that it is executed in an appropriate order. What we
22786 have is a series of elaboration code sections, potentially one section
22787 for each unit in the program. It is important that these execute
22788 in the correct order. Correctness here means that, taking the above
22789 example of the declaration of @code{Sqrt_Half},
22790 if some other piece of
22791 elaboration code references @code{Sqrt_Half},
22792 then it must run after the
22793 section of elaboration code that contains the declaration of
22794 @code{Sqrt_Half}.
22795
22796 There would never be any order of elaboration problem if we made a rule
22797 that whenever you @code{with} a unit, you must elaborate both the spec and body
22798 of that unit before elaborating the unit doing the @code{with}'ing:
22799
22800 @smallexample @c ada
22801 @group
22802 @cartouche
22803 with Unit_1;
22804 package Unit_2 is ...
22805 @end cartouche
22806 @end group
22807 @end smallexample
22808
22809 @noindent
22810 would require that both the body and spec of @code{Unit_1} be elaborated
22811 before the spec of @code{Unit_2}. However, a rule like that would be far too
22812 restrictive. In particular, it would make it impossible to have routines
22813 in separate packages that were mutually recursive.
22814
22815 You might think that a clever enough compiler could look at the actual
22816 elaboration code and determine an appropriate correct order of elaboration,
22817 but in the general case, this is not possible. Consider the following
22818 example.
22819
22820 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22821 that references
22822 the variable @code{Sqrt_1}, which is declared in the elaboration code
22823 of the body of @code{Unit_1}:
22824
22825 @smallexample @c ada
22826 @cartouche
22827 Sqrt_1 : Float := Sqrt (0.1);
22828 @end cartouche
22829 @end smallexample
22830
22831 @noindent
22832 The elaboration code of the body of @code{Unit_1} also contains:
22833
22834 @smallexample @c ada
22835 @group
22836 @cartouche
22837 if expression_1 = 1 then
22838    Q := Unit_2.Func_2;
22839 end if;
22840 @end cartouche
22841 @end group
22842 @end smallexample
22843
22844 @noindent
22845 @code{Unit_2} is exactly parallel,
22846 it has a procedure @code{Func_2} that references
22847 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22848 the body @code{Unit_2}:
22849
22850 @smallexample @c ada
22851 @cartouche
22852 Sqrt_2 : Float := Sqrt (0.1);
22853 @end cartouche
22854 @end smallexample
22855
22856 @noindent
22857 The elaboration code of the body of @code{Unit_2} also contains:
22858
22859 @smallexample @c ada
22860 @group
22861 @cartouche
22862 if expression_2 = 2 then
22863    Q := Unit_1.Func_1;
22864 end if;
22865 @end cartouche
22866 @end group
22867 @end smallexample
22868
22869 @noindent
22870 Now the question is, which of the following orders of elaboration is
22871 acceptable:
22872
22873 @smallexample
22874 @group
22875 Spec of Unit_1
22876 Spec of Unit_2
22877 Body of Unit_1
22878 Body of Unit_2
22879 @end group
22880 @end smallexample
22881
22882 @noindent
22883 or
22884
22885 @smallexample
22886 @group
22887 Spec of Unit_2
22888 Spec of Unit_1
22889 Body of Unit_2
22890 Body of Unit_1
22891 @end group
22892 @end smallexample
22893
22894 @noindent
22895 If you carefully analyze the flow here, you will see that you cannot tell
22896 at compile time the answer to this question.
22897 If @code{expression_1} is not equal to 1,
22898 and @code{expression_2} is not equal to 2,
22899 then either order is acceptable, because neither of the function calls is
22900 executed. If both tests evaluate to true, then neither order is acceptable
22901 and in fact there is no correct order.
22902
22903 If one of the two expressions is true, and the other is false, then one
22904 of the above orders is correct, and the other is incorrect. For example,
22905 if @code{expression_1} = 1 and @code{expression_2} /= 2,
22906 then the call to @code{Func_2}
22907 will occur, but not the call to @code{Func_1.}
22908 This means that it is essential
22909 to elaborate the body of @code{Unit_1} before
22910 the body of @code{Unit_2}, so the first
22911 order of elaboration is correct and the second is wrong.
22912
22913 By making @code{expression_1} and @code{expression_2}
22914 depend on input data, or perhaps
22915 the time of day, we can make it impossible for the compiler or binder
22916 to figure out which of these expressions will be true, and hence it
22917 is impossible to guarantee a safe order of elaboration at run time.
22918
22919 @node Checking the Elaboration Order in Ada 95
22920 @section Checking the Elaboration Order in Ada 95
22921
22922 @noindent
22923 In some languages that involve the same kind of elaboration problems,
22924 e.g. Java and C++, the programmer is expected to worry about these
22925 ordering problems himself, and it is common to
22926 write a program in which an incorrect elaboration order  gives
22927 surprising results, because it references variables before they
22928 are initialized.
22929 Ada 95 is designed to be a safe language, and a programmer-beware approach is
22930 clearly not sufficient. Consequently, the language provides three lines
22931 of defense:
22932
22933 @table @asis
22934 @item Standard rules
22935 Some standard rules restrict the possible choice of elaboration
22936 order. In particular, if you @code{with} a unit, then its spec is always
22937 elaborated before the unit doing the @code{with}. Similarly, a parent
22938 spec is always elaborated before the child spec, and finally
22939 a spec is always elaborated before its corresponding body.
22940
22941 @item Dynamic elaboration checks
22942 @cindex Elaboration checks
22943 @cindex Checks, elaboration
22944 Dynamic checks are made at run time, so that if some entity is accessed
22945 before it is elaborated (typically  by means of a subprogram call)
22946 then the exception (@code{Program_Error}) is raised.
22947
22948 @item Elaboration control
22949 Facilities are provided for the programmer to specify the desired order
22950 of elaboration.
22951 @end table
22952
22953 Let's look at these facilities in more detail. First, the rules for
22954 dynamic checking. One possible rule would be simply to say that the
22955 exception is raised if you access a variable which has not yet been
22956 elaborated. The trouble with this approach is that it could require
22957 expensive checks on every variable reference. Instead Ada 95 has two
22958 rules which are a little more restrictive, but easier to check, and
22959 easier to state:
22960
22961 @table @asis
22962 @item Restrictions on calls
22963 A subprogram can only be called at elaboration time if its body
22964 has been elaborated. The rules for elaboration given above guarantee
22965 that the spec of the subprogram has been elaborated before the
22966 call, but not the body. If this rule is violated, then the
22967 exception @code{Program_Error} is raised.
22968
22969 @item Restrictions on instantiations
22970 A generic unit can only be instantiated if the body of the generic
22971 unit has been elaborated. Again, the rules for elaboration given above
22972 guarantee that the spec of the generic unit has been elaborated
22973 before the instantiation, but not the body. If this rule is
22974 violated, then the exception @code{Program_Error} is raised.
22975 @end table
22976
22977 @noindent
22978 The idea is that if the body has been elaborated, then any variables
22979 it references must have been elaborated; by checking for the body being
22980 elaborated we guarantee that none of its references causes any
22981 trouble. As we noted above, this is a little too restrictive, because a
22982 subprogram that has no non-local references in its body may in fact be safe
22983 to call. However, it really would be unsafe to rely on this, because
22984 it would mean that the caller was aware of details of the implementation
22985 in the body. This goes against the basic tenets of Ada.
22986
22987 A plausible implementation can be described as follows.
22988 A Boolean variable is associated with each subprogram
22989 and each generic unit. This variable is initialized to False, and is set to
22990 True at the point body is elaborated. Every call or instantiation checks the
22991 variable, and raises @code{Program_Error} if the variable is False.
22992
22993 Note that one might think that it would be good enough to have one Boolean
22994 variable for each package, but that would not deal with cases of trying
22995 to call a body in the same package as the call
22996 that has not been elaborated yet.
22997 Of course a compiler may be able to do enough analysis to optimize away
22998 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
22999 does such optimizations, but still the easiest conceptual model is to
23000 think of there being one variable per subprogram.
23001
23002 @node Controlling the Elaboration Order in Ada 95
23003 @section Controlling the Elaboration Order in Ada 95
23004
23005 @noindent
23006 In the previous section we discussed the rules in Ada 95 which ensure
23007 that @code{Program_Error} is raised if an incorrect elaboration order is
23008 chosen. This prevents erroneous executions, but we need mechanisms to
23009 specify a correct execution and avoid the exception altogether.
23010 To achieve this, Ada 95 provides a number of features for controlling
23011 the order of elaboration. We discuss these features in this section.
23012
23013 First, there are several ways of indicating to the compiler that a given
23014 unit has no elaboration problems:
23015
23016 @table @asis
23017 @item packages that do not require a body
23018 In Ada 95, a library package that does not require a body does not permit
23019 a body. This means that if we have a such a package, as in:
23020
23021 @smallexample @c ada
23022 @group
23023 @cartouche
23024 package Definitions is
23025    generic
23026       type m is new integer;
23027    package Subp is
23028       type a is array (1 .. 10) of m;
23029       type b is array (1 .. 20) of m;
23030    end Subp;
23031 end Definitions;
23032 @end cartouche
23033 @end group
23034 @end smallexample
23035
23036 @noindent
23037 A package that @code{with}'s @code{Definitions} may safely instantiate
23038 @code{Definitions.Subp} because the compiler can determine that there
23039 definitely is no package body to worry about in this case
23040
23041 @item pragma Pure
23042 @cindex pragma Pure
23043 @findex Pure
23044 Places sufficient restrictions on a unit to guarantee that
23045 no call to any subprogram in the unit can result in an
23046 elaboration problem. This means that the compiler does not need
23047 to worry about the point of elaboration of such units, and in
23048 particular, does not need to check any calls to any subprograms
23049 in this unit.
23050
23051 @item pragma Preelaborate
23052 @findex Preelaborate
23053 @cindex pragma Preelaborate
23054 This pragma places slightly less stringent restrictions on a unit than
23055 does pragma Pure,
23056 but these restrictions are still sufficient to ensure that there
23057 are no elaboration problems with any calls to the unit.
23058
23059 @item pragma Elaborate_Body
23060 @findex Elaborate_Body
23061 @cindex pragma Elaborate_Body
23062 This pragma requires that the body of a unit be elaborated immediately
23063 after its spec. Suppose a unit @code{A} has such a pragma,
23064 and unit @code{B} does
23065 a @code{with} of unit @code{A}. Recall that the standard rules require
23066 the spec of unit @code{A}
23067 to be elaborated before the @code{with}'ing unit; given the pragma in
23068 @code{A}, we also know that the body of @code{A}
23069 will be elaborated before @code{B}, so
23070 that calls to @code{A} are safe and do not need a check.
23071 @end table
23072
23073 @noindent
23074 Note that,
23075 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23076 the use of
23077 @code{Elaborate_Body} does not guarantee that the program is
23078 free of elaboration problems, because it may not be possible
23079 to satisfy the requested elaboration order.
23080 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23081 If a programmer
23082 marks @code{Unit_1} as @code{Elaborate_Body},
23083 and not @code{Unit_2,} then the order of
23084 elaboration will be:
23085
23086 @smallexample
23087 @group
23088 Spec of Unit_2
23089 Spec of Unit_1
23090 Body of Unit_1
23091 Body of Unit_2
23092 @end group
23093 @end smallexample
23094
23095 @noindent
23096 Now that means that the call to @code{Func_1} in @code{Unit_2}
23097 need not be checked,
23098 it must be safe. But the call to @code{Func_2} in
23099 @code{Unit_1} may still fail if
23100 @code{Expression_1} is equal to 1,
23101 and the programmer must still take
23102 responsibility for this not being the case.
23103
23104 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23105 eliminated, except for calls entirely within a body, which are
23106 in any case fully under programmer control. However, using the pragma
23107 everywhere is not always possible.
23108 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23109 we marked both of them as having pragma @code{Elaborate_Body}, then
23110 clearly there would be no possible elaboration order.
23111
23112 The above pragmas allow a server to guarantee safe use by clients, and
23113 clearly this is the preferable approach. Consequently a good rule in
23114 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23115 and if this is not possible,
23116 mark them as @code{Elaborate_Body} if possible.
23117 As we have seen, there are situations where neither of these
23118 three pragmas can be used.
23119 So we also provide methods for clients to control the
23120 order of elaboration of the servers on which they depend:
23121
23122 @table @asis
23123 @item pragma Elaborate (unit)
23124 @findex Elaborate
23125 @cindex pragma Elaborate
23126 This pragma is placed in the context clause, after a @code{with} clause,
23127 and it requires that the body of the named unit be elaborated before
23128 the unit in which the pragma occurs. The idea is to use this pragma
23129 if the current unit calls at elaboration time, directly or indirectly,
23130 some subprogram in the named unit.
23131
23132 @item pragma Elaborate_All (unit)
23133 @findex Elaborate_All
23134 @cindex pragma Elaborate_All
23135 This is a stronger version of the Elaborate pragma. Consider the
23136 following example:
23137
23138 @smallexample
23139 Unit A @code{with}'s unit B and calls B.Func in elab code
23140 Unit B @code{with}'s unit C, and B.Func calls C.Func
23141 @end smallexample
23142
23143 @noindent
23144 Now if we put a pragma @code{Elaborate (B)}
23145 in unit @code{A}, this ensures that the
23146 body of @code{B} is elaborated before the call, but not the
23147 body of @code{C}, so
23148 the call to @code{C.Func} could still cause @code{Program_Error} to
23149 be raised.
23150
23151 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23152 not only that the body of the named unit be elaborated before the
23153 unit doing the @code{with}, but also the bodies of all units that the
23154 named unit uses, following @code{with} links transitively. For example,
23155 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23156 then it requires
23157 not only that the body of @code{B} be elaborated before @code{A},
23158 but also the
23159 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23160 @end table
23161
23162 @noindent
23163 We are now in a position to give a usage rule in Ada 95 for avoiding
23164 elaboration problems, at least if dynamic dispatching and access to
23165 subprogram values are not used. We will handle these cases separately
23166 later.
23167
23168 The rule is simple. If a unit has elaboration code that can directly or
23169 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23170 a generic unit in a @code{with}'ed unit,
23171 then if the @code{with}'ed unit does not have
23172 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23173 a pragma @code{Elaborate_All}
23174 for the @code{with}'ed unit. By following this rule a client is
23175 assured that calls can be made without risk of an exception.
23176 If this rule is not followed, then a program may be in one of four
23177 states:
23178
23179 @table @asis
23180 @item No order exists
23181 No order of elaboration exists which follows the rules, taking into
23182 account any @code{Elaborate}, @code{Elaborate_All},
23183 or @code{Elaborate_Body} pragmas. In
23184 this case, an Ada 95 compiler must diagnose the situation at bind
23185 time, and refuse to build an executable program.
23186
23187 @item One or more orders exist, all incorrect
23188 One or more acceptable elaboration orders exists, and all of them
23189 generate an elaboration order problem. In this case, the binder
23190 can build an executable program, but @code{Program_Error} will be raised
23191 when the program is run.
23192
23193 @item Several orders exist, some right, some incorrect
23194 One or more acceptable elaboration orders exists, and some of them
23195 work, and some do not. The programmer has not controlled
23196 the order of elaboration, so the binder may or may not pick one of
23197 the correct orders, and the program may or may not raise an
23198 exception when it is run. This is the worst case, because it means
23199 that the program may fail when moved to another compiler, or even
23200 another version of the same compiler.
23201
23202 @item One or more orders exists, all correct
23203 One ore more acceptable elaboration orders exist, and all of them
23204 work. In this case the program runs successfully. This state of
23205 affairs can be guaranteed by following the rule we gave above, but
23206 may be true even if the rule is not followed.
23207 @end table
23208
23209 @noindent
23210 Note that one additional advantage of following our Elaborate_All rule
23211 is that the program continues to stay in the ideal (all orders OK) state
23212 even if maintenance
23213 changes some bodies of some subprograms. Conversely, if a program that does
23214 not follow this rule happens to be safe at some point, this state of affairs
23215 may deteriorate silently as a result of maintenance changes.
23216
23217 You may have noticed that the above discussion did not mention
23218 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23219 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23220 code in the body makes calls to some other unit, so it is still necessary
23221 to use @code{Elaborate_All} on such units.
23222
23223 @node Controlling Elaboration in GNAT - Internal Calls
23224 @section Controlling Elaboration in GNAT - Internal Calls
23225
23226 @noindent
23227 In the case of internal calls, i.e. calls within a single package, the
23228 programmer has full control over the order of elaboration, and it is up
23229 to the programmer to elaborate declarations in an appropriate order. For
23230 example writing:
23231
23232 @smallexample @c ada
23233 @group
23234 @cartouche
23235 function One return Float;
23236
23237 Q : Float := One;
23238
23239 function One return Float is
23240 begin
23241      return 1.0;
23242 end One;
23243 @end cartouche
23244 @end group
23245 @end smallexample
23246
23247 @noindent
23248 will obviously raise @code{Program_Error} at run time, because function
23249 One will be called before its body is elaborated. In this case GNAT will
23250 generate a warning that the call will raise @code{Program_Error}:
23251
23252 @smallexample
23253 @group
23254 @cartouche
23255  1. procedure y is
23256  2.    function One return Float;
23257  3.
23258  4.    Q : Float := One;
23259                     |
23260     >>> warning: cannot call "One" before body is elaborated
23261     >>> warning: Program_Error will be raised at run time
23262
23263  5.
23264  6.    function One return Float is
23265  7.    begin
23266  8.         return 1.0;
23267  9.    end One;
23268 10.
23269 11. begin
23270 12.    null;
23271 13. end;
23272 @end cartouche
23273 @end group
23274 @end smallexample
23275
23276 @noindent
23277 Note that in this particular case, it is likely that the call is safe, because
23278 the function @code{One} does not access any global variables.
23279 Nevertheless in Ada 95, we do not want the validity of the check to depend on
23280 the contents of the body (think about the separate compilation case), so this
23281 is still wrong, as we discussed in the previous sections.
23282
23283 The error is easily corrected by rearranging the declarations so that the
23284 body of One appears before the declaration containing the call
23285 (note that in Ada 95,
23286 declarations can appear in any order, so there is no restriction that
23287 would prevent this reordering, and if we write:
23288
23289 @smallexample @c ada
23290 @group
23291 @cartouche
23292 function One return Float;
23293
23294 function One return Float is
23295 begin
23296      return 1.0;
23297 end One;
23298
23299 Q : Float := One;
23300 @end cartouche
23301 @end group
23302 @end smallexample
23303
23304 @noindent
23305 then all is well, no warning is generated, and no
23306 @code{Program_Error} exception
23307 will be raised.
23308 Things are more complicated when a chain of subprograms is executed:
23309
23310 @smallexample @c ada
23311 @group
23312 @cartouche
23313 function A return Integer;
23314 function B return Integer;
23315 function C return Integer;
23316
23317 function B return Integer is begin return A; end;
23318 function C return Integer is begin return B; end;
23319
23320 X : Integer := C;
23321
23322 function A return Integer is begin return 1; end;
23323 @end cartouche
23324 @end group
23325 @end smallexample
23326
23327 @noindent
23328 Now the call to @code{C}
23329 at elaboration time in the declaration of @code{X} is correct, because
23330 the body of @code{C} is already elaborated,
23331 and the call to @code{B} within the body of
23332 @code{C} is correct, but the call
23333 to @code{A} within the body of @code{B} is incorrect, because the body
23334 of @code{A} has not been elaborated, so @code{Program_Error}
23335 will be raised on the call to @code{A}.
23336 In this case GNAT will generate a
23337 warning that @code{Program_Error} may be
23338 raised at the point of the call. Let's look at the warning:
23339
23340 @smallexample
23341 @group
23342 @cartouche
23343  1. procedure x is
23344  2.    function A return Integer;
23345  3.    function B return Integer;
23346  4.    function C return Integer;
23347  5.
23348  6.    function B return Integer is begin return A; end;
23349                                                     |
23350     >>> warning: call to "A" before body is elaborated may
23351                  raise Program_Error
23352     >>> warning: "B" called at line 7
23353     >>> warning: "C" called at line 9
23354
23355  7.    function C return Integer is begin return B; end;
23356  8.
23357  9.    X : Integer := C;
23358 10.
23359 11.    function A return Integer is begin return 1; end;
23360 12.
23361 13. begin
23362 14.    null;
23363 15. end;
23364 @end cartouche
23365 @end group
23366 @end smallexample
23367
23368 @noindent
23369 Note that the message here says ``may raise'', instead of the direct case,
23370 where the message says ``will be raised''. That's because whether
23371 @code{A} is
23372 actually called depends in general on run-time flow of control.
23373 For example, if the body of @code{B} said
23374
23375 @smallexample @c ada
23376 @group
23377 @cartouche
23378 function B return Integer is
23379 begin
23380    if some-condition-depending-on-input-data then
23381       return A;
23382    else
23383       return 1;
23384    end if;
23385 end B;
23386 @end cartouche
23387 @end group
23388 @end smallexample
23389
23390 @noindent
23391 then we could not know until run time whether the incorrect call to A would
23392 actually occur, so @code{Program_Error} might
23393 or might not be raised. It is possible for a compiler to
23394 do a better job of analyzing bodies, to
23395 determine whether or not @code{Program_Error}
23396 might be raised, but it certainly
23397 couldn't do a perfect job (that would require solving the halting problem
23398 and is provably impossible), and because this is a warning anyway, it does
23399 not seem worth the effort to do the analysis. Cases in which it
23400 would be relevant are rare.
23401
23402 In practice, warnings of either of the forms given
23403 above will usually correspond to
23404 real errors, and should be examined carefully and eliminated.
23405 In the rare case where a warning is bogus, it can be suppressed by any of
23406 the following methods:
23407
23408 @itemize @bullet
23409 @item
23410 Compile with the @option{-gnatws} switch set
23411
23412 @item
23413 Suppress @code{Elaboration_Check} for the called subprogram
23414
23415 @item
23416 Use pragma @code{Warnings_Off} to turn warnings off for the call
23417 @end itemize
23418
23419 @noindent
23420 For the internal elaboration check case,
23421 GNAT by default generates the
23422 necessary run-time checks to ensure
23423 that @code{Program_Error} is raised if any
23424 call fails an elaboration check. Of course this can only happen if a
23425 warning has been issued as described above. The use of pragma
23426 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23427 some of these checks, meaning that it may be possible (but is not
23428 guaranteed) for a program to be able to call a subprogram whose body
23429 is not yet elaborated, without raising a @code{Program_Error} exception.
23430
23431 @node Controlling Elaboration in GNAT - External Calls
23432 @section Controlling Elaboration in GNAT - External Calls
23433
23434 @noindent
23435 The previous section discussed the case in which the execution of a
23436 particular thread of elaboration code occurred entirely within a
23437 single unit. This is the easy case to handle, because a programmer
23438 has direct and total control over the order of elaboration, and
23439 furthermore, checks need only be generated in cases which are rare
23440 and which the compiler can easily detect.
23441 The situation is more complex when separate compilation is taken into account.
23442 Consider the following:
23443
23444 @smallexample @c ada
23445 @cartouche
23446 @group
23447 package Math is
23448    function Sqrt (Arg : Float) return Float;
23449 end Math;
23450
23451 package body Math is
23452    function Sqrt (Arg : Float) return Float is
23453    begin
23454          ...
23455    end Sqrt;
23456 end Math;
23457 @end group
23458 @group
23459 with Math;
23460 package Stuff is
23461    X : Float := Math.Sqrt (0.5);
23462 end Stuff;
23463
23464 with Stuff;
23465 procedure Main is
23466 begin
23467    ...
23468 end Main;
23469 @end group
23470 @end cartouche
23471 @end smallexample
23472
23473 @noindent
23474 where @code{Main} is the main program. When this program is executed, the
23475 elaboration code must first be executed, and one of the jobs of the
23476 binder is to determine the order in which the units of a program are
23477 to be elaborated. In this case we have four units: the spec and body
23478 of @code{Math},
23479 the spec of @code{Stuff} and the body of @code{Main}).
23480 In what order should the four separate sections of elaboration code
23481 be executed?
23482
23483 There are some restrictions in the order of elaboration that the binder
23484 can choose. In particular, if unit U has a @code{with}
23485 for a package @code{X}, then you
23486 are assured that the spec of @code{X}
23487 is elaborated before U , but you are
23488 not assured that the body of @code{X}
23489 is elaborated before U.
23490 This means that in the above case, the binder is allowed to choose the
23491 order:
23492
23493 @smallexample
23494 spec of Math
23495 spec of Stuff
23496 body of Math
23497 body of Main
23498 @end smallexample
23499
23500 @noindent
23501 but that's not good, because now the call to @code{Math.Sqrt}
23502 that happens during
23503 the elaboration of the @code{Stuff}
23504 spec happens before the body of @code{Math.Sqrt} is
23505 elaborated, and hence causes @code{Program_Error} exception to be raised.
23506 At first glance, one might say that the binder is misbehaving, because
23507 obviously you want to elaborate the body of something you @code{with}
23508 first, but
23509 that is not a general rule that can be followed in all cases. Consider
23510
23511 @smallexample @c ada
23512 @group
23513 @cartouche
23514 package X is ...
23515
23516 package Y is ...
23517
23518 with X;
23519 package body Y is ...
23520
23521 with Y;
23522 package body X is ...
23523 @end cartouche
23524 @end group
23525 @end smallexample
23526
23527 @noindent
23528 This is a common arrangement, and, apart from the order of elaboration
23529 problems that might arise in connection with elaboration code, this works fine.
23530 A rule that says that you must first elaborate the body of anything you
23531 @code{with} cannot work in this case:
23532 the body of @code{X} @code{with}'s @code{Y},
23533 which means you would have to
23534 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23535 which means
23536 you have to elaborate the body of @code{X} first, but ... and we have a
23537 loop that cannot be broken.
23538
23539 It is true that the binder can in many cases guess an order of elaboration
23540 that is unlikely to cause a @code{Program_Error}
23541 exception to be raised, and it tries to do so (in the
23542 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23543 by default
23544 elaborate the body of @code{Math} right after its spec, so all will be well).
23545
23546 However, a program that blindly relies on the binder to be helpful can
23547 get into trouble, as we discussed in the previous sections, so
23548 GNAT
23549 provides a number of facilities for assisting the programmer in
23550 developing programs that are robust with respect to elaboration order.
23551
23552 @node Default Behavior in GNAT - Ensuring Safety
23553 @section Default Behavior in GNAT - Ensuring Safety
23554
23555 @noindent
23556 The default behavior in GNAT ensures elaboration safety. In its
23557 default mode GNAT implements the
23558 rule we previously described as the right approach. Let's restate it:
23559
23560 @itemize
23561 @item
23562 @emph{If a unit has elaboration code that can directly or indirectly make a
23563 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
23564 in a @code{with}'ed unit, then if the @code{with}'ed unit
23565 does not have pragma @code{Pure} or
23566 @code{Preelaborate}, then the client should have an
23567 @code{Elaborate_All} for the @code{with}'ed unit.}
23568 @end itemize
23569
23570 @noindent
23571 By following this rule a client is assured that calls and instantiations
23572 can be made without risk of an exception.
23573
23574 In this mode GNAT traces all calls that are potentially made from
23575 elaboration code, and puts in any missing implicit @code{Elaborate_All}
23576 pragmas.
23577 The advantage of this approach is that no elaboration problems
23578 are possible if the binder can find an elaboration order that is
23579 consistent with these implicit @code{Elaborate_All} pragmas. The
23580 disadvantage of this approach is that no such order may exist.
23581
23582 If the binder does not generate any diagnostics, then it means that it
23583 has found an elaboration order that is guaranteed to be safe. However,
23584 the binder may still be relying on implicitly generated
23585 @code{Elaborate_All} pragmas so portability to other compilers than
23586 GNAT is not guaranteed.
23587
23588 If it is important to guarantee portability, then the compilations should
23589 use the
23590 @option{-gnatwl}
23591 (warn on elaboration problems) switch. This will cause warning messages
23592 to be generated indicating the missing @code{Elaborate_All} pragmas.
23593 Consider the following source program:
23594
23595 @smallexample @c ada
23596 @group
23597 @cartouche
23598 with k;
23599 package j is
23600   m : integer := k.r;
23601 end;
23602 @end cartouche
23603 @end group
23604 @end smallexample
23605
23606 @noindent
23607 where it is clear that there
23608 should be a pragma @code{Elaborate_All}
23609 for unit @code{k}. An implicit pragma will be generated, and it is
23610 likely that the binder will be able to honor it. However, if you want
23611 to port this program to some other Ada compiler than GNAT.
23612 it is safer to include the pragma explicitly in the source. If this
23613 unit is compiled with the
23614 @option{-gnatwl}
23615 switch, then the compiler outputs a warning:
23616
23617 @smallexample
23618 @group
23619 @cartouche
23620 1. with k;
23621 2. package j is
23622 3.   m : integer := k.r;
23623                      |
23624    >>> warning: call to "r" may raise Program_Error
23625    >>> warning: missing pragma Elaborate_All for "k"
23626
23627 4. end;
23628 @end cartouche
23629 @end group
23630 @end smallexample
23631
23632 @noindent
23633 and these warnings can be used as a guide for supplying manually
23634 the missing pragmas. It is usually a bad idea to use this warning
23635 option during development. That's because it will warn you when
23636 you need to put in a pragma, but cannot warn you when it is time
23637 to take it out. So the use of pragma Elaborate_All may lead to
23638 unnecessary dependencies and even false circularities.
23639
23640 This default mode is more restrictive than the Ada Reference
23641 Manual, and it is possible to construct programs which will compile
23642 using the dynamic model described there, but will run into a
23643 circularity using the safer static model we have described.
23644
23645 Of course any Ada compiler must be able to operate in a mode
23646 consistent with the requirements of the Ada Reference Manual,
23647 and in particular must have the capability of implementing the
23648 standard dynamic model of elaboration with run-time checks.
23649
23650 In GNAT, this standard mode can be achieved either by the use of
23651 the @option{-gnatE} switch on the compiler (@command{gcc} or
23652 @command{gnatmake}) command, or by the use of the configuration pragma:
23653
23654 @smallexample @c ada
23655 pragma Elaboration_Checks (RM);
23656 @end smallexample
23657
23658 @noindent
23659 Either approach will cause the unit affected to be compiled using the
23660 standard dynamic run-time elaboration checks described in the Ada
23661 Reference Manual. The static model is generally preferable, since it
23662 is clearly safer to rely on compile and link time checks rather than
23663 run-time checks. However, in the case of legacy code, it may be
23664 difficult to meet the requirements of the static model. This
23665 issue is further discussed in
23666 @ref{What to Do If the Default Elaboration Behavior Fails}.
23667
23668 Note that the static model provides a strict subset of the allowed
23669 behavior and programs of the Ada Reference Manual, so if you do
23670 adhere to the static model and no circularities exist,
23671 then you are assured that your program will
23672 work using the dynamic model, providing that you remove any
23673 pragma Elaborate statements from the source.
23674
23675 @node Treatment of Pragma Elaborate
23676 @section Treatment of Pragma Elaborate
23677 @cindex Pragma Elaborate
23678
23679 @noindent
23680 The use of @code{pragma Elaborate}
23681 should generally be avoided in Ada 95 programs.
23682 The reason for this is that there is no guarantee that transitive calls
23683 will be properly handled. Indeed at one point, this pragma was placed
23684 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23685
23686 Now that's a bit restrictive. In practice, the case in which
23687 @code{pragma Elaborate} is useful is when the caller knows that there
23688 are no transitive calls, or that the called unit contains all necessary
23689 transitive @code{pragma Elaborate} statements, and legacy code often
23690 contains such uses.
23691
23692 Strictly speaking the static mode in GNAT should ignore such pragmas,
23693 since there is no assurance at compile time that the necessary safety
23694 conditions are met. In practice, this would cause GNAT to be incompatible
23695 with correctly written Ada 83 code that had all necessary
23696 @code{pragma Elaborate} statements in place. Consequently, we made the
23697 decision that GNAT in its default mode will believe that if it encounters
23698 a @code{pragma Elaborate} then the programmer knows what they are doing,
23699 and it will trust that no elaboration errors can occur.
23700
23701 The result of this decision is two-fold. First to be safe using the
23702 static mode, you should remove all @code{pragma Elaborate} statements.
23703 Second, when fixing circularities in existing code, you can selectively
23704 use @code{pragma Elaborate} statements to convince the static mode of
23705 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23706 statement.
23707
23708 When using the static mode with @option{-gnatwl}, any use of
23709 @code{pragma Elaborate} will generate a warning about possible
23710 problems.
23711
23712 @node Elaboration Issues for Library Tasks
23713 @section Elaboration Issues for Library Tasks
23714 @cindex Library tasks, elaboration issues
23715 @cindex Elaboration of library tasks
23716
23717 @noindent
23718 In this section we examine special elaboration issues that arise for
23719 programs that declare library level tasks.
23720
23721 Generally the model of execution of an Ada program is that all units are
23722 elaborated, and then execution of the program starts. However, the
23723 declaration of library tasks definitely does not fit this model. The
23724 reason for this is that library tasks start as soon as they are declared
23725 (more precisely, as soon as the statement part of the enclosing package
23726 body is reached), that is to say before elaboration
23727 of the program is complete. This means that if such a task calls a
23728 subprogram, or an entry in another task, the callee may or may not be
23729 elaborated yet, and in the standard
23730 Reference Manual model of dynamic elaboration checks, you can even
23731 get timing dependent Program_Error exceptions, since there can be
23732 a race between the elaboration code and the task code.
23733
23734 The static model of elaboration in GNAT seeks to avoid all such
23735 dynamic behavior, by being conservative, and the conservative
23736 approach in this particular case is to assume that all the code
23737 in a task body is potentially executed at elaboration time if
23738 a task is declared at the library level.
23739
23740 This can definitely result in unexpected circularities. Consider
23741 the following example
23742
23743 @smallexample @c ada
23744 package Decls is
23745   task Lib_Task is
23746      entry Start;
23747   end Lib_Task;
23748
23749   type My_Int is new Integer;
23750
23751   function Ident (M : My_Int) return My_Int;
23752 end Decls;
23753
23754 with Utils;
23755 package body Decls is
23756   task body Lib_Task is
23757   begin
23758      accept Start;
23759      Utils.Put_Val (2);
23760   end Lib_Task;
23761
23762   function Ident (M : My_Int) return My_Int is
23763   begin
23764      return M;
23765   end Ident;
23766 end Decls;
23767
23768 with Decls;
23769 package Utils is
23770   procedure Put_Val (Arg : Decls.My_Int);
23771 end Utils;
23772
23773 with Text_IO;
23774 package body Utils is
23775   procedure Put_Val (Arg : Decls.My_Int) is
23776   begin
23777      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23778   end Put_Val;
23779 end Utils;
23780
23781 with Decls;
23782 procedure Main is
23783 begin
23784    Decls.Lib_Task.Start;
23785 end;
23786 @end smallexample
23787
23788 @noindent
23789 If the above example is compiled in the default static elaboration
23790 mode, then a circularity occurs. The circularity comes from the call
23791 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23792 this call occurs in elaboration code, we need an implicit pragma
23793 @code{Elaborate_All} for @code{Utils}. This means that not only must
23794 the spec and body of @code{Utils} be elaborated before the body
23795 of @code{Decls}, but also the spec and body of any unit that is
23796 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23797 the body of @code{Decls}. This is the transitive implication of
23798 pragma @code{Elaborate_All} and it makes sense, because in general
23799 the body of @code{Put_Val} might have a call to something in a
23800 @code{with'ed} unit.
23801
23802 In this case, the body of Utils (actually its spec) @code{with's}
23803 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23804 must be elaborated before itself, in case there is a call from the
23805 body of @code{Utils}.
23806
23807 Here is the exact chain of events we are worrying about:
23808
23809 @enumerate
23810 @item
23811 In the body of @code{Decls} a call is made from within the body of a library
23812 task to a subprogram in the package @code{Utils}. Since this call may
23813 occur at elaboration time (given that the task is activated at elaboration
23814 time), we have to assume the worst, i.e. that the
23815 call does happen at elaboration time.
23816
23817 @item
23818 This means that the body and spec of @code{Util} must be elaborated before
23819 the body of @code{Decls} so that this call does not cause an access before
23820 elaboration.
23821
23822 @item
23823 Within the body of @code{Util}, specifically within the body of
23824 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23825 by this package.
23826
23827 @item
23828 One such @code{with}'ed package is package @code{Decls}, so there
23829 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23830 In fact there is such a call in this example, but we would have to
23831 assume that there was such a call even if it were not there, since
23832 we are not supposed to write the body of @code{Decls} knowing what
23833 is in the body of @code{Utils}; certainly in the case of the
23834 static elaboration model, the compiler does not know what is in
23835 other bodies and must assume the worst.
23836
23837 @item
23838 This means that the spec and body of @code{Decls} must also be
23839 elaborated before we elaborate the unit containing the call, but
23840 that unit is @code{Decls}! This means that the body of @code{Decls}
23841 must be elaborated before itself, and that's a circularity.
23842 @end enumerate
23843
23844 @noindent
23845 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
23846 the body of @code{Decls} you will get a true Ada Reference Manual
23847 circularity that makes the program illegal.
23848
23849 In practice, we have found that problems with the static model of
23850 elaboration in existing code often arise from library tasks, so
23851 we must address this particular situation.
23852
23853 Note that if we compile and run the program above, using the dynamic model of
23854 elaboration (that is to say use the @option{-gnatE} switch),
23855 then it compiles, binds,
23856 links, and runs, printing the expected result of 2. Therefore in some sense
23857 the circularity here is only apparent, and we need to capture
23858 the properties of this program that  distinguish it from other library-level
23859 tasks that have real elaboration problems.
23860
23861 We have four possible answers to this question:
23862
23863 @itemize @bullet
23864
23865 @item
23866 Use the dynamic model of elaboration.
23867
23868 If we use the @option{-gnatE} switch, then as noted above, the program works.
23869 Why is this? If we examine the task body, it is apparent that the task cannot
23870 proceed past the
23871 @code{accept} statement until after elaboration has been completed, because
23872 the corresponding entry call comes from the main program, not earlier.
23873 This is why the dynamic model works here. But that's really giving
23874 up on a precise analysis, and we prefer to take this approach only if we cannot
23875 solve the
23876 problem in any other manner. So let us examine two ways to reorganize
23877 the program to avoid the potential elaboration problem.
23878
23879 @item
23880 Split library tasks into separate packages.
23881
23882 Write separate packages, so that library tasks are isolated from
23883 other declarations as much as possible. Let us look at a variation on
23884 the above program.
23885
23886 @smallexample @c ada
23887 package Decls1 is
23888   task Lib_Task is
23889      entry Start;
23890   end Lib_Task;
23891 end Decls1;
23892
23893 with Utils;
23894 package body Decls1 is
23895   task body Lib_Task is
23896   begin
23897      accept Start;
23898      Utils.Put_Val (2);
23899   end Lib_Task;
23900 end Decls1;
23901
23902 package Decls2 is
23903   type My_Int is new Integer;
23904   function Ident (M : My_Int) return My_Int;
23905 end Decls2;
23906
23907 with Utils;
23908 package body Decls2 is
23909   function Ident (M : My_Int) return My_Int is
23910   begin
23911      return M;
23912   end Ident;
23913 end Decls2;
23914
23915 with Decls2;
23916 package Utils is
23917   procedure Put_Val (Arg : Decls2.My_Int);
23918 end Utils;
23919
23920 with Text_IO;
23921 package body Utils is
23922   procedure Put_Val (Arg : Decls2.My_Int) is
23923   begin
23924      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23925   end Put_Val;
23926 end Utils;
23927
23928 with Decls1;
23929 procedure Main is
23930 begin
23931    Decls1.Lib_Task.Start;
23932 end;
23933 @end smallexample
23934
23935 @noindent
23936 All we have done is to split @code{Decls} into two packages, one
23937 containing the library task, and one containing everything else. Now
23938 there is no cycle, and the program compiles, binds, links and executes
23939 using the default static model of elaboration.
23940
23941 @item
23942 Declare separate task types.
23943
23944 A significant part of the problem arises because of the use of the
23945 single task declaration form. This means that the elaboration of
23946 the task type, and the elaboration of the task itself (i.e. the
23947 creation of the task) happen at the same time. A good rule
23948 of style in Ada 95 is to always create explicit task types. By
23949 following the additional step of placing task objects in separate
23950 packages from the task type declaration, many elaboration problems
23951 are avoided. Here is another modified example of the example program:
23952
23953 @smallexample @c ada
23954 package Decls is
23955   task type Lib_Task_Type is
23956      entry Start;
23957   end Lib_Task_Type;
23958
23959   type My_Int is new Integer;
23960
23961   function Ident (M : My_Int) return My_Int;
23962 end Decls;
23963
23964 with Utils;
23965 package body Decls is
23966   task body Lib_Task_Type is
23967   begin
23968      accept Start;
23969      Utils.Put_Val (2);
23970   end Lib_Task_Type;
23971
23972   function Ident (M : My_Int) return My_Int is
23973   begin
23974      return M;
23975   end Ident;
23976 end Decls;
23977
23978 with Decls;
23979 package Utils is
23980   procedure Put_Val (Arg : Decls.My_Int);
23981 end Utils;
23982
23983 with Text_IO;
23984 package body Utils is
23985   procedure Put_Val (Arg : Decls.My_Int) is
23986   begin
23987      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23988   end Put_Val;
23989 end Utils;
23990
23991 with Decls;
23992 package Declst is
23993    Lib_Task : Decls.Lib_Task_Type;
23994 end Declst;
23995
23996 with Declst;
23997 procedure Main is
23998 begin
23999    Declst.Lib_Task.Start;
24000 end;
24001 @end smallexample
24002
24003 @noindent
24004 What we have done here is to replace the @code{task} declaration in
24005 package @code{Decls} with a @code{task type} declaration. Then we
24006 introduce a separate package @code{Declst} to contain the actual
24007 task object. This separates the elaboration issues for
24008 the @code{task type}
24009 declaration, which causes no trouble, from the elaboration issues
24010 of the task object, which is also unproblematic, since it is now independent
24011 of the elaboration of  @code{Utils}.
24012 This separation of concerns also corresponds to
24013 a generally sound engineering principle of separating declarations
24014 from instances. This version of the program also compiles, binds, links,
24015 and executes, generating the expected output.
24016
24017 @item
24018 Use No_Entry_Calls_In_Elaboration_Code restriction.
24019 @cindex No_Entry_Calls_In_Elaboration_Code
24020
24021 The previous two approaches described how a program can be restructured
24022 to avoid the special problems caused by library task bodies. in practice,
24023 however, such restructuring may be difficult to apply to existing legacy code,
24024 so we must consider solutions that do not require massive rewriting.
24025
24026 Let us consider more carefully why our original sample program works
24027 under the dynamic model of elaboration. The reason is that the code
24028 in the task body blocks immediately on the @code{accept}
24029 statement. Now of course there is nothing to prohibit elaboration
24030 code from making entry calls (for example from another library level task),
24031 so we cannot tell in isolation that
24032 the task will not execute the accept statement  during elaboration.
24033
24034 However, in practice it is very unusual to see elaboration code
24035 make any entry calls, and the pattern of tasks starting
24036 at elaboration time and then immediately blocking on @code{accept} or
24037 @code{select} statements is very common. What this means is that
24038 the compiler is being too pessimistic when it analyzes the
24039 whole package body as though it might be executed at elaboration
24040 time.
24041
24042 If we know that the elaboration code contains no entry calls, (a very safe
24043 assumption most of the time, that could almost be made the default
24044 behavior), then we can compile all units of the program under control
24045 of the following configuration pragma:
24046
24047 @smallexample
24048 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24049 @end smallexample
24050
24051 @noindent
24052 This pragma can be placed in the @file{gnat.adc} file in the usual
24053 manner. If we take our original unmodified program and compile it
24054 in the presence of a @file{gnat.adc} containing the above pragma,
24055 then once again, we can compile, bind, link, and execute, obtaining
24056 the expected result. In the presence of this pragma, the compiler does
24057 not trace calls in a task body, that appear after the first @code{accept}
24058 or @code{select} statement, and therefore does not report a potential
24059 circularity in the original program.
24060
24061 The compiler will check to the extent it can that the above
24062 restriction is not violated, but it is not always possible to do a
24063 complete check at compile time, so it is important to use this
24064 pragma only if the stated restriction is in fact met, that is to say
24065 no task receives an entry call before elaboration of all units is completed.
24066
24067 @end itemize
24068
24069 @node Mixing Elaboration Models
24070 @section Mixing Elaboration Models
24071 @noindent
24072 So far, we have assumed that the entire program is either compiled
24073 using the dynamic model or static model, ensuring consistency. It
24074 is possible to mix the two models, but rules have to be followed
24075 if this mixing is done to ensure that elaboration checks are not
24076 omitted.
24077
24078 The basic rule is that @emph{a unit compiled with the static model cannot
24079 be @code{with'ed} by a unit compiled with the dynamic model}. The
24080 reason for this is that in the static model, a unit assumes that
24081 its clients guarantee to use (the equivalent of) pragma
24082 @code{Elaborate_All} so that no elaboration checks are required
24083 in inner subprograms, and this assumption is violated if the
24084 client is compiled with dynamic checks.
24085
24086 The precise rule is as follows. A unit that is compiled with dynamic
24087 checks can only @code{with} a unit that meets at least one of the
24088 following criteria:
24089
24090 @itemize @bullet
24091
24092 @item
24093 The @code{with'ed} unit is itself compiled with dynamic elaboration
24094 checks (that is with the @option{-gnatE} switch.
24095
24096 @item
24097 The @code{with'ed} unit is an internal GNAT implementation unit from
24098 the System, Interfaces, Ada, or GNAT hierarchies.
24099
24100 @item
24101 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24102
24103 @item
24104 The @code{with'ing} unit (that is the client) has an explicit pragma
24105 @code{Elaborate_All} for the @code{with'ed} unit.
24106
24107 @end itemize
24108
24109 @noindent
24110 If this rule is violated, that is if a unit with dynamic elaboration
24111 checks @code{with's} a unit that does not meet one of the above four
24112 criteria, then the binder (@code{gnatbind}) will issue a warning
24113 similar to that in the following example:
24114
24115 @smallexample
24116 warning: "x.ads" has dynamic elaboration checks and with's
24117 warning:   "y.ads" which has static elaboration checks
24118 @end smallexample
24119
24120 @noindent
24121 These warnings indicate that the rule has been violated, and that as a result
24122 elaboration checks may be missed in the resulting executable file.
24123 This warning may be suppressed using the @option{-ws} binder switch
24124 in the usual manner.
24125
24126 One useful application of this mixing rule is in the case of a subsystem
24127 which does not itself @code{with} units from the remainder of the
24128 application. In this case, the entire subsystem can be compiled with
24129 dynamic checks to resolve a circularity in the subsystem, while
24130 allowing the main application that uses this subsystem to be compiled
24131 using the more reliable default static model.
24132
24133 @node What to Do If the Default Elaboration Behavior Fails
24134 @section What to Do If the Default Elaboration Behavior Fails
24135
24136 @noindent
24137 If the binder cannot find an acceptable order, it outputs detailed
24138 diagnostics. For example:
24139 @smallexample
24140 @group
24141 @iftex
24142 @leftskip=0cm
24143 @end iftex
24144 error: elaboration circularity detected
24145 info:   "proc (body)" must be elaborated before "pack (body)"
24146 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24147 info:     recompile "pack (body)" with -gnatwl
24148 info:                             for full details
24149 info:       "proc (body)"
24150 info:         is needed by its spec:
24151 info:       "proc (spec)"
24152 info:         which is withed by:
24153 info:       "pack (body)"
24154 info:  "pack (body)" must be elaborated before "proc (body)"
24155 info:     reason: pragma Elaborate in unit "proc (body)"
24156 @end group
24157
24158 @end smallexample
24159
24160 @noindent
24161 In this case we have a cycle that the binder cannot break. On the one
24162 hand, there is an explicit pragma Elaborate in @code{proc} for
24163 @code{pack}. This means that the body of @code{pack} must be elaborated
24164 before the body of @code{proc}. On the other hand, there is elaboration
24165 code in @code{pack} that calls a subprogram in @code{proc}. This means
24166 that for maximum safety, there should really be a pragma
24167 Elaborate_All in @code{pack} for @code{proc} which would require that
24168 the body of @code{proc} be elaborated before the body of
24169 @code{pack}. Clearly both requirements cannot be satisfied.
24170 Faced with a circularity of this kind, you have three different options.
24171
24172 @table @asis
24173 @item Fix the program
24174 The most desirable option from the point of view of long-term maintenance
24175 is to rearrange the program so that the elaboration problems are avoided.
24176 One useful technique is to place the elaboration code into separate
24177 child packages. Another is to move some of the initialization code to
24178 explicitly called subprograms, where the program controls the order
24179 of initialization explicitly. Although this is the most desirable option,
24180 it may be impractical and involve too much modification, especially in
24181 the case of complex legacy code.
24182
24183 @item Perform dynamic checks
24184 If the compilations are done using the
24185 @option{-gnatE}
24186 (dynamic elaboration check) switch, then GNAT behaves in
24187 a quite different manner. Dynamic checks are generated for all calls
24188 that could possibly result in raising an exception. With this switch,
24189 the compiler does not generate implicit @code{Elaborate_All} pragmas.
24190 The behavior then is exactly as specified in the Ada 95 Reference Manual.
24191 The binder will generate an executable program that may or may not
24192 raise @code{Program_Error}, and then it is the programmer's job to ensure
24193 that it does not raise an exception. Note that it is important to
24194 compile all units with the switch, it cannot be used selectively.
24195
24196 @item Suppress checks
24197 The drawback of dynamic checks is that they generate a
24198 significant overhead at run time, both in space and time. If you
24199 are absolutely sure that your program cannot raise any elaboration
24200 exceptions, and you still want to use the dynamic elaboration model,
24201 then you can use the configuration pragma
24202 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24203 example this pragma could be placed in the @file{gnat.adc} file.
24204
24205 @item Suppress checks selectively
24206 When you know that certain calls in elaboration code cannot possibly
24207 lead to an elaboration error, and the binder nevertheless generates warnings
24208 on those calls and inserts Elaborate_All pragmas that lead to elaboration
24209 circularities, it is possible to remove those warnings locally and obtain
24210 a program that will bind. Clearly this can be unsafe, and it is the
24211 responsibility of the programmer to make sure that the resulting program has
24212 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
24213 be used with different granularity to suppress warnings and break
24214 elaboration circularities:
24215
24216 @itemize @bullet
24217 @item
24218 Place the pragma that names the called subprogram in the declarative part
24219 that contains the call.
24220
24221 @item
24222 Place the pragma in the declarative part, without naming an entity. This
24223 disables warnings on all calls in the corresponding  declarative region.
24224
24225 @item
24226 Place the pragma in the package spec that declares the called subprogram,
24227 and name the subprogram. This disables warnings on all elaboration calls to
24228 that subprogram.
24229
24230 @item
24231 Place the pragma in the package spec that declares the called subprogram,
24232 without naming any entity. This disables warnings on all elaboration calls to
24233 all subprograms declared in this spec.
24234
24235 @item Use Pragma Elaborate
24236 As previously described in section @xref{Treatment of Pragma Elaborate},
24237 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24238 that no elaboration checks are required on calls to the designated unit.
24239 There may be cases in which the caller knows that no transitive calls
24240 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24241 case where @code{pragma Elaborate_All} would cause a circularity.
24242 @end itemize
24243
24244 @noindent
24245 These five cases are listed in order of decreasing safety, and therefore
24246 require increasing programmer care in their application. Consider the
24247 following program:
24248
24249 @smallexample @c adanocomment
24250 package Pack1 is
24251   function F1 return Integer;
24252   X1 : Integer;
24253 end Pack1;
24254
24255 package Pack2 is
24256   function F2 return Integer;
24257   function Pure (x : integer) return integer;
24258   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24259   --  pragma Suppress (Elaboration_Check);              -- (4)
24260 end Pack2;
24261
24262 with Pack2;
24263 package body Pack1 is
24264   function F1 return Integer is
24265   begin
24266     return 100;
24267   end F1;
24268   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24269 begin
24270   declare
24271     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24272     --  pragma Suppress(Elaboration_Check);             -- (2)
24273   begin
24274     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24275   end;
24276 end Pack1;
24277
24278 with Pack1;
24279 package body Pack2 is
24280   function F2 return Integer is
24281   begin
24282      return Pack1.F1;
24283   end F2;
24284   function Pure (x : integer) return integer is
24285   begin
24286      return x ** 3 - 3 * x;
24287   end;
24288 end Pack2;
24289
24290 with Pack1, Ada.Text_IO;
24291 procedure Proc3 is
24292 begin
24293   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24294 end Proc3;
24295 @end smallexample
24296 In the absence of any pragmas, an attempt to bind this program produces
24297 the following diagnostics:
24298 @smallexample
24299 @group
24300 @iftex
24301 @leftskip=.5cm
24302 @end iftex
24303 error: elaboration circularity detected
24304 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24305 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24306 info:       recompile "pack1 (body)" with -gnatwl for full details
24307 info:          "pack1 (body)"
24308 info:             must be elaborated along with its spec:
24309 info:          "pack1 (spec)"
24310 info:             which is withed by:
24311 info:          "pack2 (body)"
24312 info:             which must be elaborated along with its spec:
24313 info:          "pack2 (spec)"
24314 info:             which is withed by:
24315 info:          "pack1 (body)"
24316 @end group
24317 @end smallexample
24318 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24319 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24320 F2 is safe, even though F2 calls F1, because the call appears after the
24321 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24322 remove the warning on the call. It is also possible to use pragma (2)
24323 because there are no other potentially unsafe calls in the block.
24324
24325 @noindent
24326 The call to @code{Pure} is safe because this function does not depend on the
24327 state of @code{Pack2}. Therefore any call to this function is safe, and it
24328 is correct to place pragma (3) in the corresponding package spec.
24329
24330 @noindent
24331 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24332 warnings on all calls to functions declared therein. Note that this is not
24333 necessarily safe, and requires more detailed examination of the subprogram
24334 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24335 be already elaborated.
24336 @end table
24337
24338 @noindent
24339 It is hard to generalize on which of these four approaches should be
24340 taken. Obviously if it is possible to fix the program so that the default
24341 treatment works, this is preferable, but this may not always be practical.
24342 It is certainly simple enough to use
24343 @option{-gnatE}
24344 but the danger in this case is that, even if the GNAT binder
24345 finds a correct elaboration order, it may not always do so,
24346 and certainly a binder from another Ada compiler might not. A
24347 combination of testing and analysis (for which the warnings generated
24348 with the
24349 @option{-gnatwl}
24350 switch can be useful) must be used to ensure that the program is free
24351 of errors. One switch that is useful in this testing is the
24352 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24353 switch for
24354 @code{gnatbind}.
24355 Normally the binder tries to find an order that has the best chance of
24356 of avoiding elaboration problems. With this switch, the binder
24357 plays a devil's advocate role, and tries to choose the order that
24358 has the best chance of failing. If your program works even with this
24359 switch, then it has a better chance of being error free, but this is still
24360 not a guarantee.
24361
24362 For an example of this approach in action, consider the C-tests (executable
24363 tests) from the ACVC suite. If these are compiled and run with the default
24364 treatment, then all but one of them succeed without generating any error
24365 diagnostics from the binder. However, there is one test that fails, and
24366 this is not surprising, because the whole point of this test is to ensure
24367 that the compiler can handle cases where it is impossible to determine
24368 a correct order statically, and it checks that an exception is indeed
24369 raised at run time.
24370
24371 This one test must be compiled and run using the
24372 @option{-gnatE}
24373 switch, and then it passes. Alternatively, the entire suite can
24374 be run using this switch. It is never wrong to run with the dynamic
24375 elaboration switch if your code is correct, and we assume that the
24376 C-tests are indeed correct (it is less efficient, but efficiency is
24377 not a factor in running the ACVC tests.)
24378
24379 @node Elaboration for Access-to-Subprogram Values
24380 @section Elaboration for Access-to-Subprogram Values
24381 @cindex Access-to-subprogram
24382
24383 @noindent
24384 The introduction of access-to-subprogram types in Ada 95 complicates
24385 the handling of elaboration. The trouble is that it becomes
24386 impossible to tell at compile time which procedure
24387 is being called. This means that it is not possible for the binder
24388 to analyze the elaboration requirements in this case.
24389
24390 If at the point at which the access value is created
24391 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24392 the body of the subprogram is
24393 known to have been elaborated, then the access value is safe, and its use
24394 does not require a check. This may be achieved by appropriate arrangement
24395 of the order of declarations if the subprogram is in the current unit,
24396 or, if the subprogram is in another unit, by using pragma
24397 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24398 on the referenced unit.
24399
24400 If the referenced body is not known to have been elaborated at the point
24401 the access value is created, then any use of the access value must do a
24402 dynamic check, and this dynamic check will fail and raise a
24403 @code{Program_Error} exception if the body has not been elaborated yet.
24404 GNAT will generate the necessary checks, and in addition, if the
24405 @option{-gnatwl}
24406 switch is set, will generate warnings that such checks are required.
24407
24408 The use of dynamic dispatching for tagged types similarly generates
24409 a requirement for dynamic checks, and premature calls to any primitive
24410 operation of a tagged type before the body of the operation has been
24411 elaborated, will result in the raising of @code{Program_Error}.
24412
24413 @node Summary of Procedures for Elaboration Control
24414 @section Summary of Procedures for Elaboration Control
24415 @cindex Elaboration control
24416
24417 @noindent
24418 First, compile your program with the default options, using none of
24419 the special elaboration control switches. If the binder successfully
24420 binds your program, then you can be confident that, apart from issues
24421 raised by the use of access-to-subprogram types and dynamic dispatching,
24422 the program is free of elaboration errors. If it is important that the
24423 program be portable, then use the
24424 @option{-gnatwl}
24425 switch to generate warnings about missing @code{Elaborate_All}
24426 pragmas, and supply the missing pragmas.
24427
24428 If the program fails to bind using the default static elaboration
24429 handling, then you can fix the program to eliminate the binder
24430 message, or recompile the entire program with the
24431 @option{-gnatE} switch to generate dynamic elaboration checks,
24432 and, if you are sure there really are no elaboration problems,
24433 use a global pragma @code{Suppress (Elaboration_Check)}.
24434
24435 @node Other Elaboration Order Considerations
24436 @section Other Elaboration Order Considerations
24437 @noindent
24438 This section has been entirely concerned with the issue of finding a valid
24439 elaboration order, as defined by the Ada Reference Manual. In a case
24440 where several elaboration orders are valid, the task is to find one
24441 of the possible valid elaboration orders (and the static model in GNAT
24442 will ensure that this is achieved).
24443
24444 The purpose of the elaboration rules in the Ada Reference Manual is to
24445 make sure that no entity is accessed before it has been elaborated. For
24446 a subprogram, this means that the spec and body must have been elaborated
24447 before the subprogram is called. For an object, this means that the object
24448 must have been elaborated before its value is read or written. A violation
24449 of either of these two requirements is an access before elaboration order,
24450 and this section has been all about avoiding such errors.
24451
24452 In the case where more than one order of elaboration is possible, in the
24453 sense that access before elaboration errors are avoided, then any one of
24454 the orders is ``correct'' in the sense that it meets the requirements of
24455 the Ada Reference Manual, and no such error occurs.
24456
24457 However, it may be the case for a given program, that there are
24458 constraints on the order of elaboration that come not from consideration
24459 of avoiding elaboration errors, but rather from extra-lingual logic
24460 requirements. Consider this example:
24461
24462 @smallexample @c ada
24463 with Init_Constants;
24464 package Constants is
24465    X : Integer := 0;
24466    Y : Integer := 0;
24467 end Constants;
24468
24469 package Init_Constants is
24470    procedure P; -- require a body
24471 end Init_Constants;
24472
24473 with Constants;
24474 package body Init_Constants is
24475    procedure P is begin null; end;
24476 begin
24477    Constants.X := 3;
24478    Constants.Y := 4;
24479 end Init_Constants;
24480
24481 with Constants;
24482 package Calc is
24483    Z : Integer := Constants.X + Constants.Y;
24484 end Calc;
24485
24486 with Calc;
24487 with Text_IO; use Text_IO;
24488 procedure Main is
24489 begin
24490    Put_Line (Calc.Z'Img);
24491 end Main;
24492 @end smallexample
24493
24494 @noindent
24495 In this example, there is more than one valid order of elaboration. For
24496 example both the following are correct orders:
24497
24498 @smallexample
24499 Init_Constants spec
24500 Constants spec
24501 Calc spec
24502 Init_Constants body
24503 Main body
24504
24505   and
24506
24507 Init_Constants spec
24508 Init_Constants body
24509 Constants spec
24510 Calc spec
24511 Main body
24512 @end smallexample
24513
24514 @noindent
24515 There is no language rule to prefer one or the other, both are correct
24516 from an order of elaboration point of view. But the programmatic effects
24517 of the two orders are very different. In the first, the elaboration routine
24518 of @code{Calc} initializes @code{Z} to zero, and then the main program
24519 runs with this value of zero. But in the second order, the elaboration
24520 routine of @code{Calc} runs after the body of Init_Constants has set
24521 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24522 runs.
24523
24524 One could perhaps by applying pretty clever non-artificial intelligence
24525 to the situation guess that it is more likely that the second order of
24526 elaboration is the one desired, but there is no formal linguistic reason
24527 to prefer one over the other. In fact in this particular case, GNAT will
24528 prefer the second order, because of the rule that bodies are elaborated
24529 as soon as possible, but it's just luck that this is what was wanted
24530 (if indeed the second order was preferred).
24531
24532 If the program cares about the order of elaboration routines in a case like
24533 this, it is important to specify the order required. In this particular
24534 case, that could have been achieved by adding to the spec of Calc:
24535
24536 @smallexample @c ada
24537 pragma Elaborate_All (Constants);
24538 @end smallexample
24539
24540 @noindent
24541 which requires that the body (if any) and spec of @code{Constants},
24542 as well as the body and spec of any unit @code{with}'ed by
24543 @code{Constants} be elaborated before @code{Calc} is elaborated.
24544
24545 Clearly no automatic method can always guess which alternative you require,
24546 and if you are working with legacy code that had constraints of this kind
24547 which were not properly specified by adding @code{Elaborate} or
24548 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24549 compilers can choose different orders.
24550
24551 The @code{gnatbind}
24552 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24553 out problems. This switch causes bodies to be elaborated as late as possible
24554 instead of as early as possible. In the example above, it would have forced
24555 the choice of the first elaboration order. If you get different results
24556 when using this switch, and particularly if one set of results is right,
24557 and one is wrong as far as you are concerned, it shows that you have some
24558 missing @code{Elaborate} pragmas. For the example above, we have the
24559 following output:
24560
24561 @smallexample
24562 gnatmake -f -q main
24563 main
24564  7
24565 gnatmake -f -q main -bargs -p
24566 main
24567  0
24568 @end smallexample
24569
24570 @noindent
24571 It is of course quite unlikely that both these results are correct, so
24572 it is up to you in a case like this to investigate the source of the
24573 difference, by looking at the two elaboration orders that are chosen,
24574 and figuring out which is correct, and then adding the necessary
24575 @code{Elaborate_All} pragmas to ensure the desired order.
24576
24577 @node Inline Assembler
24578 @appendix Inline Assembler
24579
24580 @noindent
24581 If you need to write low-level software that interacts directly
24582 with the hardware, Ada provides two ways to incorporate assembly
24583 language code into your program.  First, you can import and invoke
24584 external routines written in assembly language, an Ada feature fully
24585 supported by GNAT.  However, for small sections of code it may be simpler
24586 or more efficient to include assembly language statements directly
24587 in your Ada source program, using the facilities of the implementation-defined
24588 package @code{System.Machine_Code}, which incorporates the gcc
24589 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
24590 including the following:
24591
24592 @itemize @bullet
24593 @item No need to use non-Ada tools
24594 @item Consistent interface over different targets
24595 @item Automatic usage of the proper calling conventions
24596 @item Access to Ada constants and variables
24597 @item Definition of intrinsic routines
24598 @item Possibility of inlining a subprogram comprising assembler code
24599 @item Code optimizer can take Inline Assembler code into account
24600 @end itemize
24601
24602 This chapter presents a series of examples to show you how to use
24603 the Inline Assembler.  Although it focuses on the Intel x86,
24604 the general approach applies also to other processors.
24605 It is assumed that you are familiar with Ada
24606 and with assembly language programming.
24607
24608 @menu
24609 * Basic Assembler Syntax::
24610 * A Simple Example of Inline Assembler::
24611 * Output Variables in Inline Assembler::
24612 * Input Variables in Inline Assembler::
24613 * Inlining Inline Assembler Code::
24614 * Other Asm Functionality::
24615 @end menu
24616
24617 @c ---------------------------------------------------------------------------
24618 @node Basic Assembler Syntax
24619 @section Basic Assembler Syntax
24620
24621 @noindent
24622 The assembler used by GNAT and gcc is based not on the Intel assembly
24623 language, but rather on a language that descends from the AT&T Unix
24624 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
24625 The following table summarizes the main features of @emph{as} syntax
24626 and points out the differences from the Intel conventions.
24627 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
24628 pre-processor) documentation for further information.
24629
24630 @table @asis
24631 @item Register names
24632 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
24633 @*
24634 Intel: No extra punctuation; for example @code{eax}
24635
24636 @item Immediate operand
24637 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
24638 @*
24639 Intel: No extra punctuation; for example @code{4}
24640
24641 @item Address
24642 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
24643 @*
24644 Intel: No extra punctuation; for example @code{loc}
24645
24646 @item Memory contents
24647 gcc / @emph{as}: No extra punctuation; for example @code{loc}
24648 @*
24649 Intel: Square brackets; for example @code{[loc]}
24650
24651 @item Register contents
24652 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
24653 @*
24654 Intel: Square brackets; for example @code{[eax]}
24655
24656 @item Hexadecimal numbers
24657 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
24658 @*
24659 Intel: Trailing ``h''; for example @code{A0h}
24660
24661 @item Operand size
24662 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
24663 a 16-bit word
24664 @*
24665 Intel: Implicit, deduced by assembler; for example @code{mov}
24666
24667 @item Instruction repetition
24668 gcc / @emph{as}: Split into two lines; for example
24669 @*
24670 @code{rep}
24671 @*
24672 @code{stosl}
24673 @*
24674 Intel: Keep on one line; for example @code{rep stosl}
24675
24676 @item Order of operands
24677 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
24678 @*
24679 Intel: Destination first; for example @code{mov eax, 4}
24680 @end table
24681
24682 @c ---------------------------------------------------------------------------
24683 @node A Simple Example of Inline Assembler
24684 @section A Simple Example of Inline Assembler
24685
24686 @noindent
24687 The following example will generate a single assembly language statement,
24688 @code{nop}, which does nothing.  Despite its lack of run-time effect,
24689 the example will be useful in illustrating the basics of
24690 the Inline Assembler facility.
24691
24692 @smallexample @c ada
24693 @group
24694 with System.Machine_Code; use System.Machine_Code;
24695 procedure Nothing is
24696 begin
24697    Asm ("nop");
24698 end Nothing;
24699 @end group
24700 @end smallexample
24701
24702 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
24703 here it takes one parameter, a @emph{template string} that must be a static
24704 expression and that will form the generated instruction.
24705 @code{Asm} may be regarded as a compile-time procedure that parses
24706 the template string and additional parameters (none here),
24707 from which it generates a sequence of assembly language instructions.
24708
24709 The examples in this chapter will illustrate several of the forms
24710 for invoking @code{Asm}; a complete specification of the syntax
24711 is found in the @cite{GNAT Reference Manual}.
24712
24713 Under the standard GNAT conventions, the @code{Nothing} procedure
24714 should be in a file named @file{nothing.adb}.
24715 You can build the executable in the usual way:
24716 @smallexample
24717 gnatmake nothing
24718 @end smallexample
24719 However, the interesting aspect of this example is not its run-time behavior
24720 but rather the generated assembly code.
24721 To see this output, invoke the compiler as follows:
24722 @smallexample
24723    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
24724 @end smallexample
24725 where the options are:
24726
24727 @table @code
24728 @item -c
24729 compile only (no bind or link)
24730 @item -S
24731 generate assembler listing
24732 @item -fomit-frame-pointer
24733 do not set up separate stack frames
24734 @item -gnatp
24735 do not add runtime checks
24736 @end table
24737
24738 This gives a human-readable assembler version of the code. The resulting
24739 file will have the same name as the Ada source file, but with a @code{.s}
24740 extension. In our example, the file @file{nothing.s} has the following
24741 contents:
24742
24743 @smallexample
24744 @group
24745 .file "nothing.adb"
24746 gcc2_compiled.:
24747 ___gnu_compiled_ada:
24748 .text
24749    .align 4
24750 .globl __ada_nothing
24751 __ada_nothing:
24752 #APP
24753    nop
24754 #NO_APP
24755    jmp L1
24756    .align 2,0x90
24757 L1:
24758    ret
24759 @end group
24760 @end smallexample
24761
24762 The assembly code you included is clearly indicated by
24763 the compiler, between the @code{#APP} and @code{#NO_APP}
24764 delimiters. The character before the 'APP' and 'NOAPP'
24765 can differ on different targets. For example, GNU/Linux uses '#APP' while
24766 on NT you will see '/APP'.
24767
24768 If you make a mistake in your assembler code (such as using the
24769 wrong size modifier, or using a wrong operand for the instruction) GNAT
24770 will report this error in a temporary file, which will be deleted when
24771 the compilation is finished.  Generating an assembler file will help
24772 in such cases, since you can assemble this file separately using the
24773 @emph{as} assembler that comes with gcc.
24774
24775 Assembling the file using the command
24776
24777 @smallexample
24778 as @file{nothing.s}
24779 @end smallexample
24780 @noindent
24781 will give you error messages whose lines correspond to the assembler
24782 input file, so you can easily find and correct any mistakes you made.
24783 If there are no errors, @emph{as} will generate an object file
24784 @file{nothing.out}.
24785
24786 @c ---------------------------------------------------------------------------
24787 @node Output Variables in Inline Assembler
24788 @section Output Variables in Inline Assembler
24789
24790 @noindent
24791 The examples in this section, showing how to access the processor flags,
24792 illustrate how to specify the destination operands for assembly language
24793 statements.
24794
24795 @smallexample @c ada
24796 @group
24797 with Interfaces; use Interfaces;
24798 with Ada.Text_IO; use Ada.Text_IO;
24799 with System.Machine_Code; use System.Machine_Code;
24800 procedure Get_Flags is
24801    Flags : Unsigned_32;
24802    use ASCII;
24803 begin
24804    Asm ("pushfl"          & LF & HT & -- push flags on stack
24805         "popl %%eax"      & LF & HT & -- load eax with flags
24806         "movl %%eax, %0",             -- store flags in variable
24807         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24808    Put_Line ("Flags register:" & Flags'Img);
24809 end Get_Flags;
24810 @end group
24811 @end smallexample
24812
24813 In order to have a nicely aligned assembly listing, we have separated
24814 multiple assembler statements in the Asm template string with linefeed
24815 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
24816 The resulting section of the assembly output file is:
24817
24818 @smallexample
24819 @group
24820 #APP
24821    pushfl
24822    popl %eax
24823    movl %eax, -40(%ebp)
24824 #NO_APP
24825 @end group
24826 @end smallexample
24827
24828 It would have been legal to write the Asm invocation as:
24829
24830 @smallexample
24831 Asm ("pushfl popl %%eax movl %%eax, %0")
24832 @end smallexample
24833
24834 but in the generated assembler file, this would come out as:
24835
24836 @smallexample
24837 #APP
24838    pushfl popl %eax movl %eax, -40(%ebp)
24839 #NO_APP
24840 @end smallexample
24841
24842 which is not so convenient for the human reader.
24843
24844 We use Ada comments
24845 at the end of each line to explain what the assembler instructions
24846 actually do.  This is a useful convention.
24847
24848 When writing Inline Assembler instructions, you need to precede each register
24849 and variable name with a percent sign.  Since the assembler already requires
24850 a percent sign at the beginning of a register name, you need two consecutive
24851 percent signs for such names in the Asm template string, thus @code{%%eax}.
24852 In the generated assembly code, one of the percent signs will be stripped off.
24853
24854 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
24855 variables: operands you later define using @code{Input} or @code{Output}
24856 parameters to @code{Asm}.
24857 An output variable is illustrated in
24858 the third statement in the Asm template string:
24859 @smallexample
24860 movl %%eax, %0
24861 @end smallexample
24862 The intent is to store the contents of the eax register in a variable that can
24863 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
24864 necessarily work, since the compiler might optimize by using a register
24865 to hold Flags, and the expansion of the @code{movl} instruction would not be
24866 aware of this optimization.  The solution is not to store the result directly
24867 but rather to advise the compiler to choose the correct operand form;
24868 that is the purpose of the @code{%0} output variable.
24869
24870 Information about the output variable is supplied in the @code{Outputs}
24871 parameter to @code{Asm}:
24872 @smallexample
24873 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24874 @end smallexample
24875
24876 The output is defined by the @code{Asm_Output} attribute of the target type;
24877 the general format is
24878 @smallexample
24879 Type'Asm_Output (constraint_string, variable_name)
24880 @end smallexample
24881
24882 The constraint string directs the compiler how
24883 to store/access the associated variable.  In the example
24884 @smallexample
24885 Unsigned_32'Asm_Output ("=m", Flags);
24886 @end smallexample
24887 the @code{"m"} (memory) constraint tells the compiler that the variable
24888 @code{Flags} should be stored in a memory variable, thus preventing
24889 the optimizer from keeping it in a register.  In contrast,
24890 @smallexample
24891 Unsigned_32'Asm_Output ("=r", Flags);
24892 @end smallexample
24893 uses the @code{"r"} (register) constraint, telling the compiler to
24894 store the variable in a register.
24895
24896 If the constraint is preceded by the equal character (@strong{=}), it tells
24897 the compiler that the variable will be used to store data into it.
24898
24899 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
24900 allowing the optimizer to choose whatever it deems best.
24901
24902 There are a fairly large number of constraints, but the ones that are
24903 most useful (for the Intel x86 processor) are the following:
24904
24905 @table @code
24906 @item =
24907 output constraint
24908 @item g
24909 global (i.e. can be stored anywhere)
24910 @item m
24911 in memory
24912 @item I
24913 a constant
24914 @item a
24915 use eax
24916 @item b
24917 use ebx
24918 @item c
24919 use ecx
24920 @item d
24921 use edx
24922 @item S
24923 use esi
24924 @item D
24925 use edi
24926 @item r
24927 use one of eax, ebx, ecx or edx
24928 @item q
24929 use one of eax, ebx, ecx, edx, esi or edi
24930 @end table
24931
24932 The full set of constraints is described in the gcc and @emph{as}
24933 documentation; note that it is possible to combine certain constraints
24934 in one constraint string.
24935
24936 You specify the association of an output variable with an assembler operand
24937 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
24938 integer.  Thus in
24939 @smallexample @c ada
24940 @group
24941 Asm ("pushfl"          & LF & HT & -- push flags on stack
24942      "popl %%eax"      & LF & HT & -- load eax with flags
24943      "movl %%eax, %0",             -- store flags in variable
24944      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24945 @end group
24946 @end smallexample
24947 @noindent
24948 @code{%0} will be replaced in the expanded code by the appropriate operand,
24949 whatever
24950 the compiler decided for the @code{Flags} variable.
24951
24952 In general, you may have any number of output variables:
24953 @itemize @bullet
24954 @item
24955 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
24956 @item
24957 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
24958 of @code{Asm_Output} attributes
24959 @end itemize
24960
24961 For example:
24962 @smallexample @c ada
24963 @group
24964 Asm ("movl %%eax, %0" & LF & HT &
24965      "movl %%ebx, %1" & LF & HT &
24966      "movl %%ecx, %2",
24967      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
24968                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
24969                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
24970 @end group
24971 @end smallexample
24972 @noindent
24973 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
24974 in the Ada program.
24975
24976 As a variation on the @code{Get_Flags} example, we can use the constraints
24977 string to direct the compiler to store the eax register into the @code{Flags}
24978 variable, instead of including the store instruction explicitly in the
24979 @code{Asm} template string:
24980
24981 @smallexample @c ada
24982 @group
24983 with Interfaces; use Interfaces;
24984 with Ada.Text_IO; use Ada.Text_IO;
24985 with System.Machine_Code; use System.Machine_Code;
24986 procedure Get_Flags_2 is
24987    Flags : Unsigned_32;
24988    use ASCII;
24989 begin
24990    Asm ("pushfl"      & LF & HT & -- push flags on stack
24991         "popl %%eax",             -- save flags in eax
24992         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
24993    Put_Line ("Flags register:" & Flags'Img);
24994 end Get_Flags_2;
24995 @end group
24996 @end smallexample
24997
24998 @noindent
24999 The @code{"a"} constraint tells the compiler that the @code{Flags}
25000 variable will come from the eax register. Here is the resulting code:
25001
25002 @smallexample
25003 @group
25004 #APP
25005    pushfl
25006    popl %eax
25007 #NO_APP
25008    movl %eax,-40(%ebp)
25009 @end group
25010 @end smallexample
25011
25012 @noindent
25013 The compiler generated the store of eax into Flags after
25014 expanding the assembler code.
25015
25016 Actually, there was no need to pop the flags into the eax register;
25017 more simply, we could just pop the flags directly into the program variable:
25018
25019 @smallexample @c ada
25020 @group
25021 with Interfaces; use Interfaces;
25022 with Ada.Text_IO; use Ada.Text_IO;
25023 with System.Machine_Code; use System.Machine_Code;
25024 procedure Get_Flags_3 is
25025    Flags : Unsigned_32;
25026    use ASCII;
25027 begin
25028    Asm ("pushfl"  & LF & HT & -- push flags on stack
25029         "pop %0",             -- save flags in Flags
25030         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25031    Put_Line ("Flags register:" & Flags'Img);
25032 end Get_Flags_3;
25033 @end group
25034 @end smallexample
25035
25036 @c ---------------------------------------------------------------------------
25037 @node Input Variables in Inline Assembler
25038 @section Input Variables in Inline Assembler
25039
25040 @noindent
25041 The example in this section illustrates how to specify the source operands
25042 for assembly language statements.
25043 The program simply increments its input value by 1:
25044
25045 @smallexample @c ada
25046 @group
25047 with Interfaces; use Interfaces;
25048 with Ada.Text_IO; use Ada.Text_IO;
25049 with System.Machine_Code; use System.Machine_Code;
25050 procedure Increment is
25051
25052    function Incr (Value : Unsigned_32) return Unsigned_32 is
25053       Result : Unsigned_32;
25054    begin
25055       Asm ("incl %0",
25056            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25057            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25058       return Result;
25059    end Incr;
25060
25061    Value : Unsigned_32;
25062
25063 begin
25064    Value := 5;
25065    Put_Line ("Value before is" & Value'Img);
25066    Value := Incr (Value);
25067    Put_Line ("Value after is" & Value'Img);
25068 end Increment;
25069 @end group
25070 @end smallexample
25071
25072 The @code{Outputs} parameter to @code{Asm} specifies
25073 that the result will be in the eax register and that it is to be stored
25074 in the @code{Result} variable.
25075
25076 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25077 but with an @code{Asm_Input} attribute.
25078 The @code{"="} constraint, indicating an output value, is not present.
25079
25080 You can have multiple input variables, in the same way that you can have more
25081 than one output variable.
25082
25083 The parameter count (%0, %1) etc, now starts at the first input
25084 statement, and continues with the output statements.
25085 When both parameters use the same variable, the
25086 compiler will treat them as the same %n operand, which is the case here.
25087
25088 Just as the @code{Outputs} parameter causes the register to be stored into the
25089 target variable after execution of the assembler statements, so does the
25090 @code{Inputs} parameter cause its variable to be loaded into the register
25091 before execution of the assembler statements.
25092
25093 Thus the effect of the @code{Asm} invocation is:
25094 @enumerate
25095 @item load the 32-bit value of @code{Value} into eax
25096 @item execute the @code{incl %eax} instruction
25097 @item store the contents of eax into the @code{Result} variable
25098 @end enumerate
25099
25100 The resulting assembler file (with @option{-O2} optimization) contains:
25101 @smallexample
25102 @group
25103 _increment__incr.1:
25104    subl $4,%esp
25105    movl 8(%esp),%eax
25106 #APP
25107    incl %eax
25108 #NO_APP
25109    movl %eax,%edx
25110    movl %ecx,(%esp)
25111    addl $4,%esp
25112    ret
25113 @end group
25114 @end smallexample
25115
25116 @c ---------------------------------------------------------------------------
25117 @node Inlining Inline Assembler Code
25118 @section Inlining Inline Assembler Code
25119
25120 @noindent
25121 For a short subprogram such as the @code{Incr} function in the previous
25122 section, the overhead of the call and return (creating / deleting the stack
25123 frame) can be significant, compared to the amount of code in the subprogram
25124 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25125 which directs the compiler to expand invocations of the subprogram at the
25126 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25127 Here is the resulting program:
25128
25129 @smallexample @c ada
25130 @group
25131 with Interfaces; use Interfaces;
25132 with Ada.Text_IO; use Ada.Text_IO;
25133 with System.Machine_Code; use System.Machine_Code;
25134 procedure Increment_2 is
25135
25136    function Incr (Value : Unsigned_32) return Unsigned_32 is
25137       Result : Unsigned_32;
25138    begin
25139       Asm ("incl %0",
25140            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25141            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25142       return Result;
25143    end Incr;
25144    pragma Inline (Increment);
25145
25146    Value : Unsigned_32;
25147
25148 begin
25149    Value := 5;
25150    Put_Line ("Value before is" & Value'Img);
25151    Value := Increment (Value);
25152    Put_Line ("Value after is" & Value'Img);
25153 end Increment_2;
25154 @end group
25155 @end smallexample
25156
25157 Compile the program with both optimization (@option{-O2}) and inlining
25158 enabled (@option{-gnatpn} instead of @option{-gnatp}).
25159
25160 The @code{Incr} function is still compiled as usual, but at the
25161 point in @code{Increment} where our function used to be called:
25162
25163 @smallexample
25164 @group
25165 pushl %edi
25166 call _increment__incr.1
25167 @end group
25168 @end smallexample
25169
25170 @noindent
25171 the code for the function body directly appears:
25172
25173 @smallexample
25174 @group
25175 movl %esi,%eax
25176 #APP
25177    incl %eax
25178 #NO_APP
25179    movl %eax,%edx
25180 @end group
25181 @end smallexample
25182
25183 @noindent
25184 thus saving the overhead of stack frame setup and an out-of-line call.
25185
25186 @c ---------------------------------------------------------------------------
25187 @node Other Asm Functionality
25188 @section Other @code{Asm} Functionality
25189
25190 @noindent
25191 This section describes two important parameters to the @code{Asm}
25192 procedure: @code{Clobber}, which identifies register usage;
25193 and @code{Volatile}, which inhibits unwanted optimizations.
25194
25195 @menu
25196 * The Clobber Parameter::
25197 * The Volatile Parameter::
25198 @end menu
25199
25200 @c ---------------------------------------------------------------------------
25201 @node The Clobber Parameter
25202 @subsection The @code{Clobber} Parameter
25203
25204 @noindent
25205 One of the dangers of intermixing assembly language and a compiled language
25206 such as Ada is that the compiler needs to be aware of which registers are
25207 being used by the assembly code.  In some cases, such as the earlier examples,
25208 the constraint string is sufficient to indicate register usage (e.g.,
25209 @code{"a"} for
25210 the eax register).  But more generally, the compiler needs an explicit
25211 identification of the registers that are used by the Inline Assembly
25212 statements.
25213
25214 Using a register that the compiler doesn't know about
25215 could be a side effect of an instruction (like @code{mull}
25216 storing its result in both eax and edx).
25217 It can also arise from explicit register usage in your
25218 assembly code; for example:
25219 @smallexample
25220 @group
25221 Asm ("movl %0, %%ebx" & LF & HT &
25222      "movl %%ebx, %1",
25223      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25224      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25225 @end group
25226 @end smallexample
25227 @noindent
25228 where the compiler (since it does not analyze the @code{Asm} template string)
25229 does not know you are using the ebx register.
25230
25231 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25232 to identify the registers that will be used by your assembly code:
25233
25234 @smallexample
25235 @group
25236 Asm ("movl %0, %%ebx" & LF & HT &
25237      "movl %%ebx, %1",
25238      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25239      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25240      Clobber => "ebx");
25241 @end group
25242 @end smallexample
25243
25244 The Clobber parameter is a static string expression specifying the
25245 register(s) you are using.  Note that register names are @emph{not} prefixed
25246 by a percent sign. Also, if more than one register is used then their names
25247 are separated by commas; e.g., @code{"eax, ebx"}
25248
25249 The @code{Clobber} parameter has several additional uses:
25250 @enumerate
25251 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25252 @item Use ``register'' name @code{memory} if you changed a memory location
25253 @end enumerate
25254
25255 @c ---------------------------------------------------------------------------
25256 @node The Volatile Parameter
25257 @subsection The @code{Volatile} Parameter
25258 @cindex Volatile parameter
25259
25260 @noindent
25261 Compiler optimizations in the presence of Inline Assembler may sometimes have
25262 unwanted effects.  For example, when an @code{Asm} invocation with an input
25263 variable is inside a loop, the compiler might move the loading of the input
25264 variable outside the loop, regarding it as a one-time initialization.
25265
25266 If this effect is not desired, you can disable such optimizations by setting
25267 the @code{Volatile} parameter to @code{True}; for example:
25268
25269 @smallexample @c ada
25270 @group
25271 Asm ("movl %0, %%ebx" & LF & HT &
25272      "movl %%ebx, %1",
25273      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
25274      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
25275      Clobber  => "ebx",
25276      Volatile => True);
25277 @end group
25278 @end smallexample
25279
25280 By default, @code{Volatile} is set to @code{False} unless there is no
25281 @code{Outputs} parameter.
25282
25283 Although setting @code{Volatile} to @code{True} prevents unwanted
25284 optimizations, it will also disable other optimizations that might be
25285 important for efficiency. In general, you should set @code{Volatile}
25286 to @code{True} only if the compiler's optimizations have created
25287 problems.
25288 @c END OF INLINE ASSEMBLER CHAPTER
25289 @c ===============================
25290
25291 @c ***********************************
25292 @c * Compatibility and Porting Guide *
25293 @c ***********************************
25294 @node Compatibility and Porting Guide
25295 @appendix Compatibility and Porting Guide
25296
25297 @noindent
25298 This chapter describes the compatibility issues that may arise between
25299 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
25300 can expedite porting
25301 applications developed in other Ada environments.
25302
25303 @menu
25304 * Compatibility with Ada 83::
25305 * Implementation-dependent characteristics::
25306 * Compatibility with Other Ada 95 Systems::
25307 * Representation Clauses::
25308 * Compatibility with DEC Ada 83::
25309 @ifset vms
25310 * Transitioning from Alpha to Integrity OpenVMS::
25311 @end ifset
25312 @end menu
25313
25314 @node Compatibility with Ada 83
25315 @section Compatibility with Ada 83
25316 @cindex Compatibility (between Ada 83 and Ada 95)
25317
25318 @noindent
25319 Ada 95 is designed to be highly upwards compatible with Ada 83.  In
25320 particular, the design intention is that the difficulties associated
25321 with moving from Ada 83 to Ada 95 should be no greater than those
25322 that occur when moving from one Ada 83 system to another.
25323
25324 However, there are a number of points at which there are minor
25325 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25326 full details of these issues,
25327 and should be consulted for a complete treatment.
25328 In practice the
25329 following subsections treat the most likely issues to be encountered.
25330
25331 @menu
25332 * Legal Ada 83 programs that are illegal in Ada 95::
25333 * More deterministic semantics::
25334 * Changed semantics::
25335 * Other language compatibility issues::
25336 @end menu
25337
25338 @node Legal Ada 83 programs that are illegal in Ada 95
25339 @subsection Legal Ada 83 programs that are illegal in Ada 95
25340
25341 @table @asis
25342 @item Character literals
25343 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25344 @code{Wide_Character} as a new predefined character type, some uses of
25345 character literals that were legal in Ada 83 are illegal in Ada 95.
25346 For example:
25347 @smallexample @c ada
25348    for Char in 'A' .. 'Z' loop ... end loop;
25349 @end smallexample
25350 @noindent
25351 The problem is that @code{'A'} and @code{'Z'} could be from either
25352 @code{Character} or @code{Wide_Character}.  The simplest correction
25353 is to make the type explicit; e.g.:
25354 @smallexample @c ada
25355    for Char in Character range 'A' .. 'Z' loop ... end loop;
25356 @end smallexample
25357
25358 @item New reserved words
25359 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25360 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25361 Existing Ada 83 code using any of these identifiers must be edited to
25362 use some alternative name.
25363
25364 @item Freezing rules
25365 The rules in Ada 95 are slightly different with regard to the point at
25366 which entities are frozen, and representation pragmas and clauses are
25367 not permitted past the freeze point.  This shows up most typically in
25368 the form of an error message complaining that a representation item
25369 appears too late, and the appropriate corrective action is to move
25370 the item nearer to the declaration of the entity to which it refers.
25371
25372 A particular case is that representation pragmas
25373 @ifset vms
25374 (including the
25375 extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure})
25376 @end ifset
25377 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25378 declaration must be introduced to which the pragma can be applied.
25379
25380 @item Optional bodies for library packages
25381 In Ada 83, a package that did not require a package body was nevertheless
25382 allowed to have one.  This lead to certain surprises in compiling large
25383 systems (situations in which the body could be unexpectedly ignored by the
25384 binder).  In Ada 95, if a package does not require a body then it is not
25385 permitted to have a body.  To fix this problem, simply remove a redundant
25386 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25387 into the spec that makes the body required.  One approach is to add a private
25388 part to the package declaration (if necessary), and define a parameterless
25389 procedure called @code{Requires_Body}, which must then be given a dummy
25390 procedure body in the package body, which then becomes required.
25391 Another approach (assuming that this does not introduce elaboration
25392 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25393 since one effect of this pragma is to require the presence of a package body.
25394
25395 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25396 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25397 @code{Constraint_Error}.
25398 This means that it is illegal to have separate exception handlers for
25399 the two exceptions.  The fix is simply to remove the handler for the
25400 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25401 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25402
25403 @item Indefinite subtypes in generics
25404 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25405 as the actual for a generic formal private type, but then the instantiation
25406 would be illegal if there were any instances of declarations of variables
25407 of this type in the generic body.  In Ada 95, to avoid this clear violation
25408 of the methodological principle known as the ``contract model'',
25409 the generic declaration explicitly indicates whether
25410 or not such instantiations are permitted.  If a generic formal parameter
25411 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25412 type name, then it can be instantiated with indefinite types, but no
25413 stand-alone variables can be declared of this type.  Any attempt to declare
25414 such a variable will result in an illegality at the time the generic is
25415 declared.  If the @code{(<>)} notation is not used, then it is illegal
25416 to instantiate the generic with an indefinite type.
25417 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25418 It will show up as a compile time error, and
25419 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25420 @end table
25421
25422 @node More deterministic semantics
25423 @subsection More deterministic semantics
25424
25425 @table @asis
25426 @item Conversions
25427 Conversions from real types to integer types round away from 0.  In Ada 83
25428 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
25429 implementation freedom was intended to support unbiased rounding in
25430 statistical applications, but in practice it interfered with portability.
25431 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25432 is required.  Numeric code may be affected by this change in semantics.
25433 Note, though, that this issue is no worse than already existed in Ada 83
25434 when porting code from one vendor to another.
25435
25436 @item Tasking
25437 The Real-Time Annex introduces a set of policies that define the behavior of
25438 features that were implementation dependent in Ada 83, such as the order in
25439 which open select branches are executed.
25440 @end table
25441
25442 @node Changed semantics
25443 @subsection Changed semantics
25444
25445 @noindent
25446 The worst kind of incompatibility is one where a program that is legal in
25447 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25448 possible in Ada 83.  Fortunately this is extremely rare, but the one
25449 situation that you should be alert to is the change in the predefined type
25450 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25451
25452 @table @asis
25453 @item range of @code{Character}
25454 The range of @code{Standard.Character} is now the full 256 characters
25455 of Latin-1, whereas in most Ada 83 implementations it was restricted
25456 to 128 characters. Although some of the effects of
25457 this change will be manifest in compile-time rejection of legal
25458 Ada 83 programs it is possible for a working Ada 83 program to have
25459 a different effect in Ada 95, one that was not permitted in Ada 83.
25460 As an example, the expression
25461 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25462 delivers @code{255} as its value.
25463 In general, you should look at the logic of any
25464 character-processing Ada 83 program and see whether it needs to be adapted
25465 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
25466 character handling package that may be relevant if code needs to be adapted
25467 to account for the additional Latin-1 elements.
25468 The desirable fix is to
25469 modify the program to accommodate the full character set, but in some cases
25470 it may be convenient to define a subtype or derived type of Character that
25471 covers only the restricted range.
25472 @cindex Latin-1
25473 @end table
25474
25475 @node Other language compatibility issues
25476 @subsection Other language compatibility issues
25477 @table @asis
25478 @item @option{-gnat83 switch}
25479 All implementations of GNAT provide a switch that causes GNAT to operate
25480 in Ada 83 mode.  In this mode, some but not all compatibility problems
25481 of the type described above are handled automatically.  For example, the
25482 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
25483 However,
25484 in practice, it is usually advisable to make the necessary modifications
25485 to the program to remove the need for using this switch.
25486 See @ref{Compiling Different Versions of Ada}.
25487
25488 @item Support for removed Ada 83 pragmas and attributes
25489 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
25490 generally because they have been replaced by other mechanisms.  Ada 95
25491 compilers are allowed, but not required, to implement these missing
25492 elements.  In contrast with some other Ada 95 compilers, GNAT implements all
25493 such pragmas and attributes, eliminating this compatibility concern.  These
25494 include @code{pragma Interface} and the floating point type attributes
25495 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25496 @end table
25497
25498 @node Implementation-dependent characteristics
25499 @section Implementation-dependent characteristics
25500 @noindent
25501 Although the Ada language defines the semantics of each construct as
25502 precisely as practical, in some situations (for example for reasons of
25503 efficiency, or where the effect is heavily dependent on the host or target
25504 platform) the implementation is allowed some freedom.  In porting Ada 83
25505 code to GNAT, you need to be aware of whether / how the existing code
25506 exercised such implementation dependencies.  Such characteristics fall into
25507 several categories, and GNAT offers specific support in assisting the
25508 transition from certain Ada 83 compilers.
25509
25510 @menu
25511 * Implementation-defined pragmas::
25512 * Implementation-defined attributes::
25513 * Libraries::
25514 * Elaboration order::
25515 * Target-specific aspects::
25516 @end menu
25517
25518 @node Implementation-defined pragmas
25519 @subsection Implementation-defined pragmas
25520
25521 @noindent
25522 Ada compilers are allowed to supplement the language-defined pragmas, and
25523 these are a potential source of non-portability.  All GNAT-defined pragmas
25524 are described in the GNAT Reference Manual, and these include several that
25525 are specifically intended to correspond to other vendors' Ada 83 pragmas.
25526 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25527 For
25528 compatibility with DEC Ada 83, GNAT supplies the pragmas
25529 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25530 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25531 and @code{Volatile}.
25532 Other relevant pragmas include @code{External} and @code{Link_With}.
25533 Some vendor-specific
25534 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25535 recognized, thus
25536 avoiding compiler rejection of units that contain such pragmas; they are not
25537 relevant in a GNAT context and hence are not otherwise implemented.
25538
25539 @node Implementation-defined attributes
25540 @subsection Implementation-defined attributes
25541
25542 Analogous to pragmas, the set of attributes may be extended by an
25543 implementation.  All GNAT-defined attributes are described in the
25544 @cite{GNAT Reference Manual}, and these include several that are specifically
25545 intended
25546 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
25547 the attribute @code{VADS_Size} may be useful.  For compatibility with DEC
25548 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25549 @code{Type_Class}.
25550
25551 @node Libraries
25552 @subsection Libraries
25553 @noindent
25554 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
25555 code uses vendor-specific libraries then there are several ways to manage
25556 this in Ada 95:
25557 @enumerate
25558 @item
25559 If the source code for the libraries (specifications and bodies) are
25560 available, then the libraries can be migrated in the same way as the
25561 application.
25562 @item
25563 If the source code for the specifications but not the bodies are
25564 available, then you can reimplement the bodies.
25565 @item
25566 Some new Ada 95 features obviate the need for library support.  For
25567 example most Ada 83 vendors supplied a package for unsigned integers.  The
25568 Ada 95 modular type feature is the preferred way to handle this need, so
25569 instead of migrating or reimplementing the unsigned integer package it may
25570 be preferable to retrofit the application using modular types.
25571 @end enumerate
25572
25573 @node Elaboration order
25574 @subsection Elaboration order
25575 @noindent
25576 The implementation can choose any elaboration order consistent with the unit
25577 dependency relationship.  This freedom means that some orders can result in
25578 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25579 to invoke a subprogram its body has been elaborated, or to instantiate a
25580 generic before the generic body has been elaborated.  By default GNAT
25581 attempts to choose a safe order (one that will not encounter access before
25582 elaboration problems) by implicitly inserting Elaborate_All pragmas where
25583 needed.  However, this can lead to the creation of elaboration circularities
25584 and a resulting rejection of the program by gnatbind.  This issue is
25585 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25586 In brief, there are several
25587 ways to deal with this situation:
25588
25589 @itemize @bullet
25590 @item
25591 Modify the program to eliminate the circularities, e.g. by moving
25592 elaboration-time code into explicitly-invoked procedures
25593 @item
25594 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25595 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25596 @code{Elaborate_All}
25597 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25598 (by selectively suppressing elaboration checks via pragma
25599 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25600 @end itemize
25601
25602 @node Target-specific aspects
25603 @subsection Target-specific aspects
25604 @noindent
25605 Low-level applications need to deal with machine addresses, data
25606 representations, interfacing with assembler code, and similar issues.  If
25607 such an Ada 83 application is being ported to different target hardware (for
25608 example where the byte endianness has changed) then you will need to
25609 carefully examine the program logic; the porting effort will heavily depend
25610 on the robustness of the original design.  Moreover, Ada 95 is sometimes
25611 incompatible with typical Ada 83 compiler practices regarding implicit
25612 packing, the meaning of the Size attribute, and the size of access values.
25613 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25614
25615 @node Compatibility with Other Ada 95 Systems
25616 @section Compatibility with Other Ada 95 Systems
25617
25618 @noindent
25619 Providing that programs avoid the use of implementation dependent and
25620 implementation defined features of Ada 95, as documented in the Ada 95
25621 reference manual, there should be a high degree of portability between
25622 GNAT and other Ada 95 systems.  The following are specific items which
25623 have proved troublesome in moving GNAT programs to other Ada 95
25624 compilers, but do not affect porting code to GNAT@.
25625
25626 @table @asis
25627 @item Ada 83 Pragmas and Attributes
25628 Ada 95 compilers are allowed, but not required, to implement the missing
25629 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25630 GNAT implements all such pragmas and attributes, eliminating this as
25631 a compatibility concern, but some other Ada 95 compilers reject these
25632 pragmas and attributes.
25633
25634 @item Special-needs Annexes
25635 GNAT implements the full set of special needs annexes.  At the
25636 current time, it is the only Ada 95 compiler to do so.  This means that
25637 programs making use of these features may not be portable to other Ada
25638 95 compilation systems.
25639
25640 @item Representation Clauses
25641 Some other Ada 95 compilers implement only the minimal set of
25642 representation clauses required by the Ada 95 reference manual.  GNAT goes
25643 far beyond this minimal set, as described in the next section.
25644 @end table
25645
25646 @node Representation Clauses
25647 @section Representation Clauses
25648
25649 @noindent
25650 The Ada 83 reference manual was quite vague in describing both the minimal
25651 required implementation of representation clauses, and also their precise
25652 effects.  The Ada 95 reference manual is much more explicit, but the minimal
25653 set of capabilities required in Ada 95 is quite limited.
25654
25655 GNAT implements the full required set of capabilities described in the
25656 Ada 95 reference manual, but also goes much beyond this, and in particular
25657 an effort has been made to be compatible with existing Ada 83 usage to the
25658 greatest extent possible.
25659
25660 A few cases exist in which Ada 83 compiler behavior is incompatible with
25661 requirements in the Ada 95 reference manual.  These are instances of
25662 intentional or accidental dependence on specific implementation dependent
25663 characteristics of these Ada 83 compilers.  The following is a list of
25664 the cases most likely to arise in existing legacy Ada 83 code.
25665
25666 @table @asis
25667 @item Implicit Packing
25668 Some Ada 83 compilers allowed a Size specification to cause implicit
25669 packing of an array or record.  This could cause expensive implicit
25670 conversions for change of representation in the presence of derived
25671 types, and the Ada design intends to avoid this possibility.
25672 Subsequent AI's were issued to make it clear that such implicit
25673 change of representation in response to a Size clause is inadvisable,
25674 and this recommendation is represented explicitly in the Ada 95 RM
25675 as implementation advice that is followed by GNAT@.
25676 The problem will show up as an error
25677 message rejecting the size clause.  The fix is simply to provide
25678 the explicit pragma @code{Pack}, or for more fine tuned control, provide
25679 a Component_Size clause.
25680
25681 @item Meaning of Size Attribute
25682 The Size attribute in Ada 95 for discrete types is defined as being the
25683 minimal number of bits required to hold values of the type.  For example,
25684 on a 32-bit machine, the size of Natural will typically be 31 and not
25685 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
25686 some 32 in this situation.  This problem will usually show up as a compile
25687 time error, but not always.  It is a good idea to check all uses of the
25688 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
25689 Object_Size can provide a useful way of duplicating the behavior of
25690 some Ada 83 compiler systems.
25691
25692 @item Size of Access Types
25693 A common assumption in Ada 83 code is that an access type is in fact a pointer,
25694 and that therefore it will be the same size as a System.Address value.  This
25695 assumption is true for GNAT in most cases with one exception.  For the case of
25696 a pointer to an unconstrained array type (where the bounds may vary from one
25697 value of the access type to another), the default is to use a ``fat pointer'',
25698 which is represented as two separate pointers, one to the bounds, and one to
25699 the array.  This representation has a number of advantages, including improved
25700 efficiency.  However, it may cause some difficulties in porting existing Ada 83
25701 code which makes the assumption that, for example, pointers fit in 32 bits on
25702 a machine with 32-bit addressing.
25703
25704 To get around this problem, GNAT also permits the use of ``thin pointers'' for
25705 access types in this case (where the designated type is an unconstrained array
25706 type).  These thin pointers are indeed the same size as a System.Address value.
25707 To specify a thin pointer, use a size clause for the type, for example:
25708
25709 @smallexample @c ada
25710 type X is access all String;
25711 for X'Size use Standard'Address_Size;
25712 @end smallexample
25713
25714 @noindent
25715 which will cause the type X to be represented using a single pointer.
25716 When using this representation, the bounds are right behind the array.
25717 This representation is slightly less efficient, and does not allow quite
25718 such flexibility in the use of foreign pointers or in using the
25719 Unrestricted_Access attribute to create pointers to non-aliased objects.
25720 But for any standard portable use of the access type it will work in
25721 a functionally correct manner and allow porting of existing code.
25722 Note that another way of forcing a thin pointer representation
25723 is to use a component size clause for the element size in an array,
25724 or a record representation clause for an access field in a record.
25725 @end table
25726
25727 @node Compatibility with DEC Ada 83
25728 @section Compatibility with DEC Ada 83
25729
25730 @noindent
25731 The VMS version of GNAT fully implements all the pragmas and attributes
25732 provided by DEC Ada 83, as well as providing the standard DEC Ada 83
25733 libraries, including Starlet.  In addition, data layouts and parameter
25734 passing conventions are highly compatible.  This means that porting
25735 existing DEC Ada 83 code to GNAT in VMS systems should be easier than
25736 most other porting efforts.  The following are some of the most
25737 significant differences between GNAT and DEC Ada 83.
25738
25739 @table @asis
25740 @item Default floating-point representation
25741 In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83,
25742 it is VMS format.  GNAT does implement the necessary pragmas
25743 (Long_Float, Float_Representation) for changing this default.
25744
25745 @item System
25746 The package System in GNAT exactly corresponds to the definition in the
25747 Ada 95 reference manual, which means that it excludes many of the
25748 DEC Ada 83 extensions.  However, a separate package Aux_DEC is provided
25749 that contains the additional definitions, and a special pragma,
25750 Extend_System allows this package to be treated transparently as an
25751 extension of package System.
25752
25753 @item To_Address
25754 The definitions provided by Aux_DEC are exactly compatible with those
25755 in the DEC Ada 83 version of System, with one exception.
25756 DEC Ada provides the following declarations:
25757
25758 @smallexample @c ada
25759 TO_ADDRESS (INTEGER)
25760 TO_ADDRESS (UNSIGNED_LONGWORD)
25761 TO_ADDRESS (universal_integer)
25762 @end smallexample
25763
25764 @noindent
25765 The version of TO_ADDRESS taking a universal integer argument is in fact
25766 an extension to Ada 83 not strictly compatible with the reference manual.
25767 In GNAT, we are constrained to be exactly compatible with the standard,
25768 and this means we cannot provide this capability.  In DEC Ada 83, the
25769 point of this definition is to deal with a call like:
25770
25771 @smallexample @c ada
25772 TO_ADDRESS (16#12777#);
25773 @end smallexample
25774
25775 @noindent
25776 Normally, according to the Ada 83 standard, one would expect this to be
25777 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
25778 of TO_ADDRESS@.  However, in DEC Ada 83, there is no ambiguity, since the
25779 definition using universal_integer takes precedence.
25780
25781 In GNAT, since the version with universal_integer cannot be supplied, it is
25782 not possible to be 100% compatible.  Since there are many programs using
25783 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
25784 to change the name of the function in the UNSIGNED_LONGWORD case, so the
25785 declarations provided in the GNAT version of AUX_Dec are:
25786
25787 @smallexample @c ada
25788 function To_Address (X : Integer) return Address;
25789 pragma Pure_Function (To_Address);
25790
25791 function To_Address_Long (X : Unsigned_Longword)
25792  return Address;
25793 pragma Pure_Function (To_Address_Long);
25794 @end smallexample
25795
25796 @noindent
25797 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
25798 change the name to TO_ADDRESS_LONG@.
25799
25800 @item Task_Id values
25801 The Task_Id values assigned will be different in the two systems, and GNAT
25802 does not provide a specified value for the Task_Id of the environment task,
25803 which in GNAT is treated like any other declared task.
25804 @end table
25805
25806 For full details on these and other less significant compatibility issues,
25807 see appendix E of the Digital publication entitled @cite{DEC Ada, Technical
25808 Overview and Comparison on DIGITAL Platforms}.
25809
25810 For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and
25811 attributes are recognized, although only a subset of them can sensibly
25812 be implemented.  The description of pragmas in this reference manual
25813 indicates whether or not they are applicable to non-VMS systems.
25814
25815
25816 @ifset vms
25817 @node Transitioning from Alpha to Integrity OpenVMS
25818 @section Transitioning from Alpha to Integrity OpenVMS
25819
25820 @menu
25821 * Introduction to transitioning::
25822 * Migration of 32 bit code::
25823 * Taking advantage of 64 bit addressing::
25824 * Technical details::
25825 @end menu
25826
25827 @node Introduction to transitioning
25828 @subsection Introduction to transitioning
25829
25830 @noindent
25831 This guide is meant to assist users of GNAT Pro
25832 for Alpha OpenVMS who are planning to transition to the IA64 architecture.
25833 GNAT Pro for Open VMS Integrity has been designed to meet
25834 three main goals:
25835
25836 @enumerate
25837 @item
25838 Providing a full conforming implementation of the Ada 95 language
25839
25840 @item
25841 Allowing maximum backward compatibility, thus easing migration of existing
25842 Ada source code
25843
25844 @item
25845 Supplying a path for exploiting the full IA64 address range
25846 @end enumerate
25847
25848 @noindent
25849 Ada's strong typing semantics has made it
25850 impractical to have different 32-bit and 64-bit modes. As soon as
25851 one object could possibly be outside the 32-bit address space, this
25852 would make it necessary for the @code{System.Address} type to be 64 bits.
25853 In particular, this would cause inconsistencies if 32-bit code is
25854 called from 64-bit code that raises an exception.
25855
25856 This issue has been resolved by always using 64-bit addressing
25857 at the system level, but allowing for automatic conversions between
25858 32-bit and 64-bit addresses where required. Thus users who
25859 do not currently require 64-bit addressing capabilities, can
25860 recompile their code with only minimal changes (and indeed
25861 if the code is written in portable Ada, with no assumptions about
25862 the size of the @code{Address} type, then no changes at all are necessary).
25863 At the same time,
25864 this approach provides a simple, gradual upgrade path to future
25865 use of larger memories than available for 32-bit systems.
25866 Also, newly written applications or libraries will by default
25867 be fully compatible with future systems exploiting 64-bit
25868 addressing capabilities present in IA64.
25869
25870 @ref{Migration of 32 bit code}, will focus on porting applications
25871 that do not require more than 2 GB of
25872 addressable memory. This code will be referred to as
25873 @emph{32-bit code}.
25874 For applications intending to exploit the full ia64 address space,
25875 @ref{Taking advantage of 64 bit addressing},
25876 will consider further changes that may be required.
25877 Such code is called @emph{64-bit code} in the
25878 remainder of this guide.
25879
25880
25881 @node Migration of 32 bit code
25882 @subsection Migration of 32-bit code
25883
25884 @menu
25885 * Address types::
25886 * Access types::
25887 * Unchecked conversions::
25888 * Predefined constants::
25889 * Single source compatibility::
25890 * Experience with source compatibility::
25891 @end menu
25892
25893 @node Address types
25894 @subsubsection Address types
25895
25896 @noindent
25897 To solve the problem of mixing 64-bit and 32-bit addressing,
25898 while maintaining maximum backward compatibility, the following
25899 approach has been taken:
25900
25901 @itemize @bullet
25902 @item
25903 @code{System.Address} always has a size of 64 bits
25904
25905 @item
25906 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
25907 @end itemize
25908
25909
25910 @noindent
25911 Since @code{System.Short_Address} is a subtype of @code{System.Address},
25912 a @code{Short_Address}
25913 may be used where an @code{Address} is required, and vice versa, without
25914 needing explicit type conversions.
25915 By virtue of the Open VMS Integrity parameter passing conventions,
25916 even imported
25917 and exported subprograms that have 32-bit address parameters are
25918 compatible with those that have 64-bit address parameters.
25919 (See @ref{Making code 64 bit clean} for details.)
25920
25921 The areas that may need attention are those where record types have
25922 been defined that contain components of the type @code{System.Address}, and
25923 where objects of this type are passed to code expecting a record layout with
25924 32-bit addresses.
25925
25926 Different compilers on different platforms cannot be
25927 expected to represent the same type in the same way,
25928 since alignment constraints
25929 and other system-dependent properties affect the compiler's decision.
25930 For that reason, Ada code
25931 generally uses representation clauses to specify the expected
25932 layout where required.
25933
25934 If such a representation clause uses 32 bits for a component having
25935 the type @code{System.Address}, GNAT Pro for OpenVMS Integrity will detect
25936 that error and produce a specific diagnostic message.
25937 The developer should then determine whether the representation
25938 should be 64 bits or not and make either of two changes:
25939 change the size to 64 bits and leave the type as @code{System.Address}, or
25940 leave the size as 32 bits and change the type to @code{System.Short_Address}.
25941 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
25942 required in any code setting or accessing the field; the compiler will
25943 automatically perform any needed conversions between address
25944 formats.
25945
25946 @node Access types
25947 @subsubsection Access types
25948
25949 @noindent
25950 By default, objects designated by access values are always
25951 allocated in the 32-bit
25952 address space. Thus legacy code will never contain
25953 any objects that are not addressable with 32-bit addresses, and
25954 the compiler will never raise exceptions as result of mixing
25955 32-bit and 64-bit addresses.
25956
25957 However, the access values themselves are represented in 64 bits, for optimum
25958 performance and future compatibility with 64-bit code. As was
25959 the case with @code{System.Address}, the compiler will give an error message
25960 if an object or record component has a representation clause that
25961 requires the access value to fit in 32 bits. In such a situation,
25962 an explicit size clause for the access type, specifying 32 bits,
25963 will have the desired effect.
25964
25965 General access types (declared with @code{access all}) can never be
25966 32 bits, as values of such types must be able to refer to any object
25967 of the  designated type,
25968 including objects residing outside the 32-bit address range.
25969 Existing Ada 83 code will not contain such type definitions,
25970 however, since general access types were introduced in Ada 95.
25971
25972 @node Unchecked conversions
25973 @subsubsection Unchecked conversions
25974
25975 @noindent
25976 In the case of an @code{Unchecked_Conversion} where the source type is a
25977 64-bit access type or the type @code{System.Address}, and the target
25978 type is a 32-bit type, the compiler will generate a warning.
25979 Even though the generated code will still perform the required
25980 conversions, it is highly recommended in these cases to use
25981 respectively a 32-bit access type or @code{System.Short_Address}
25982 as the source type.
25983
25984 @node Predefined constants
25985 @subsubsection Predefined constants
25986
25987 @noindent
25988 The following predefined constants have changed:
25989
25990 @multitable {@code{System.Address_Size}} {2**32} {2**64}
25991 @item   @b{Constant}               @tab @b{Old} @tab @b{New}
25992 @item   @code{System.Word_Size}    @tab 32      @tab 64
25993 @item   @code{System.Memory_Size}  @tab 2**32   @tab 2**64
25994 @item   @code{System.Address_Size} @tab 32      @tab 64
25995 @end multitable
25996
25997 @noindent
25998 If you need to refer to the specific
25999 memory size of a 32-bit implementation, instead of the
26000 actual memory size, use @code{System.Short_Memory_Size}
26001 rather than @code{System.Memory_Size}.
26002 Similarly, references to @code{System.Address_Size} may need
26003 to be replaced by @code{System.Short_Address'Size}.
26004 The program @command{gnatfind} may be useful for locating
26005 references to the above constants, so that you can verify that they
26006 are still correct.
26007
26008 @node Single source compatibility
26009 @subsubsection Single source compatibility
26010
26011 @noindent
26012 In order to allow the same source code to be compiled on
26013 both Alpha and IA64 platforms, GNAT Pro for Alpha/OpenVMS
26014 defines @code{System.Short_Address} and System.Short_Memory_Size
26015 as aliases of respectively @code{System.Address} and
26016 @code{System.Memory_Size}.
26017 (These aliases also leave the door open for a possible
26018 future ``upgrade'' of OpenVMS Alpha to a 64-bit address space.)
26019
26020 @node Experience with source compatibility
26021 @subsubsection Experience with source compatibility
26022
26023 @noindent
26024 The Security Server and STARLET provide an interesting ``test case''
26025 for source compatibility issues, since it is in such system code
26026 where assumptions about @code{Address} size might be expected to occur.
26027 Indeed, there were a small number of occasions in the Security Server
26028 file @file{jibdef.ads}
26029 where a representation clause for a record type specified
26030 32 bits for a component of type @code{Address}.
26031 All of these errors were detected by the compiler.
26032 The repair was obvious and immediate; to simply replace @code{Address} by
26033 @code{Short_Address}.
26034
26035 In the case of STARLET, there were several record types that should
26036 have had representation clauses but did not.  In these record types
26037 there was an implicit assumption that an @code{Address} value occupied
26038 32 bits.
26039 These compiled without error, but their usage resulted in run-time error
26040 returns from STARLET system calls.
26041 To assist in the compile-time detection of such situations, we
26042 plan to include a switch to generate a warning message when a
26043 record component is of type @code{Address}.
26044
26045
26046 @c ****************************************
26047 @node Taking advantage of 64 bit addressing
26048 @subsection Taking advantage of 64-bit addressing
26049
26050 @menu
26051 * Making code 64 bit clean::
26052 * Allocating memory from the 64 bit storage pool::
26053 * Restrictions on use of 64 bit objects::
26054 * Using 64 bit storage pools by default::
26055 * General access types::
26056 * STARLET and other predefined libraries::
26057 @end menu
26058
26059 @node Making code 64 bit clean
26060 @subsubsection Making code 64-bit clean
26061
26062 @noindent
26063 In order to prevent problems that may occur when (parts of) a
26064 system start using memory outside the 32-bit address range,
26065 we recommend some additional guidelines:
26066
26067 @itemize @bullet
26068 @item
26069 For imported subprograms that take parameters of the
26070 type @code{System.Address}, ensure that these subprograms can
26071 indeed handle 64-bit addresses. If not, or when in doubt,
26072 change the subprogram declaration to specify
26073 @code{System.Short_Address} instead.
26074
26075 @item
26076 Resolve all warnings related to size mismatches in
26077 unchecked conversions. Failing to do so causes
26078 erroneous execution if the source object is outside
26079 the 32-bit address space.
26080
26081 @item
26082 (optional) Explicitly use the 32-bit storage pool
26083 for access types used in a 32-bit context, or use
26084 generic access types where possible
26085 (@pxref{Restrictions on use of 64 bit objects}).
26086 @end itemize
26087
26088 @noindent
26089 If these rules are followed, the compiler will automatically insert
26090 any necessary checks to ensure that no addresses or access values
26091 passed to 32-bit code ever refer to objects outside the 32-bit
26092 address range.
26093 Any attempt to do this will raise @code{Constraint_Error}.
26094
26095 @node Allocating memory from the 64 bit storage pool
26096 @subsubsection Allocating memory from the 64-bit storage pool
26097
26098 @noindent
26099 For any access type @code{T} that potentially requires memory allocations
26100 beyond the 32-bit address space,
26101 use the following representation clause:
26102
26103 @smallexample @c ada
26104    for T'Storage_Pool use System.Pool_64;
26105 @end smallexample
26106
26107
26108 @node Restrictions on use of 64 bit objects
26109 @subsubsection Restrictions on use of 64-bit objects
26110
26111 @noindent
26112 Taking the address of an object allocated from a 64-bit storage pool,
26113 and then passing this address to a subprogram expecting
26114 @code{System.Short_Address},
26115 or assigning it to a variable of type @code{Short_Address}, will cause
26116 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26117 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26118 no exception is raised and execution
26119 will become erroneous.
26120
26121 @node Using 64 bit storage pools by default
26122 @subsubsection Using 64-bit storage pools by default
26123
26124 @noindent
26125 In some cases it may be desirable to have the compiler allocate
26126 from 64-bit storage pools by default. This may be the case for
26127 libraries that are 64-bit clean, but may be used in both 32-bit
26128 and 64-bit contexts. For these cases the following configuration
26129 pragma may be specified:
26130
26131 @smallexample @c ada
26132   pragma Pool_64_Default;
26133 @end smallexample
26134
26135 @noindent
26136 Any code compiled in the context of this pragma will by default
26137 use the @code{System.Pool_64} storage pool. This default may be overridden
26138 for a specific access type @code{T} by the representation clause:
26139
26140 @smallexample @c ada
26141    for T'Storage_Pool use System.Pool_32;
26142 @end smallexample
26143
26144 @noindent
26145 Any object whose address may be passed to a subprogram with a
26146 @code{Short_Address} argument, or assigned to a variable of type
26147 @code{Short_Address}, needs to be allocated from this pool.
26148
26149 @node General access types
26150 @subsubsection General access types
26151
26152 @noindent
26153 Objects designated by access values from a
26154 general access type (declared with @code{access all}) are never allocated
26155 from a 64-bit storage pool. Code that uses general access types will
26156 accept objects allocated in either 32-bit or 64-bit address spaces,
26157 but never allocate objects outside the 32-bit address space.
26158 Using general access types ensures maximum compatibility with both
26159 32-bit and 64-bit code.
26160
26161
26162 @node STARLET and other predefined libraries
26163 @subsubsection STARLET and other predefined libraries
26164
26165 @noindent
26166 All code that comes as part of GNAT is 64-bit clean, but the
26167 restrictions given in @ref{Restrictions on use of 64 bit objects},
26168 still apply. Look at the package
26169 specifications to see in which contexts objects allocated
26170 in 64-bit address space are acceptable.
26171
26172 @node Technical details
26173 @subsection Technical details
26174
26175 @noindent
26176 GNAT Pro for Open VMS Integrity takes advantage of the freedom given in the Ada
26177 standard with respect to the type of @code{System.Address}. Previous versions
26178 of GNAT Pro have defined this type as private and implemented it as
26179 a modular type.
26180
26181 In order to allow defining @code{System.Short_Address} as a proper subtype,
26182 and to match the implicit sign extension in parameter passing,
26183 in GNAT Pro for Open VMS Integrity, @code{System.Address} is defined as a
26184 visible (i.e., non-private) integer type.
26185 Standard operations on the type, such as the binary operators ``+'', ``-'',
26186 etc., that take @code{Address} operands and return an @code{Address} result,
26187 have been hidden by declaring these
26188 @code{abstract}, an Ada 95 feature that helps avoid the potential ambiguities
26189 that would otherwise result from overloading.
26190 (Note that, although @code{Address} is a visible integer type,
26191 good programming practice dictates against exploiting the type's
26192 integer properties such as literals, since this will compromise
26193 code portability.)
26194
26195 Defining @code{Address} as a visible integer type helps achieve
26196 maximum compatibility for existing Ada code,
26197 without sacrificing the capabilities of the IA64 architecture.
26198 @end ifset
26199
26200
26201 @c ************************************************
26202 @ifset unw
26203 @node Microsoft Windows Topics
26204 @appendix Microsoft Windows Topics
26205 @cindex Windows NT
26206 @cindex Windows 95
26207 @cindex Windows 98
26208
26209 @noindent
26210 This chapter describes topics that are specific to the Microsoft Windows
26211 platforms (NT, 2000, and XP Professional).
26212
26213 @menu
26214 * Using GNAT on Windows::
26215 * Using a network installation of GNAT::
26216 * CONSOLE and WINDOWS subsystems::
26217 * Temporary Files::
26218 * Mixed-Language Programming on Windows::
26219 * Windows Calling Conventions::
26220 * Introduction to Dynamic Link Libraries (DLLs)::
26221 * Using DLLs with GNAT::
26222 * Building DLLs with GNAT::
26223 * Building DLLs with GNAT Project files::
26224 * Building DLLs with gnatdll::
26225 * GNAT and Windows Resources::
26226 * Debugging a DLL::
26227 * GNAT and COM/DCOM Objects::
26228 @end menu
26229
26230 @node Using GNAT on Windows
26231 @section Using GNAT on Windows
26232
26233 @noindent
26234 One of the strengths of the GNAT technology is that its tool set
26235 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26236 @code{gdb} debugger, etc.) is used in the same way regardless of the
26237 platform.
26238
26239 On Windows this tool set is complemented by a number of Microsoft-specific
26240 tools that have been provided to facilitate interoperability with Windows
26241 when this is required. With these tools:
26242
26243 @itemize @bullet
26244
26245 @item
26246 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26247 subsystems.
26248
26249 @item
26250 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26251 relocatable and non-relocatable DLLs are supported).
26252
26253 @item
26254 You can build Ada DLLs for use in other applications. These applications
26255 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26256 relocatable and non-relocatable Ada DLLs are supported.
26257
26258 @item
26259 You can include Windows resources in your Ada application.
26260
26261 @item
26262 You can use or create COM/DCOM objects.
26263 @end itemize
26264
26265 @noindent
26266 Immediately below are listed all known general GNAT-for-Windows restrictions.
26267 Other restrictions about specific features like Windows Resources and DLLs
26268 are listed in separate sections below.
26269
26270 @itemize @bullet
26271
26272 @item
26273 It is not possible to use @code{GetLastError} and @code{SetLastError}
26274 when tasking, protected records, or exceptions are used. In these
26275 cases, in order to implement Ada semantics, the GNAT run-time system
26276 calls certain Win32 routines that set the last error variable to 0 upon
26277 success. It should be possible to use @code{GetLastError} and
26278 @code{SetLastError} when tasking, protected record, and exception
26279 features are not used, but it is not guaranteed to work.
26280
26281 @item
26282 It is not possible to link against Microsoft libraries except for
26283 import libraries. The library must be built to be compatible with
26284 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
26285 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
26286 not be compatible with the GNAT runtime. Even if the library is
26287 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
26288
26289 @item
26290 When the compilation environment is located on FAT32 drives, users may
26291 experience recompilations of the source files that have not changed if
26292 Daylight Saving Time (DST) state has changed since the last time files
26293 were compiled. NTFS drives do not have this problem.
26294
26295 @item
26296 No components of the GNAT toolset use any entries in the Windows
26297 registry. The only entries that can be created are file associations and
26298 PATH settings, provided the user has chosen to create them at installation
26299 time, as well as some minimal book-keeping information needed to correctly
26300 uninstall or integrate different GNAT products.
26301 @end itemize
26302
26303 @node Using a network installation of GNAT
26304 @section Using a network installation of GNAT
26305
26306 @noindent
26307 Make sure the system on which GNAT is installed is accessible from the
26308 current machine, i.e. the install location is shared over the network.
26309 Shared resources are accessed on Windows by means of UNC paths, which
26310 have the format @code{\\server\sharename\path}
26311
26312 In order to use such a network installation, simply add the UNC path of the
26313 @file{bin} directory of your GNAT installation in front of your PATH. For
26314 example, if GNAT is installed in @file{\GNAT} directory of a share location
26315 called @file{c-drive} on a machine @file{LOKI}, the following command will
26316 make it available:
26317
26318 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26319
26320 Be aware that every compilation using the network installation results in the
26321 transfer of large amounts of data across the network and will likely cause
26322 serious performance penalty.
26323
26324 @node CONSOLE and WINDOWS subsystems
26325 @section CONSOLE and WINDOWS subsystems
26326 @cindex CONSOLE Subsystem
26327 @cindex WINDOWS Subsystem
26328 @cindex -mwindows
26329
26330 @noindent
26331 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26332 (which is the default subsystem) will always create a console when
26333 launching the application. This is not something desirable when the
26334 application has a Windows GUI. To get rid of this console the
26335 application must be using the @code{WINDOWS} subsystem. To do so
26336 the @option{-mwindows} linker option must be specified.
26337
26338 @smallexample
26339 $ gnatmake winprog -largs -mwindows
26340 @end smallexample
26341
26342 @node Temporary Files
26343 @section Temporary Files
26344 @cindex Temporary files
26345
26346 @noindent
26347 It is possible to control where temporary files gets created by setting
26348 the TMP environment variable. The file will be created:
26349
26350 @itemize
26351 @item Under the directory pointed to by the TMP environment variable if
26352 this directory exists.
26353
26354 @item Under c:\temp, if the TMP environment variable is not set (or not
26355 pointing to a directory) and if this directory exists.
26356
26357 @item Under the current working directory otherwise.
26358 @end itemize
26359
26360 @noindent
26361 This allows you to determine exactly where the temporary
26362 file will be created. This is particularly useful in networked
26363 environments where you may not have write access to some
26364 directories.
26365
26366 @node Mixed-Language Programming on Windows
26367 @section Mixed-Language Programming on Windows
26368
26369 @noindent
26370 Developing pure Ada applications on Windows is no different than on
26371 other GNAT-supported platforms. However, when developing or porting an
26372 application that contains a mix of Ada and C/C++, the choice of your
26373 Windows C/C++ development environment conditions your overall
26374 interoperability strategy.
26375
26376 If you use @command{gcc} to compile the non-Ada part of your application,
26377 there are no Windows-specific restrictions that affect the overall
26378 interoperability with your Ada code. If you plan to use
26379 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
26380 the following limitations:
26381
26382 @itemize @bullet
26383 @item
26384 You cannot link your Ada code with an object or library generated with
26385 Microsoft tools if these use the @code{.tls} section (Thread Local
26386 Storage section) since the GNAT linker does not yet support this section.
26387
26388 @item
26389 You cannot link your Ada code with an object or library generated with
26390 Microsoft tools if these use I/O routines other than those provided in
26391 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
26392 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
26393 libraries can cause a conflict with @code{msvcrt.dll} services. For
26394 instance Visual C++ I/O stream routines conflict with those in
26395 @code{msvcrt.dll}.
26396 @end itemize
26397
26398 @noindent
26399 If you do want to use the Microsoft tools for your non-Ada code and hit one
26400 of the above limitations, you have two choices:
26401
26402 @enumerate
26403 @item
26404 Encapsulate your non Ada code in a DLL to be linked with your Ada
26405 application. In this case, use the Microsoft or whatever environment to
26406 build the DLL and use GNAT to build your executable
26407 (@pxref{Using DLLs with GNAT}).
26408
26409 @item
26410 Or you can encapsulate your Ada code in a DLL to be linked with the
26411 other part of your application. In this case, use GNAT to build the DLL
26412 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
26413 environment to build your executable.
26414 @end enumerate
26415
26416 @node Windows Calling Conventions
26417 @section Windows Calling Conventions
26418 @findex Stdcall
26419 @findex APIENTRY
26420
26421 @menu
26422 * C Calling Convention::
26423 * Stdcall Calling Convention::
26424 * DLL Calling Convention::
26425 @end menu
26426
26427 @noindent
26428 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26429 (callee), there are several ways to push @code{G}'s parameters on the
26430 stack and there are several possible scenarios to clean up the stack
26431 upon @code{G}'s return. A calling convention is an agreed upon software
26432 protocol whereby the responsibilities between the caller (@code{F}) and
26433 the callee (@code{G}) are clearly defined. Several calling conventions
26434 are available for Windows:
26435
26436 @itemize @bullet
26437 @item
26438 @code{C} (Microsoft defined)
26439
26440 @item
26441 @code{Stdcall} (Microsoft defined)
26442
26443 @item
26444 @code{DLL} (GNAT specific)
26445 @end itemize
26446
26447 @node C Calling Convention
26448 @subsection @code{C} Calling Convention
26449
26450 @noindent
26451 This is the default calling convention used when interfacing to C/C++
26452 routines compiled with either @command{gcc} or Microsoft Visual C++.
26453
26454 In the @code{C} calling convention subprogram parameters are pushed on the
26455 stack by the caller from right to left. The caller itself is in charge of
26456 cleaning up the stack after the call. In addition, the name of a routine
26457 with @code{C} calling convention is mangled by adding a leading underscore.
26458
26459 The name to use on the Ada side when importing (or exporting) a routine
26460 with @code{C} calling convention is the name of the routine. For
26461 instance the C function:
26462
26463 @smallexample
26464 int get_val (long);
26465 @end smallexample
26466
26467 @noindent
26468 should be imported from Ada as follows:
26469
26470 @smallexample @c ada
26471 @group
26472 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26473 pragma Import (C, Get_Val, External_Name => "get_val");
26474 @end group
26475 @end smallexample
26476
26477 @noindent
26478 Note that in this particular case the @code{External_Name} parameter could
26479 have been omitted since, when missing, this parameter is taken to be the
26480 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26481 is missing, as in the above example, this parameter is set to be the
26482 @code{External_Name} with a leading underscore.
26483
26484 When importing a variable defined in C, you should always use the @code{C}
26485 calling convention unless the object containing the variable is part of a
26486 DLL (in which case you should use the @code{DLL} calling convention,
26487 @pxref{DLL Calling Convention}).
26488
26489 @node Stdcall Calling Convention
26490 @subsection @code{Stdcall} Calling Convention
26491
26492 @noindent
26493 This convention, which was the calling convention used for Pascal
26494 programs, is used by Microsoft for all the routines in the Win32 API for
26495 efficiency reasons. It must be used to import any routine for which this
26496 convention was specified.
26497
26498 In the @code{Stdcall} calling convention subprogram parameters are pushed
26499 on the stack by the caller from right to left. The callee (and not the
26500 caller) is in charge of cleaning the stack on routine exit. In addition,
26501 the name of a routine with @code{Stdcall} calling convention is mangled by
26502 adding a leading underscore (as for the @code{C} calling convention) and a
26503 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
26504 bytes) of the parameters passed to the routine.
26505
26506 The name to use on the Ada side when importing a C routine with a
26507 @code{Stdcall} calling convention is the name of the C routine. The leading
26508 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
26509 the compiler. For instance the Win32 function:
26510
26511 @smallexample
26512 @b{APIENTRY} int get_val (long);
26513 @end smallexample
26514
26515 @noindent
26516 should be imported from Ada as follows:
26517
26518 @smallexample @c ada
26519 @group
26520 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26521 pragma Import (Stdcall, Get_Val);
26522 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26523 @end group
26524 @end smallexample
26525
26526 @noindent
26527 As for the @code{C} calling convention, when the @code{External_Name}
26528 parameter is missing, it is taken to be the name of the Ada entity in lower
26529 case. If instead of writing the above import pragma you write:
26530
26531 @smallexample @c ada
26532 @group
26533 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26534 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26535 @end group
26536 @end smallexample
26537
26538 @noindent
26539 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26540 of specifying the @code{External_Name} parameter you specify the
26541 @code{Link_Name} as in the following example:
26542
26543 @smallexample @c ada
26544 @group
26545 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26546 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26547 @end group
26548 @end smallexample
26549
26550 @noindent
26551 then the imported routine is @code{retrieve_val@@4}, that is, there is no
26552 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
26553 added at the end of the @code{Link_Name} by the compiler.
26554
26555 @noindent
26556 Note, that in some special cases a DLL's entry point name lacks a trailing
26557 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
26558 The @code{gnatdll} tool, which creates the import library for the DLL, is able
26559 to handle those cases (@pxref{Using gnatdll} for the description of
26560 the switches).
26561
26562 @node DLL Calling Convention
26563 @subsection @code{DLL} Calling Convention
26564
26565 @noindent
26566 This convention, which is GNAT-specific, must be used when you want to
26567 import in Ada a variables defined in a DLL. For functions and procedures
26568 this convention is equivalent to the @code{Stdcall} convention. As an
26569 example, if a DLL contains a variable defined as:
26570
26571 @smallexample
26572 int my_var;
26573 @end smallexample
26574
26575 @noindent
26576 then, to access this variable from Ada you should write:
26577
26578 @smallexample @c ada
26579 @group
26580 My_Var : Interfaces.C.int;
26581 pragma Import (DLL, My_Var);
26582 @end group
26583 @end smallexample
26584
26585 The remarks concerning the @code{External_Name} and @code{Link_Name}
26586 parameters given in the previous sections equally apply to the @code{DLL}
26587 calling convention.
26588
26589 @node Introduction to Dynamic Link Libraries (DLLs)
26590 @section Introduction to Dynamic Link Libraries (DLLs)
26591 @findex DLL
26592
26593 @noindent
26594 A Dynamically Linked Library (DLL) is a library that can be shared by
26595 several applications running under Windows. A DLL can contain any number of
26596 routines and variables.
26597
26598 One advantage of DLLs is that you can change and enhance them without
26599 forcing all the applications that depend on them to be relinked or
26600 recompiled. However, you should be aware than all calls to DLL routines are
26601 slower since, as you will understand below, such calls are indirect.
26602
26603 To illustrate the remainder of this section, suppose that an application
26604 wants to use the services of a DLL @file{API.dll}. To use the services
26605 provided by @file{API.dll} you must statically link against the DLL or
26606 an import library which contains a jump table with an entry for each
26607 routine and variable exported by the DLL. In the Microsoft world this
26608 import library is called @file{API.lib}. When using GNAT this import
26609 library is called either @file{libAPI.a} or @file{libapi.a} (names are
26610 case insensitive).
26611
26612 After you have linked your application with the DLL or the import library
26613 and you run your application, here is what happens:
26614
26615 @enumerate
26616 @item
26617 Your application is loaded into memory.
26618
26619 @item
26620 The DLL @file{API.dll} is mapped into the address space of your
26621 application. This means that:
26622
26623 @itemize @bullet
26624 @item
26625 The DLL will use the stack of the calling thread.
26626
26627 @item
26628 The DLL will use the virtual address space of the calling process.
26629
26630 @item
26631 The DLL will allocate memory from the virtual address space of the calling
26632 process.
26633
26634 @item
26635 Handles (pointers) can be safely exchanged between routines in the DLL
26636 routines and routines in the application using the DLL.
26637 @end itemize
26638
26639 @item
26640 The entries in the jump table (from the import library @file{libAPI.a}
26641 or @file{API.lib} or automatically created when linking against a DLL)
26642 which is part of your application are initialized with the addresses
26643 of the routines and variables in @file{API.dll}.
26644
26645 @item
26646 If present in @file{API.dll}, routines @code{DllMain} or
26647 @code{DllMainCRTStartup} are invoked. These routines typically contain
26648 the initialization code needed for the well-being of the routines and
26649 variables exported by the DLL.
26650 @end enumerate
26651
26652 @noindent
26653 There is an additional point which is worth mentioning. In the Windows
26654 world there are two kind of DLLs: relocatable and non-relocatable
26655 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
26656 in the target application address space. If the addresses of two
26657 non-relocatable DLLs overlap and these happen to be used by the same
26658 application, a conflict will occur and the application will run
26659 incorrectly. Hence, when possible, it is always preferable to use and
26660 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
26661 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
26662 User's Guide) removes the debugging symbols from the DLL but the DLL can
26663 still be relocated.
26664
26665 As a side note, an interesting difference between Microsoft DLLs and
26666 Unix shared libraries, is the fact that on most Unix systems all public
26667 routines are exported by default in a Unix shared library, while under
26668 Windows it is possible (but not required) to list exported routines in
26669 a definition file (@pxref{The Definition File}).
26670
26671 @node Using DLLs with GNAT
26672 @section Using DLLs with GNAT
26673
26674 @menu
26675 * Creating an Ada Spec for the DLL Services::
26676 * Creating an Import Library::
26677 @end menu
26678
26679 @noindent
26680 To use the services of a DLL, say @file{API.dll}, in your Ada application
26681 you must have:
26682
26683 @enumerate
26684 @item
26685 The Ada spec for the routines and/or variables you want to access in
26686 @file{API.dll}. If not available this Ada spec must be built from the C/C++
26687 header files provided with the DLL.
26688
26689 @item
26690 The import library (@file{libAPI.a} or @file{API.lib}). As previously
26691 mentioned an import library is a statically linked library containing the
26692 import table which will be filled at load time to point to the actual
26693 @file{API.dll} routines. Sometimes you don't have an import library for the
26694 DLL you want to use. The following sections will explain how to build
26695 one. Note that this is optional.
26696
26697 @item
26698 The actual DLL, @file{API.dll}.
26699 @end enumerate
26700
26701 @noindent
26702 Once you have all the above, to compile an Ada application that uses the
26703 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
26704 you simply issue the command
26705
26706 @smallexample
26707 $ gnatmake my_ada_app -largs -lAPI
26708 @end smallexample
26709
26710 @noindent
26711 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
26712 tells the GNAT linker to look first for a library named @file{API.lib}
26713 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
26714 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
26715 contains the following pragma
26716
26717 @smallexample @c ada
26718 pragma Linker_Options ("-lAPI");
26719 @end smallexample
26720
26721 @noindent
26722 you do not have to add @option{-largs -lAPI} at the end of the
26723 @command{gnatmake} command.
26724
26725 If any one of the items above is missing you will have to create it
26726 yourself. The following sections explain how to do so using as an
26727 example a fictitious DLL called @file{API.dll}.
26728
26729 @node Creating an Ada Spec for the DLL Services
26730 @subsection Creating an Ada Spec for the DLL Services
26731
26732 @noindent
26733 A DLL typically comes with a C/C++ header file which provides the
26734 definitions of the routines and variables exported by the DLL. The Ada
26735 equivalent of this header file is a package spec that contains definitions
26736 for the imported entities. If the DLL you intend to use does not come with
26737 an Ada spec you have to generate one such spec yourself. For example if
26738 the header file of @file{API.dll} is a file @file{api.h} containing the
26739 following two definitions:
26740
26741 @smallexample
26742 @group
26743 @cartouche
26744 int some_var;
26745 int get (char *);
26746 @end cartouche
26747 @end group
26748 @end smallexample
26749
26750 @noindent
26751 then the equivalent Ada spec could be:
26752
26753 @smallexample @c ada
26754 @group
26755 @cartouche
26756 with Interfaces.C.Strings;
26757 package API is
26758    use Interfaces;
26759
26760    Some_Var : C.int;
26761    function Get (Str : C.Strings.Chars_Ptr) return C.int;
26762
26763 private
26764    pragma Import (C, Get);
26765    pragma Import (DLL, Some_Var);
26766 end API;
26767 @end cartouche
26768 @end group
26769 @end smallexample
26770
26771 @noindent
26772 Note that a variable is @strong{always imported with a DLL convention}. A
26773 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
26774 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
26775 (@pxref{Windows Calling Conventions}).
26776
26777 @node Creating an Import Library
26778 @subsection Creating an Import Library
26779 @cindex Import library
26780
26781 @menu
26782 * The Definition File::
26783 * GNAT-Style Import Library::
26784 * Microsoft-Style Import Library::
26785 @end menu
26786
26787 @noindent
26788 If a Microsoft-style import library @file{API.lib} or a GNAT-style
26789 import library @file{libAPI.a} is available with @file{API.dll} you
26790 can skip this section. You can also skip this section if
26791 @file{API.dll} is built with GNU tools as in this case it is possible
26792 to link directly against the DLL. Otherwise read on.
26793
26794 @node The Definition File
26795 @subsubsection The Definition File
26796 @cindex Definition file
26797 @findex .def
26798
26799 @noindent
26800 As previously mentioned, and unlike Unix systems, the list of symbols
26801 that are exported from a DLL must be provided explicitly in Windows.
26802 The main goal of a definition file is precisely that: list the symbols
26803 exported by a DLL. A definition file (usually a file with a @code{.def}
26804 suffix) has the following structure:
26805
26806 @smallexample
26807 @group
26808 @cartouche
26809 [LIBRARY @i{name}]
26810 [DESCRIPTION @i{string}]
26811 EXPORTS
26812    @i{symbol1}
26813    @i{symbol2}
26814    ...
26815 @end cartouche
26816 @end group
26817 @end smallexample
26818
26819 @table @code
26820 @item LIBRARY @i{name}
26821 This section, which is optional, gives the name of the DLL.
26822
26823 @item DESCRIPTION @i{string}
26824 This section, which is optional, gives a description string that will be
26825 embedded in the import library.
26826
26827 @item EXPORTS
26828 This section gives the list of exported symbols (procedures, functions or
26829 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
26830 section of @file{API.def} looks like:
26831
26832 @smallexample
26833 @group
26834 @cartouche
26835 EXPORTS
26836    some_var
26837    get
26838 @end cartouche
26839 @end group
26840 @end smallexample
26841 @end table
26842
26843 @noindent
26844 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
26845 (@pxref{Windows Calling Conventions}) for a Stdcall
26846 calling convention function in the exported symbols list.
26847
26848 @noindent
26849 There can actually be other sections in a definition file, but these
26850 sections are not relevant to the discussion at hand.
26851
26852 @node GNAT-Style Import Library
26853 @subsubsection GNAT-Style Import Library
26854
26855 @noindent
26856 To create a static import library from @file{API.dll} with the GNAT tools
26857 you should proceed as follows:
26858
26859 @enumerate
26860 @item
26861 Create the definition file @file{API.def} (@pxref{The Definition File}).
26862 For that use the @code{dll2def} tool as follows:
26863
26864 @smallexample
26865 $ dll2def API.dll > API.def
26866 @end smallexample
26867
26868 @noindent
26869 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
26870 to standard output the list of entry points in the DLL. Note that if
26871 some routines in the DLL have the @code{Stdcall} convention
26872 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
26873 suffix then you'll have to edit @file{api.def} to add it, and specify
26874 @code{-k} to @code{gnatdll} when creating the import library.
26875
26876 @noindent
26877 Here are some hints to find the right @code{@@}@i{nn} suffix.
26878
26879 @enumerate
26880 @item
26881 If you have the Microsoft import library (.lib), it is possible to get
26882 the right symbols by using Microsoft @code{dumpbin} tool (see the
26883 corresponding Microsoft documentation for further details).
26884
26885 @smallexample
26886 $ dumpbin /exports api.lib
26887 @end smallexample
26888
26889 @item
26890 If you have a message about a missing symbol at link time the compiler
26891 tells you what symbol is expected. You just have to go back to the
26892 definition file and add the right suffix.
26893 @end enumerate
26894
26895 @item
26896 Build the import library @code{libAPI.a}, using @code{gnatdll}
26897 (@pxref{Using gnatdll}) as follows:
26898
26899 @smallexample
26900 $ gnatdll -e API.def -d API.dll
26901 @end smallexample
26902
26903 @noindent
26904 @code{gnatdll} takes as input a definition file @file{API.def} and the
26905 name of the DLL containing the services listed in the definition file
26906 @file{API.dll}. The name of the static import library generated is
26907 computed from the name of the definition file as follows: if the
26908 definition file name is @i{xyz}@code{.def}, the import library name will
26909 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
26910 @option{-e} could have been removed because the name of the definition
26911 file (before the ``@code{.def}'' suffix) is the same as the name of the
26912 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
26913 @end enumerate
26914
26915 @node Microsoft-Style Import Library
26916 @subsubsection Microsoft-Style Import Library
26917
26918 @noindent
26919 With GNAT you can either use a GNAT-style or Microsoft-style import
26920 library. A Microsoft import library is needed only if you plan to make an
26921 Ada DLL available to applications developed with Microsoft
26922 tools (@pxref{Mixed-Language Programming on Windows}).
26923
26924 To create a Microsoft-style import library for @file{API.dll} you
26925 should proceed as follows:
26926
26927 @enumerate
26928 @item
26929 Create the definition file @file{API.def} from the DLL. For this use either
26930 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
26931 tool (see the corresponding Microsoft documentation for further details).
26932
26933 @item
26934 Build the actual import library using Microsoft's @code{lib} utility:
26935
26936 @smallexample
26937 $ lib -machine:IX86 -def:API.def -out:API.lib
26938 @end smallexample
26939
26940 @noindent
26941 If you use the above command the definition file @file{API.def} must
26942 contain a line giving the name of the DLL:
26943
26944 @smallexample
26945 LIBRARY      "API"
26946 @end smallexample
26947
26948 @noindent
26949 See the Microsoft documentation for further details about the usage of
26950 @code{lib}.
26951 @end enumerate
26952
26953 @node Building DLLs with GNAT
26954 @section Building DLLs with GNAT
26955 @cindex DLLs, building
26956
26957 @noindent
26958 This section explain how to build DLLs using the GNAT built-in DLL
26959 support. With the following procedure it is straight forward to build
26960 and use DLLs with GNAT.
26961
26962 @enumerate
26963
26964 @item building object files
26965
26966 The first step is to build all objects files that are to be included
26967 into the DLL. This is done by using the standard @command{gnatmake} tool.
26968
26969 @item building the DLL
26970
26971 To build the DLL you must use @command{gcc}'s @code{-shared}
26972 option. It is quite simple to use this method:
26973
26974 @smallexample
26975 $ gcc -shared -o api.dll obj1.o obj2.o ...
26976 @end smallexample
26977
26978 It is important to note that in this case all symbols found in the
26979 object files are automatically exported. It is possible to restrict
26980 the set of symbols to export by passing to @command{gcc} a definition
26981 file, @pxref{The Definition File}. For example:
26982
26983 @smallexample
26984 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
26985 @end smallexample
26986
26987 If you use a definition file you must export the elaboration procedures
26988 for every package that required one. Elaboration procedures are named
26989 using the package name followed by "_E".
26990
26991 @item preparing DLL to be used
26992
26993 For the DLL to be used by client programs the bodies must be hidden
26994 from it and the .ali set with read-only attribute. This is very important
26995 otherwise GNAT will recompile all packages and will not actually use
26996 the code in the DLL. For example:
26997
26998 @smallexample
26999 $ mkdir apilib
27000 $ copy *.ads *.ali api.dll apilib
27001 $ attrib +R apilib\*.ali
27002 @end smallexample
27003
27004 @end enumerate
27005
27006 At this point it is possible to use the DLL by directly linking
27007 against it. Note that you must use the GNAT shared runtime when using
27008 GNAT shared libraries. This is achieved by using @code{-shared} binder's
27009 option.
27010
27011 @smallexample
27012 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27013 @end smallexample
27014
27015 @node Building DLLs with GNAT Project files
27016 @section Building DLLs with GNAT Project files
27017 @cindex DLLs, building
27018
27019 @noindent
27020 There is nothing specific to Windows in this area. @pxref{Library Projects}.
27021
27022 @node Building DLLs with gnatdll
27023 @section Building DLLs with gnatdll
27024 @cindex DLLs, building
27025
27026 @menu
27027 * Limitations When Using Ada DLLs from Ada::
27028 * Exporting Ada Entities::
27029 * Ada DLLs and Elaboration::
27030 * Ada DLLs and Finalization::
27031 * Creating a Spec for Ada DLLs::
27032 * Creating the Definition File::
27033 * Using gnatdll::
27034 @end menu
27035
27036 @noindent
27037 Note that it is prefered to use the built-in GNAT DLL support
27038 (@pxref{Building DLLs with GNAT}) or GNAT Project files
27039 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
27040
27041 This section explains how to build DLLs containing Ada code using
27042 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27043 remainder of this section.
27044
27045 The steps required to build an Ada DLL that is to be used by Ada as well as
27046 non-Ada applications are as follows:
27047
27048 @enumerate
27049 @item
27050 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27051 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27052 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27053 skip this step if you plan to use the Ada DLL only from Ada applications.
27054
27055 @item
27056 Your Ada code must export an initialization routine which calls the routine
27057 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27058 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27059 routine exported by the Ada DLL must be invoked by the clients of the DLL
27060 to initialize the DLL.
27061
27062 @item
27063 When useful, the DLL should also export a finalization routine which calls
27064 routine @code{adafinal} generated by @command{gnatbind} to perform the
27065 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27066 The finalization routine exported by the Ada DLL must be invoked by the
27067 clients of the DLL when the DLL services are no further needed.
27068
27069 @item
27070 You must provide a spec for the services exported by the Ada DLL in each
27071 of the programming languages to which you plan to make the DLL available.
27072
27073 @item
27074 You must provide a definition file listing the exported entities
27075 (@pxref{The Definition File}).
27076
27077 @item
27078 Finally you must use @code{gnatdll} to produce the DLL and the import
27079 library (@pxref{Using gnatdll}).
27080 @end enumerate
27081
27082 @noindent
27083 Note that a relocatable DLL stripped using the @code{strip} binutils
27084 tool will not be relocatable anymore. To build a DLL without debug
27085 information pass @code{-largs -s} to @code{gnatdll}.
27086
27087 @node Limitations When Using Ada DLLs from Ada
27088 @subsection Limitations When Using Ada DLLs from Ada
27089
27090 @noindent
27091 When using Ada DLLs from Ada applications there is a limitation users
27092 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27093 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27094 each Ada DLL includes the services of the GNAT run time that are necessary
27095 to the Ada code inside the DLL. As a result, when an Ada program uses an
27096 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27097 one in the main program.
27098
27099 It is therefore not possible to exchange GNAT run-time objects between the
27100 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27101 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
27102 types, etc.
27103
27104 It is completely safe to exchange plain elementary, array or record types,
27105 Windows object handles, etc.
27106
27107 @node Exporting Ada Entities
27108 @subsection Exporting Ada Entities
27109 @cindex Export table
27110
27111 @noindent
27112 Building a DLL is a way to encapsulate a set of services usable from any
27113 application. As a result, the Ada entities exported by a DLL should be
27114 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27115 any Ada name mangling. Please note that the @code{Stdcall} convention
27116 should only be used for subprograms, not for variables. As an example here
27117 is an Ada package @code{API}, spec and body, exporting two procedures, a
27118 function, and a variable:
27119
27120 @smallexample @c ada
27121 @group
27122 @cartouche
27123 with Interfaces.C; use Interfaces;
27124 package API is
27125    Count : C.int := 0;
27126    function Factorial (Val : C.int) return C.int;
27127
27128    procedure Initialize_API;
27129    procedure Finalize_API;
27130    --  Initialization & Finalization routines. More in the next section.
27131 private
27132    pragma Export (C, Initialize_API);
27133    pragma Export (C, Finalize_API);
27134    pragma Export (C, Count);
27135    pragma Export (C, Factorial);
27136 end API;
27137 @end cartouche
27138 @end group
27139 @end smallexample
27140
27141 @smallexample @c ada
27142 @group
27143 @cartouche
27144 package body API is
27145    function Factorial (Val : C.int) return C.int is
27146       Fact : C.int := 1;
27147    begin
27148       Count := Count + 1;
27149       for K in 1 .. Val loop
27150          Fact := Fact * K;
27151       end loop;
27152       return Fact;
27153    end Factorial;
27154
27155    procedure Initialize_API is
27156       procedure Adainit;
27157       pragma Import (C, Adainit);
27158    begin
27159       Adainit;
27160    end Initialize_API;
27161
27162    procedure Finalize_API is
27163       procedure Adafinal;
27164       pragma Import (C, Adafinal);
27165    begin
27166       Adafinal;
27167    end Finalize_API;
27168 end API;
27169 @end cartouche
27170 @end group
27171 @end smallexample
27172
27173 @noindent
27174 If the Ada DLL you are building will only be used by Ada applications
27175 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27176 convention. As an example, the previous package could be written as
27177 follows:
27178
27179 @smallexample @c ada
27180 @group
27181 @cartouche
27182 package API is
27183    Count : Integer := 0;
27184    function Factorial (Val : Integer) return Integer;
27185
27186    procedure Initialize_API;
27187    procedure Finalize_API;
27188    --  Initialization and Finalization routines.
27189 end API;
27190 @end cartouche
27191 @end group
27192 @end smallexample
27193
27194 @smallexample @c ada
27195 @group
27196 @cartouche
27197 package body API is
27198    function Factorial (Val : Integer) return Integer is
27199       Fact : Integer := 1;
27200    begin
27201       Count := Count + 1;
27202       for K in 1 .. Val loop
27203          Fact := Fact * K;
27204       end loop;
27205       return Fact;
27206    end Factorial;
27207
27208    ...
27209    --  The remainder of this package body is unchanged.
27210 end API;
27211 @end cartouche
27212 @end group
27213 @end smallexample
27214
27215 @noindent
27216 Note that if you do not export the Ada entities with a @code{C} or
27217 @code{Stdcall} convention you will have to provide the mangled Ada names
27218 in the definition file of the Ada DLL
27219 (@pxref{Creating the Definition File}).
27220
27221 @node Ada DLLs and Elaboration
27222 @subsection Ada DLLs and Elaboration
27223 @cindex DLLs and elaboration
27224
27225 @noindent
27226 The DLL that you are building contains your Ada code as well as all the
27227 routines in the Ada library that are needed by it. The first thing a
27228 user of your DLL must do is elaborate the Ada code
27229 (@pxref{Elaboration Order Handling in GNAT}).
27230
27231 To achieve this you must export an initialization routine
27232 (@code{Initialize_API} in the previous example), which must be invoked
27233 before using any of the DLL services. This elaboration routine must call
27234 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27235 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27236 @code{Initialize_Api} for an example. Note that the GNAT binder is
27237 automatically invoked during the DLL build process by the @code{gnatdll}
27238 tool (@pxref{Using gnatdll}).
27239
27240 When a DLL is loaded, Windows systematically invokes a routine called
27241 @code{DllMain}. It would therefore be possible to call @code{adainit}
27242 directly from @code{DllMain} without having to provide an explicit
27243 initialization routine. Unfortunately, it is not possible to call
27244 @code{adainit} from the @code{DllMain} if your program has library level
27245 tasks because access to the @code{DllMain} entry point is serialized by
27246 the system (that is, only a single thread can execute ``through'' it at a
27247 time), which means that the GNAT run time will deadlock waiting for the
27248 newly created task to complete its initialization.
27249
27250 @node Ada DLLs and Finalization
27251 @subsection Ada DLLs and Finalization
27252 @cindex DLLs and finalization
27253
27254 @noindent
27255 When the services of an Ada DLL are no longer needed, the client code should
27256 invoke the DLL finalization routine, if available. The DLL finalization
27257 routine is in charge of releasing all resources acquired by the DLL. In the
27258 case of the Ada code contained in the DLL, this is achieved by calling
27259 routine @code{adafinal} generated by the GNAT binder
27260 (@pxref{Binding with Non-Ada Main Programs}).
27261 See the body of @code{Finalize_Api} for an
27262 example. As already pointed out the GNAT binder is automatically invoked
27263 during the DLL build process by the @code{gnatdll} tool
27264 (@pxref{Using gnatdll}).
27265
27266 @node Creating a Spec for Ada DLLs
27267 @subsection Creating a Spec for Ada DLLs
27268
27269 @noindent
27270 To use the services exported by the Ada DLL from another programming
27271 language (e.g. C), you have to translate the specs of the exported Ada
27272 entities in that language. For instance in the case of @code{API.dll},
27273 the corresponding C header file could look like:
27274
27275 @smallexample
27276 @group
27277 @cartouche
27278 extern int *_imp__count;
27279 #define count (*_imp__count)
27280 int factorial (int);
27281 @end cartouche
27282 @end group
27283 @end smallexample
27284
27285 @noindent
27286 It is important to understand that when building an Ada DLL to be used by
27287 other Ada applications, you need two different specs for the packages
27288 contained in the DLL: one for building the DLL and the other for using
27289 the DLL. This is because the @code{DLL} calling convention is needed to
27290 use a variable defined in a DLL, but when building the DLL, the variable
27291 must have either the @code{Ada} or @code{C} calling convention. As an
27292 example consider a DLL comprising the following package @code{API}:
27293
27294 @smallexample @c ada
27295 @group
27296 @cartouche
27297 package API is
27298    Count : Integer := 0;
27299    ...
27300    --  Remainder of the package omitted.
27301 end API;
27302 @end cartouche
27303 @end group
27304 @end smallexample
27305
27306 @noindent
27307 After producing a DLL containing package @code{API}, the spec that
27308 must be used to import @code{API.Count} from Ada code outside of the
27309 DLL is:
27310
27311 @smallexample @c ada
27312 @group
27313 @cartouche
27314 package API is
27315    Count : Integer;
27316    pragma Import (DLL, Count);
27317 end API;
27318 @end cartouche
27319 @end group
27320 @end smallexample
27321
27322 @node Creating the Definition File
27323 @subsection Creating the Definition File
27324
27325 @noindent
27326 The definition file is the last file needed to build the DLL. It lists
27327 the exported symbols. As an example, the definition file for a DLL
27328 containing only package @code{API} (where all the entities are exported
27329 with a @code{C} calling convention) is:
27330
27331 @smallexample
27332 @group
27333 @cartouche
27334 EXPORTS
27335     count
27336     factorial
27337     finalize_api
27338     initialize_api
27339 @end cartouche
27340 @end group
27341 @end smallexample
27342
27343 @noindent
27344 If the @code{C} calling convention is missing from package @code{API},
27345 then the definition file contains the mangled Ada names of the above
27346 entities, which in this case are:
27347
27348 @smallexample
27349 @group
27350 @cartouche
27351 EXPORTS
27352     api__count
27353     api__factorial
27354     api__finalize_api
27355     api__initialize_api
27356 @end cartouche
27357 @end group
27358 @end smallexample
27359
27360 @node Using gnatdll
27361 @subsection Using @code{gnatdll}
27362 @findex gnatdll
27363
27364 @menu
27365 * gnatdll Example::
27366 * gnatdll behind the Scenes::
27367 * Using dlltool::
27368 @end menu
27369
27370 @noindent
27371 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
27372 and non-Ada sources that make up your DLL have been compiled.
27373 @code{gnatdll} is actually in charge of two distinct tasks: build the
27374 static import library for the DLL and the actual DLL. The form of the
27375 @code{gnatdll} command is
27376
27377 @smallexample
27378 @cartouche
27379 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
27380 @end cartouche
27381 @end smallexample
27382
27383 @noindent
27384 where @i{list-of-files} is a list of ALI and object files. The object
27385 file list must be the exact list of objects corresponding to the non-Ada
27386 sources whose services are to be included in the DLL. The ALI file list
27387 must be the exact list of ALI files for the corresponding Ada sources
27388 whose services are to be included in the DLL. If @i{list-of-files} is
27389 missing, only the static import library is generated.
27390
27391 @noindent
27392 You may specify any of the following switches to @code{gnatdll}:
27393
27394 @table @code
27395 @item -a[@var{address}]
27396 @cindex @option{-a} (@code{gnatdll})
27397 Build a non-relocatable DLL at @var{address}. If @var{address} is not
27398 specified the default address @var{0x11000000} will be used. By default,
27399 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
27400 advise the reader to build relocatable DLL.
27401
27402 @item -b @var{address}
27403 @cindex @option{-b} (@code{gnatdll})
27404 Set the relocatable DLL base address. By default the address is
27405 @var{0x11000000}.
27406
27407 @item -bargs @var{opts}
27408 @cindex @option{-bargs} (@code{gnatdll})
27409 Binder options. Pass @var{opts} to the binder.
27410
27411 @item -d @var{dllfile}
27412 @cindex @option{-d} (@code{gnatdll})
27413 @var{dllfile} is the name of the DLL. This switch must be present for
27414 @code{gnatdll} to do anything. The name of the generated import library is
27415 obtained algorithmically from @var{dllfile} as shown in the following
27416 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
27417 @code{libxyz.a}. The name of the definition file to use (if not specified
27418 by option @option{-e}) is obtained algorithmically from @var{dllfile}
27419 as shown in the following example:
27420 if @var{dllfile} is @code{xyz.dll}, the definition
27421 file used is @code{xyz.def}.
27422
27423 @item -e @var{deffile}
27424 @cindex @option{-e} (@code{gnatdll})
27425 @var{deffile} is the name of the definition file.
27426
27427 @item -g
27428 @cindex @option{-g} (@code{gnatdll})
27429 Generate debugging information. This information is stored in the object
27430 file and copied from there to the final DLL file by the linker,
27431 where it can be read by the debugger. You must use the
27432 @option{-g} switch if you plan on using the debugger or the symbolic
27433 stack traceback.
27434
27435 @item -h
27436 @cindex @option{-h} (@code{gnatdll})
27437 Help mode. Displays @code{gnatdll} switch usage information.
27438
27439 @item -Idir
27440 @cindex @option{-I} (@code{gnatdll})
27441 Direct @code{gnatdll} to search the @var{dir} directory for source and
27442 object files needed to build the DLL.
27443 (@pxref{Search Paths and the Run-Time Library (RTL)}).
27444
27445 @item -k
27446 @cindex @option{-k} (@code{gnatdll})
27447 Removes the @code{@@}@i{nn} suffix from the import library's exported
27448 names, but keeps them for the link names. You must specify this
27449 option if you want to use a @code{Stdcall} function in a DLL for which
27450 the @code{@@}@i{nn} suffix has been removed. This is the case for most
27451 of the Windows NT DLL for example. This option has no effect when
27452 @option{-n} option is specified.
27453
27454 @item -l @var{file}
27455 @cindex @option{-l} (@code{gnatdll})
27456 The list of ALI and object files used to build the DLL are listed in
27457 @var{file}, instead of being given in the command line. Each line in
27458 @var{file} contains the name of an ALI or object file.
27459
27460 @item -n
27461 @cindex @option{-n} (@code{gnatdll})
27462 No Import. Do not create the import library.
27463
27464 @item -q
27465 @cindex @option{-q} (@code{gnatdll})
27466 Quiet mode. Do not display unnecessary messages.
27467
27468 @item -v
27469 @cindex @option{-v} (@code{gnatdll})
27470 Verbose mode. Display extra information.
27471
27472 @item -largs @var{opts}
27473 @cindex @option{-largs} (@code{gnatdll})
27474 Linker options. Pass @var{opts} to the linker.
27475 @end table
27476
27477 @node gnatdll Example
27478 @subsubsection @code{gnatdll} Example
27479
27480 @noindent
27481 As an example the command to build a relocatable DLL from @file{api.adb}
27482 once @file{api.adb} has been compiled and @file{api.def} created is
27483
27484 @smallexample
27485 $ gnatdll -d api.dll api.ali
27486 @end smallexample
27487
27488 @noindent
27489 The above command creates two files: @file{libapi.a} (the import
27490 library) and @file{api.dll} (the actual DLL). If you want to create
27491 only the DLL, just type:
27492
27493 @smallexample
27494 $ gnatdll -d api.dll -n api.ali
27495 @end smallexample
27496
27497 @noindent
27498 Alternatively if you want to create just the import library, type:
27499
27500 @smallexample
27501 $ gnatdll -d api.dll
27502 @end smallexample
27503
27504 @node gnatdll behind the Scenes
27505 @subsubsection @code{gnatdll} behind the Scenes
27506
27507 @noindent
27508 This section details the steps involved in creating a DLL. @code{gnatdll}
27509 does these steps for you. Unless you are interested in understanding what
27510 goes on behind the scenes, you should skip this section.
27511
27512 We use the previous example of a DLL containing the Ada package @code{API},
27513 to illustrate the steps necessary to build a DLL. The starting point is a
27514 set of objects that will make up the DLL and the corresponding ALI
27515 files. In the case of this example this means that @file{api.o} and
27516 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27517 the following:
27518
27519 @enumerate
27520 @item
27521 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27522 the information necessary to generate relocation information for the
27523 DLL.
27524
27525 @smallexample
27526 @group
27527 $ gnatbind -n api
27528 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27529 @end group
27530 @end smallexample
27531
27532 @noindent
27533 In addition to the base file, the @command{gnatlink} command generates an
27534 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27535 asks @command{gnatlink} to generate the routines @code{DllMain} and
27536 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27537 is loaded into memory.
27538
27539 @item
27540 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27541 export table (@file{api.exp}). The export table contains the relocation
27542 information in a form which can be used during the final link to ensure
27543 that the Windows loader is able to place the DLL anywhere in memory.
27544
27545 @smallexample
27546 @group
27547 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27548           --output-exp api.exp
27549 @end group
27550 @end smallexample
27551
27552 @item
27553 @code{gnatdll} builds the base file using the new export table. Note that
27554 @command{gnatbind} must be called once again since the binder generated file
27555 has been deleted during the previous call to @command{gnatlink}.
27556
27557 @smallexample
27558 @group
27559 $ gnatbind -n api
27560 $ gnatlink api -o api.jnk api.exp -mdll
27561       -Wl,--base-file,api.base
27562 @end group
27563 @end smallexample
27564
27565 @item
27566 @code{gnatdll} builds the new export table using the new base file and
27567 generates the DLL import library @file{libAPI.a}.
27568
27569 @smallexample
27570 @group
27571 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27572           --output-exp api.exp --output-lib libAPI.a
27573 @end group
27574 @end smallexample
27575
27576 @item
27577 Finally @code{gnatdll} builds the relocatable DLL using the final export
27578 table.
27579
27580 @smallexample
27581 @group
27582 $ gnatbind -n api
27583 $ gnatlink api api.exp -o api.dll -mdll
27584 @end group
27585 @end smallexample
27586 @end enumerate
27587
27588 @node Using dlltool
27589 @subsubsection Using @code{dlltool}
27590
27591 @noindent
27592 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27593 DLLs and static import libraries. This section summarizes the most
27594 common @code{dlltool} switches. The form of the @code{dlltool} command
27595 is
27596
27597 @smallexample
27598 $ dlltool [@var{switches}]
27599 @end smallexample
27600
27601 @noindent
27602 @code{dlltool} switches include:
27603
27604 @table @option
27605 @item --base-file @var{basefile}
27606 @cindex @option{--base-file} (@command{dlltool})
27607 Read the base file @var{basefile} generated by the linker. This switch
27608 is used to create a relocatable DLL.
27609
27610 @item --def @var{deffile}
27611 @cindex @option{--def} (@command{dlltool})
27612 Read the definition file.
27613
27614 @item --dllname @var{name}
27615 @cindex @option{--dllname} (@command{dlltool})
27616 Gives the name of the DLL. This switch is used to embed the name of the
27617 DLL in the static import library generated by @code{dlltool} with switch
27618 @option{--output-lib}.
27619
27620 @item -k
27621 @cindex @option{-k} (@command{dlltool})
27622 Kill @code{@@}@i{nn} from exported names
27623 (@pxref{Windows Calling Conventions}
27624 for a discussion about @code{Stdcall}-style symbols.
27625
27626 @item --help
27627 @cindex @option{--help} (@command{dlltool})
27628 Prints the @code{dlltool} switches with a concise description.
27629
27630 @item --output-exp @var{exportfile}
27631 @cindex @option{--output-exp} (@command{dlltool})
27632 Generate an export file @var{exportfile}. The export file contains the
27633 export table (list of symbols in the DLL) and is used to create the DLL.
27634
27635 @item --output-lib @i{libfile}
27636 @cindex @option{--output-lib} (@command{dlltool})
27637 Generate a static import library @var{libfile}.
27638
27639 @item -v
27640 @cindex @option{-v} (@command{dlltool})
27641 Verbose mode.
27642
27643 @item --as @i{assembler-name}
27644 @cindex @option{--as} (@command{dlltool})
27645 Use @i{assembler-name} as the assembler. The default is @code{as}.
27646 @end table
27647
27648 @node GNAT and Windows Resources
27649 @section GNAT and Windows Resources
27650 @cindex Resources, windows
27651
27652 @menu
27653 * Building Resources::
27654 * Compiling Resources::
27655 * Using Resources::
27656 @end menu
27657
27658 @noindent
27659 Resources are an easy way to add Windows specific objects to your
27660 application. The objects that can be added as resources include:
27661
27662 @itemize @bullet
27663 @item
27664 menus
27665
27666 @item
27667 accelerators
27668
27669 @item
27670 dialog boxes
27671
27672 @item
27673 string tables
27674
27675 @item
27676 bitmaps
27677
27678 @item
27679 cursors
27680
27681 @item
27682 icons
27683
27684 @item
27685 fonts
27686 @end itemize
27687
27688 @noindent
27689 This section explains how to build, compile and use resources.
27690
27691 @node Building Resources
27692 @subsection Building Resources
27693 @cindex Resources, building
27694
27695 @noindent
27696 A resource file is an ASCII file. By convention resource files have an
27697 @file{.rc} extension.
27698 The easiest way to build a resource file is to use Microsoft tools
27699 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
27700 @code{dlgedit.exe} to build dialogs.
27701 It is always possible to build an @file{.rc} file yourself by writing a
27702 resource script.
27703
27704 It is not our objective to explain how to write a resource file. A
27705 complete description of the resource script language can be found in the
27706 Microsoft documentation.
27707
27708 @node Compiling Resources
27709 @subsection Compiling Resources
27710 @findex rc
27711 @findex windres
27712 @cindex Resources, compiling
27713
27714 @noindent
27715 This section describes how to build a GNAT-compatible (COFF) object file
27716 containing the resources. This is done using the Resource Compiler
27717 @code{windres} as follows:
27718
27719 @smallexample
27720 $ windres -i myres.rc -o myres.o
27721 @end smallexample
27722
27723 @noindent
27724 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
27725 file. You can specify an alternate preprocessor (usually named
27726 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
27727 parameter. A list of all possible options may be obtained by entering
27728 the command @code{windres} @option{--help}.
27729
27730 It is also possible to use the Microsoft resource compiler @code{rc.exe}
27731 to produce a @file{.res} file (binary resource file). See the
27732 corresponding Microsoft documentation for further details. In this case
27733 you need to use @code{windres} to translate the @file{.res} file to a
27734 GNAT-compatible object file as follows:
27735
27736 @smallexample
27737 $ windres -i myres.res -o myres.o
27738 @end smallexample
27739
27740 @node Using Resources
27741 @subsection Using Resources
27742 @cindex Resources, using
27743
27744 @noindent
27745 To include the resource file in your program just add the
27746 GNAT-compatible object file for the resource(s) to the linker
27747 arguments. With @command{gnatmake} this is done by using the @option{-largs}
27748 option:
27749
27750 @smallexample
27751 $ gnatmake myprog -largs myres.o
27752 @end smallexample
27753
27754 @node Debugging a DLL
27755 @section Debugging a DLL
27756 @cindex DLL debugging
27757
27758 @menu
27759 * Program and DLL Both Built with GCC/GNAT::
27760 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
27761 @end menu
27762
27763 @noindent
27764 Debugging a DLL is similar to debugging a standard program. But
27765 we have to deal with two different executable parts: the DLL and the
27766 program that uses it. We have the following four possibilities:
27767
27768 @enumerate 1
27769 @item
27770 The program and the DLL are built with @code{GCC/GNAT}.
27771 @item
27772 The program is built with foreign tools and the DLL is built with
27773 @code{GCC/GNAT}.
27774 @item
27775 The program is built with @code{GCC/GNAT} and the DLL is built with
27776 foreign tools.
27777 @item
27778 @end enumerate
27779
27780 @noindent
27781 In this section we address only cases one and two above.
27782 There is no point in trying to debug
27783 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
27784 information in it. To do so you must use a debugger compatible with the
27785 tools suite used to build the DLL.
27786
27787 @node Program and DLL Both Built with GCC/GNAT
27788 @subsection Program and DLL Both Built with GCC/GNAT
27789
27790 @noindent
27791 This is the simplest case. Both the DLL and the program have @code{GDB}
27792 compatible debugging information. It is then possible to break anywhere in
27793 the process. Let's suppose here that the main procedure is named
27794 @code{ada_main} and that in the DLL there is an entry point named
27795 @code{ada_dll}.
27796
27797 @noindent
27798 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
27799 program must have been built with the debugging information (see GNAT -g
27800 switch). Here are the step-by-step instructions for debugging it:
27801
27802 @enumerate 1
27803 @item Launch @code{GDB} on the main program.
27804
27805 @smallexample
27806 $ gdb -nw ada_main
27807 @end smallexample
27808
27809 @item Break on the main procedure and run the program.
27810
27811 @smallexample
27812 (gdb) break ada_main
27813 (gdb) run
27814 @end smallexample
27815
27816 @noindent
27817 This step is required to be able to set a breakpoint inside the DLL. As long
27818 as the program is not run, the DLL is not loaded. This has the
27819 consequence that the DLL debugging information is also not loaded, so it is not
27820 possible to set a breakpoint in the DLL.
27821
27822 @item Set a breakpoint inside the DLL
27823
27824 @smallexample
27825 (gdb) break ada_dll
27826 (gdb) run
27827 @end smallexample
27828
27829 @end enumerate
27830
27831 @noindent
27832 At this stage a breakpoint is set inside the DLL. From there on
27833 you can use the standard approach to debug the whole program
27834 (@pxref{Running and Debugging Ada Programs}).
27835
27836 To break on the @code{DllMain} routine it is not possible to follow
27837 the procedure above. At the time the program stop on @code{ada_main}
27838 the @code{DllMain} routine as already been called. Either you can use
27839 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
27840
27841 @enumerate 1
27842 @item Launch @code{GDB} on the main program.
27843
27844 @smallexample
27845 $ gdb -nw ada_main
27846 @end smallexample
27847
27848 @item Load DLL symbols
27849
27850 @smallexample
27851 (gdb) add-sym api.dll
27852 @end smallexample
27853
27854 @item Set a breakpoint inside the DLL
27855
27856 @smallexample
27857 (gdb) break ada_dll.adb:45
27858 @end smallexample
27859
27860 Note that at this point it is not possible to break using the routine symbol
27861 directly as the program is not yet running. The solution is to break
27862 on the proper line (break in @file{ada_dll.adb} line 45).
27863
27864 @item Start the program
27865
27866 @smallexample
27867 (gdb) run
27868 @end smallexample
27869
27870 @end enumerate
27871
27872 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
27873 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
27874
27875 @menu
27876 * Debugging the DLL Directly::
27877 * Attaching to a Running Process::
27878 @end menu
27879
27880 @noindent
27881 In this case things are slightly more complex because it is not possible to
27882 start the main program and then break at the beginning to load the DLL and the
27883 associated DLL debugging information. It is not possible to break at the
27884 beginning of the program because there is no @code{GDB} debugging information,
27885 and therefore there is no direct way of getting initial control. This
27886 section addresses this issue by describing some methods that can be used
27887 to break somewhere in the DLL to debug it.
27888
27889 @noindent
27890 First suppose that the main procedure is named @code{main} (this is for
27891 example some C code built with Microsoft Visual C) and that there is a
27892 DLL named @code{test.dll} containing an Ada entry point named
27893 @code{ada_dll}.
27894
27895 @noindent
27896 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
27897 been built with debugging information (see GNAT -g option).
27898
27899 @node Debugging the DLL Directly
27900 @subsubsection Debugging the DLL Directly
27901
27902 @enumerate 1
27903 @item
27904 Launch the debugger on the DLL.
27905
27906 @smallexample
27907 $ gdb -nw test.dll
27908 @end smallexample
27909
27910 @item Set a breakpoint on a DLL subroutine.
27911
27912 @smallexample
27913 (gdb) break ada_dll.adb:45
27914 @end smallexample
27915
27916 Note that at this point it is not possible to break using the routine symbol
27917 directly as the program is not yet running. The solution is to break
27918 on the proper line (break in @file{ada_dll.adb} line 45).
27919
27920 @item
27921 Specify the executable file to @code{GDB}.
27922
27923 @smallexample
27924 (gdb) exec-file main.exe
27925 @end smallexample
27926
27927 @item
27928 Run the program.
27929
27930 @smallexample
27931 (gdb) run
27932 @end smallexample
27933
27934 @noindent
27935 This will run the program until it reaches the breakpoint that has been
27936 set. From that point you can use the standard way to debug a program
27937 as described in (@pxref{Running and Debugging Ada Programs}).
27938
27939 @end enumerate
27940
27941 @noindent
27942 It is also possible to debug the DLL by attaching to a running process.
27943
27944 @node Attaching to a Running Process
27945 @subsubsection Attaching to a Running Process
27946 @cindex DLL debugging, attach to process
27947
27948 @noindent
27949 With @code{GDB} it is always possible to debug a running process by
27950 attaching to it. It is possible to debug a DLL this way. The limitation
27951 of this approach is that the DLL must run long enough to perform the
27952 attach operation. It may be useful for instance to insert a time wasting
27953 loop in the code of the DLL to meet this criterion.
27954
27955 @enumerate 1
27956
27957 @item Launch the main program @file{main.exe}.
27958
27959 @smallexample
27960 $ main
27961 @end smallexample
27962
27963 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
27964 that the process PID for @file{main.exe} is 208.
27965
27966 @item Launch gdb.
27967
27968 @smallexample
27969 $ gdb -nw
27970 @end smallexample
27971
27972 @item Attach to the running process to be debugged.
27973
27974 @smallexample
27975 (gdb) attach 208
27976 @end smallexample
27977
27978 @item Load the process debugging information.
27979
27980 @smallexample
27981 (gdb) symbol-file main.exe
27982 @end smallexample
27983
27984 @item Break somewhere in the DLL.
27985
27986 @smallexample
27987 (gdb) break ada_dll
27988 @end smallexample
27989
27990 @item Continue process execution.
27991
27992 @smallexample
27993 (gdb) continue
27994 @end smallexample
27995
27996 @end enumerate
27997
27998 @noindent
27999 This last step will resume the process execution, and stop at
28000 the breakpoint we have set. From there you can use the standard
28001 approach to debug a program as described in
28002 (@pxref{Running and Debugging Ada Programs}).
28003
28004 @node GNAT and COM/DCOM Objects
28005 @section GNAT and COM/DCOM Objects
28006 @findex COM
28007 @findex DCOM
28008
28009 @noindent
28010 This section is temporarily left blank.
28011
28012 @end ifset
28013
28014 @c **********************************
28015 @c * GNU Free Documentation License *
28016 @c **********************************
28017 @include fdl.texi
28018 @c GNU Free Documentation License
28019
28020 @node Index,,GNU Free Documentation License, Top
28021 @unnumbered Index
28022
28023 @printindex cp
28024
28025 @contents
28026 @c Put table of contents at end, otherwise it precedes the "title page" in
28027 @c the .txt version
28028 @c Edit the pdf file to move the contents to the beginning, after the title
28029 @c page
28030
28031 @bye