OSDN Git Service

* Makefile.in (reload1.o-warn): Remove.
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
4 @c                                                                            o
5 @c                            GNAT DOCUMENTATION                              o
6 @c                                                                            o
7 @c                             G N A T _ U G N                                o
8 @c                                                                            o
9 @c                     Copyright (C) 1992-2007, AdaCore                       o
10 @c                                                                            o
11 @c  GNAT is free software;  you can  redistribute it  and/or modify it under  o
12 @c  terms of the  GNU General Public License as published  by the Free Soft-  o
13 @c  ware  Foundation;  either version 2,  or (at your option) any later ver-  o
14 @c  sion.  GNAT is distributed in the hope that it will be useful, but WITH-  o
15 @c  OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY  o
16 @c  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License  o
17 @c  for  more details.  You should have  received  a copy of the GNU General  o
18 @c  Public License  distributed with GNAT;  see file COPYING.  If not, write  o
19 @c  to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor,  o
20 @c  Boston, MA 02110-1301, USA.                                               o
21 @c                                                                            o
22 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
23
24 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
25 @c
26 @c                           GNAT_UGN Style Guide
27 @c
28 @c  1. Always put a @noindent on the line before the first paragraph
29 @c     after any of these commands:
30 @c
31 @c          @chapter
32 @c          @section
33 @c          @subsection
34 @c          @subsubsection
35 @c          @subsubsubsection
36 @c
37 @c          @end smallexample
38 @c          @end itemize
39 @c          @end enumerate
40 @c
41 @c  2. DO NOT use @example. Use @smallexample instead.
42 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
43 @c        context.  These can interfere with the readability of the texi
44 @c        source file.  Instead, use one of the following annotated
45 @c        @smallexample commands, and preprocess the texi file with the
46 @c        ada2texi tool (which generates appropriate highlighting):
47 @c        @smallexample @c ada
48 @c        @smallexample @c adanocomment
49 @c        @smallexample @c projectfile
50 @c     b) The "@c ada" markup will result in boldface for reserved words
51 @c        and italics for comments
52 @c     c) The "@c adanocomment" markup will result only in boldface for
53 @c        reserved words (comments are left alone)
54 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
55 @c        of reserved words include the new reserved words for project files
56 @c
57 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
58 @c     command must be preceded by two empty lines
59 @c
60 @c  4. The @item command should be on a line of its own if it is in an
61 @c     @itemize or @enumerate command.
62 @c
63 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
64 @c     or "ali".
65 @c
66 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
67 @c     cause the document build to fail.
68 @c
69 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
70 @c     This command inhibits page breaks, so long examples in a @cartouche can
71 @c     lead to large, ugly patches of empty space on a page.
72 @c
73 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
74 @c        or the unw flag set.  The unw flag covers topics for both Unix and
75 @c        Windows.
76 @c
77 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
78
79 @setfilename gnat_ugn.info
80
81 @set NOW January 2007
82 @c This flag is used where the text refers to conditions that exist when the
83 @c text was entered into the document but which may change over time.
84 @c Update the setting for the flag, and (if necessary) the text surrounding,
85 @c the references to the flag, on future doc revisions:
86 @c search for @value{NOW}.
87
88 @set FSFEDITION
89 @set EDITION GNAT
90 @set DEFAULTLANGUAGEVERSION Ada 2005
91 @set NONDEFAULTLANGUAGEVERSION Ada 95
92
93 @ifset unw
94 @setfilename gnat_ugn_unw.info
95 @end ifset
96
97 @ifset unw
98 @set PLATFORM
99 @set FILE gnat_ugn_unw
100 @end ifset
101
102 @ifset vms
103 @set PLATFORM OpenVMS
104 @set FILE gnat_ugn_vms
105 @end ifset
106
107 @settitle @value{EDITION} User's Guide @value{PLATFORM}
108 @dircategory GNU Ada tools
109 @direntry
110 * @value{EDITION} User's Guide (@value{FILE}) @value{PLATFORM}
111 @end direntry
112
113 @include gcc-common.texi
114
115 @setchapternewpage odd
116 @syncodeindex fn cp
117 @c %**end of header
118
119 @copying
120 Copyright @copyright{} 1995-2005, Free Software Foundation
121
122 Permission is granted to copy, distribute and/or modify this document
123 under the terms of the GNU Free Documentation License, Version 1.2
124 or any later version published by the Free Software Foundation;
125 with the Invariant Sections being ``GNU Free Documentation License'', with the
126 Front-Cover Texts being
127 ``@value{EDITION} User's Guide'',
128 and with no Back-Cover Texts.
129 A copy of the license is included in the section entitled
130 ``GNU Free Documentation License''.
131 @end copying
132
133 @titlepage
134 @title @value{EDITION} User's Guide
135 @ifset vms
136 @sp 1
137 @flushright
138 @titlefont{@i{@value{PLATFORM}}}
139 @end flushright
140 @end ifset
141
142 @sp 2
143
144 @subtitle GNAT, The GNU Ada Compiler
145 @versionsubtitle
146 @author AdaCore
147
148 @page
149 @vskip 0pt plus 1filll
150
151 @insertcopying
152
153 @end titlepage
154
155 @ifnottex
156 @node Top, About This Guide, (dir), (dir)
157 @top @value{EDITION} User's Guide
158
159 @noindent
160 @value{EDITION} User's Guide @value{PLATFORM}
161
162 @noindent
163 GNAT, The GNU Ada Compiler@*
164 GCC version @value{version-GCC}@*
165
166 @noindent
167 AdaCore@*
168
169 @menu
170 * About This Guide::
171 * Getting Started with GNAT::
172 * The GNAT Compilation Model::
173 * Compiling Using gcc::
174 * Binding Using gnatbind::
175 * Linking Using gnatlink::
176 * The GNAT Make Program gnatmake::
177 * Improving Performance::
178 * Renaming Files Using gnatchop::
179 * Configuration Pragmas::
180 * Handling Arbitrary File Naming Conventions Using gnatname::
181 * GNAT Project Manager::
182 * The Cross-Referencing Tools gnatxref and gnatfind::
183 * The GNAT Pretty-Printer gnatpp::
184 * The GNAT Metric Tool gnatmetric::
185 * File Name Krunching Using gnatkr::
186 * Preprocessing Using gnatprep::
187 @ifset vms
188 * The GNAT Run-Time Library Builder gnatlbr::
189 @end ifset
190 * The GNAT Library Browser gnatls::
191 * Cleaning Up Using gnatclean::
192 @ifclear vms
193 * GNAT and Libraries::
194 * Using the GNU make Utility::
195 @end ifclear
196 * Memory Management Issues::
197 * Stack Related Facilities::
198 * Verifying Properties Using gnatcheck::
199 * Creating Sample Bodies Using gnatstub::
200 * Other Utility Programs::
201 * Running and Debugging Ada Programs::
202 @ifset vms
203 * Compatibility with HP Ada::
204 @end ifset
205 * Platform-Specific Information for the Run-Time Libraries::
206 * Example of Binder Output File::
207 * Elaboration Order Handling in GNAT::
208 * Inline Assembler::
209 * Compatibility and Porting Guide::
210 @ifset unw
211 * Microsoft Windows Topics::
212 @end ifset
213 * GNU Free Documentation License::
214 * Index::
215
216  --- The Detailed Node Listing ---
217
218 About This Guide
219
220 * What This Guide Contains::
221 * What You Should Know before Reading This Guide::
222 * Related Information::
223 * Conventions::
224
225 Getting Started with GNAT
226
227 * Running GNAT::
228 * Running a Simple Ada Program::
229 * Running a Program with Multiple Units::
230 * Using the gnatmake Utility::
231 @ifset vms
232 * Editing with Emacs::
233 @end ifset
234 @ifclear vms
235 * Introduction to GPS::
236 @end ifclear
237
238 The GNAT Compilation Model
239
240 * Source Representation::
241 * Foreign Language Representation::
242 * File Naming Rules::
243 * Using Other File Names::
244 * Alternative File Naming Schemes::
245 * Generating Object Files::
246 * Source Dependencies::
247 * The Ada Library Information Files::
248 * Binding an Ada Program::
249 * Mixed Language Programming::
250 @ifclear vms
251 * Building Mixed Ada & C++ Programs::
252 * Comparison between GNAT and C/C++ Compilation Models::
253 @end ifclear
254 * Comparison between GNAT and Conventional Ada Library Models::
255 @ifset vms
256 * Placement of temporary files::
257 @end ifset
258
259 Foreign Language Representation
260
261 * Latin-1::
262 * Other 8-Bit Codes::
263 * Wide Character Encodings::
264
265 Compiling Ada Programs With gcc
266
267 * Compiling Programs::
268 * Switches for gcc::
269 * Search Paths and the Run-Time Library (RTL)::
270 * Order of Compilation Issues::
271 * Examples::
272
273 Switches for gcc
274
275 * Output and Error Message Control::
276 * Warning Message Control::
277 * Debugging and Assertion Control::
278 * Validity Checking::
279 * Style Checking::
280 * Run-Time Checks::
281 * Using gcc for Syntax Checking::
282 * Using gcc for Semantic Checking::
283 * Compiling Different Versions of Ada::
284 * Character Set Control::
285 * File Naming Control::
286 * Subprogram Inlining Control::
287 * Auxiliary Output Control::
288 * Debugging Control::
289 * Exception Handling Control::
290 * Units to Sources Mapping Files::
291 * Integrated Preprocessing::
292 @ifset vms
293 * Return Codes::
294 @end ifset
295
296 Binding Ada Programs With gnatbind
297
298 * Running gnatbind::
299 * Switches for gnatbind::
300 * Command-Line Access::
301 * Search Paths for gnatbind::
302 * Examples of gnatbind Usage::
303
304 Switches for gnatbind
305
306 * Consistency-Checking Modes::
307 * Binder Error Message Control::
308 * Elaboration Control::
309 * Output Control::
310 * Binding with Non-Ada Main Programs::
311 * Binding Programs with No Main Subprogram::
312
313 Linking Using gnatlink
314
315 * Running gnatlink::
316 * Switches for gnatlink::
317
318 The GNAT Make Program gnatmake
319
320 * Running gnatmake::
321 * Switches for gnatmake::
322 * Mode Switches for gnatmake::
323 * Notes on the Command Line::
324 * How gnatmake Works::
325 * Examples of gnatmake Usage::
326
327 Improving Performance
328 * Performance Considerations::
329 * Reducing Size of Ada Executables with gnatelim::
330 * Reducing Size of Executables with unused subprogram/data elimination::
331
332 Performance Considerations
333 * Controlling Run-Time Checks::
334 * Use of Restrictions::
335 * Optimization Levels::
336 * Debugging Optimized Code::
337 * Inlining of Subprograms::
338 * Other Optimization Switches::
339 * Optimization and Strict Aliasing::
340 @ifset vms
341 * Coverage Analysis::
342 @end ifset
343
344 Reducing Size of Ada Executables with gnatelim
345 * About gnatelim::
346 * Running gnatelim::
347 * Correcting the List of Eliminate Pragmas::
348 * Making Your Executables Smaller::
349 * Summary of the gnatelim Usage Cycle::
350
351 Reducing Size of Executables with unused subprogram/data elimination
352 * About unused subprogram/data elimination::
353 * Compilation options::
354
355 Renaming Files Using gnatchop
356
357 * Handling Files with Multiple Units::
358 * Operating gnatchop in Compilation Mode::
359 * Command Line for gnatchop::
360 * Switches for gnatchop::
361 * Examples of gnatchop Usage::
362
363 Configuration Pragmas
364
365 * Handling of Configuration Pragmas::
366 * The Configuration Pragmas Files::
367
368 Handling Arbitrary File Naming Conventions Using gnatname
369
370 * Arbitrary File Naming Conventions::
371 * Running gnatname::
372 * Switches for gnatname::
373 * Examples of gnatname Usage::
374
375 GNAT Project Manager
376
377 * Introduction::
378 * Examples of Project Files::
379 * Project File Syntax::
380 * Objects and Sources in Project Files::
381 * Importing Projects::
382 * Project Extension::
383 * Project Hierarchy Extension::
384 * External References in Project Files::
385 * Packages in Project Files::
386 * Variables from Imported Projects::
387 * Naming Schemes::
388 * Library Projects::
389 * Stand-alone Library Projects::
390 * Switches Related to Project Files::
391 * Tools Supporting Project Files::
392 * An Extended Example::
393 * Project File Complete Syntax::
394
395 The Cross-Referencing Tools gnatxref and gnatfind
396
397 * gnatxref Switches::
398 * gnatfind Switches::
399 * Project Files for gnatxref and gnatfind::
400 * Regular Expressions in gnatfind and gnatxref::
401 * Examples of gnatxref Usage::
402 * Examples of gnatfind Usage::
403
404 The GNAT Pretty-Printer gnatpp
405
406 * Switches for gnatpp::
407 * Formatting Rules::
408
409 The GNAT Metrics Tool gnatmetric
410
411 * Switches for gnatmetric::
412
413 File Name Krunching Using gnatkr
414
415 * About gnatkr::
416 * Using gnatkr::
417 * Krunching Method::
418 * Examples of gnatkr Usage::
419
420 Preprocessing Using gnatprep
421
422 * Using gnatprep::
423 * Switches for gnatprep::
424 * Form of Definitions File::
425 * Form of Input Text for gnatprep::
426
427 @ifset vms
428 The GNAT Run-Time Library Builder gnatlbr
429
430 * Running gnatlbr::
431 * Switches for gnatlbr::
432 * Examples of gnatlbr Usage::
433 @end ifset
434
435 The GNAT Library Browser gnatls
436
437 * Running gnatls::
438 * Switches for gnatls::
439 * Examples of gnatls Usage::
440
441 Cleaning Up Using gnatclean
442
443 * Running gnatclean::
444 * Switches for gnatclean::
445 @c * Examples of gnatclean Usage::
446
447 @ifclear vms
448
449 GNAT and Libraries
450
451 * Introduction to Libraries in GNAT::
452 * General Ada Libraries::
453 * Stand-alone Ada Libraries::
454 * Rebuilding the GNAT Run-Time Library::
455
456 Using the GNU make Utility
457
458 * Using gnatmake in a Makefile::
459 * Automatically Creating a List of Directories::
460 * Generating the Command Line Switches::
461 * Overcoming Command Line Length Limits::
462 @end ifclear
463
464 Memory Management Issues
465
466 * Some Useful Memory Pools::
467 * The GNAT Debug Pool Facility::
468 @ifclear vms
469 * The gnatmem Tool::
470 @end ifclear
471
472 Stack Related Facilities
473
474 * Stack Overflow Checking::
475 * Static Stack Usage Analysis::
476 * Dynamic Stack Usage Analysis::
477
478 Some Useful Memory Pools
479
480 The GNAT Debug Pool Facility
481
482 @ifclear vms
483 The gnatmem Tool
484
485 * Running gnatmem::
486 * Switches for gnatmem::
487 * Example of gnatmem Usage::
488 @end ifclear
489
490 Verifying Properties Using gnatcheck
491
492 * Format of the Report File::
493 * General gnatcheck Switches::
494 * gnatcheck Rule Options::
495 * Adding the Results of Compiler Checks to gnatcheck Output::
496 * Project-Wide Checks::
497 * Predefined Rules::
498
499 Sample Bodies Using gnatstub
500
501 * Running gnatstub::
502 * Switches for gnatstub::
503
504 Other Utility Programs
505
506 * Using Other Utility Programs with GNAT::
507 * The External Symbol Naming Scheme of GNAT::
508 * Converting Ada Files to html with gnathtml::
509
510 Running and Debugging Ada Programs
511
512 * The GNAT Debugger GDB::
513 * Running GDB::
514 * Introduction to GDB Commands::
515 * Using Ada Expressions::
516 * Calling User-Defined Subprograms::
517 * Using the Next Command in a Function::
518 * Ada Exceptions::
519 * Ada Tasks::
520 * Debugging Generic Units::
521 * GNAT Abnormal Termination or Failure to Terminate::
522 * Naming Conventions for GNAT Source Files::
523 * Getting Internal Debugging Information::
524 * Stack Traceback::
525
526 @ifset vms
527 * LSE::
528 @end ifset
529
530 @ifset vms
531 Compatibility with HP Ada
532
533 * Ada Language Compatibility::
534 * Differences in the Definition of Package System::
535 * Language-Related Features::
536 * The Package STANDARD::
537 * The Package SYSTEM::
538 * Tasking and Task-Related Features::
539 * Pragmas and Pragma-Related Features::
540 * Library of Predefined Units::
541 * Bindings::
542 * Main Program Definition::
543 * Implementation-Defined Attributes::
544 * Compiler and Run-Time Interfacing::
545 * Program Compilation and Library Management::
546 * Input-Output::
547 * Implementation Limits::
548 * Tools and Utilities::
549
550 Language-Related Features
551
552 * Integer Types and Representations::
553 * Floating-Point Types and Representations::
554 * Pragmas Float_Representation and Long_Float::
555 * Fixed-Point Types and Representations::
556 * Record and Array Component Alignment::
557 * Address Clauses::
558 * Other Representation Clauses::
559
560 Tasking and Task-Related Features
561
562 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
563 * Assigning Task IDs::
564 * Task IDs and Delays::
565 * Task-Related Pragmas::
566 * Scheduling and Task Priority::
567 * The Task Stack::
568 * External Interrupts::
569
570 Pragmas and Pragma-Related Features
571
572 * Restrictions on the Pragma INLINE::
573 * Restrictions on the Pragma INTERFACE::
574 * Restrictions on the Pragma SYSTEM_NAME::
575
576 Library of Predefined Units
577
578 * Changes to DECLIB::
579
580 Bindings
581
582 * Shared Libraries and Options Files::
583 * Interfaces to C::
584 @end ifset
585
586 Platform-Specific Information for the Run-Time Libraries
587
588 * Summary of Run-Time Configurations::
589 * Specifying a Run-Time Library::
590 * Choosing the Scheduling Policy::
591 * Solaris-Specific Considerations::
592 * Linux-Specific Considerations::
593 * AIX-Specific Considerations::
594
595 Example of Binder Output File
596
597 Elaboration Order Handling in GNAT
598
599 * Elaboration Code::
600 * Checking the Elaboration Order::
601 * Controlling the Elaboration Order::
602 * Controlling Elaboration in GNAT - Internal Calls::
603 * Controlling Elaboration in GNAT - External Calls::
604 * Default Behavior in GNAT - Ensuring Safety::
605 * Treatment of Pragma Elaborate::
606 * Elaboration Issues for Library Tasks::
607 * Mixing Elaboration Models::
608 * What to Do If the Default Elaboration Behavior Fails::
609 * Elaboration for Access-to-Subprogram Values::
610 * Summary of Procedures for Elaboration Control::
611 * Other Elaboration Order Considerations::
612
613 Inline Assembler
614
615 * Basic Assembler Syntax::
616 * A Simple Example of Inline Assembler::
617 * Output Variables in Inline Assembler::
618 * Input Variables in Inline Assembler::
619 * Inlining Inline Assembler Code::
620 * Other Asm Functionality::
621
622 Compatibility and Porting Guide
623
624 * Compatibility with Ada 83::
625 * Compatibility between Ada 95 and Ada 2005::
626 * Implementation-dependent characteristics::
627 @ifclear vms
628 @c This brief section is only in the non-VMS version
629 @c The complete chapter on HP Ada issues is in the VMS version
630 * Compatibility with HP Ada 83::
631 @end ifclear
632 * Compatibility with Other Ada Systems::
633 * Representation Clauses::
634 @ifset vms
635 * Transitioning to 64-Bit GNAT for OpenVMS::
636 @end ifset
637
638 @ifset unw
639 Microsoft Windows Topics
640
641 * Using GNAT on Windows::
642 * CONSOLE and WINDOWS subsystems::
643 * Temporary Files::
644 * Mixed-Language Programming on Windows::
645 * Windows Calling Conventions::
646 * Introduction to Dynamic Link Libraries (DLLs)::
647 * Using DLLs with GNAT::
648 * Building DLLs with GNAT::
649 * GNAT and Windows Resources::
650 * Debugging a DLL::
651 * Setting Stack Size from gnatlink::
652 * Setting Heap Size from gnatlink::
653 @end ifset
654
655 * Index::
656 @end menu
657 @end ifnottex
658
659 @node About This Guide
660 @unnumbered About This Guide
661
662 @noindent
663 @ifset vms
664 This guide describes the use of @value{EDITION},
665 a compiler and software development toolset for the full Ada
666 programming language, implemented on OpenVMS for HP's Alpha and
667 Integrity server (I64) platforms.
668 @end ifset
669 @ifclear vms
670 This guide describes the use of @value{EDITION},
671 a compiler and software development
672 toolset for the full Ada programming language.
673 @end ifclear
674 It documents the features of the compiler and tools, and explains
675 how to use them to build Ada applications.
676
677 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
678 Ada 83 compatibility mode.
679 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
680 but you can override with a compiler switch
681 (@pxref{Compiling Different Versions of Ada})
682 to explicitly specify the language version.
683 Throughout this manual, references to ``Ada'' without a year suffix
684 apply to both the Ada 95 and Ada 2005 versions of the language.
685
686
687 @ifclear FSFEDITION
688 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
689 ``GNAT'' in the remainder of this document.
690 @end ifclear
691
692
693
694
695 @menu
696 * What This Guide Contains::
697 * What You Should Know before Reading This Guide::
698 * Related Information::
699 * Conventions::
700 @end menu
701
702 @node What This Guide Contains
703 @unnumberedsec What This Guide Contains
704
705 @noindent
706 This guide contains the following chapters:
707 @itemize @bullet
708
709 @item
710 @ref{Getting Started with GNAT}, describes how to get started compiling
711 and running Ada programs with the GNAT Ada programming environment.
712 @item
713 @ref{The GNAT Compilation Model}, describes the compilation model used
714 by GNAT.
715
716 @item
717 @ref{Compiling Using gcc}, describes how to compile
718 Ada programs with @command{gcc}, the Ada compiler.
719
720 @item
721 @ref{Binding Using gnatbind}, describes how to
722 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
723 utility.
724
725 @item
726 @ref{Linking Using gnatlink},
727 describes @command{gnatlink}, a
728 program that provides for linking using the GNAT run-time library to
729 construct a program. @command{gnatlink} can also incorporate foreign language
730 object units into the executable.
731
732 @item
733 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
734 utility that automatically determines the set of sources
735 needed by an Ada compilation unit, and executes the necessary compilations
736 binding and link.
737
738 @item
739 @ref{Improving Performance}, shows various techniques for making your
740 Ada program run faster or take less space.
741 It discusses the effect of the compiler's optimization switch and
742 also describes the @command{gnatelim} tool and unused subprogram/data
743 elimination.
744
745 @item
746 @ref{Renaming Files Using gnatchop}, describes
747 @code{gnatchop}, a utility that allows you to preprocess a file that
748 contains Ada source code, and split it into one or more new files, one
749 for each compilation unit.
750
751 @item
752 @ref{Configuration Pragmas}, describes the configuration pragmas
753 handled by GNAT.
754
755 @item
756 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
757 shows how to override the default GNAT file naming conventions,
758 either for an individual unit or globally.
759
760 @item
761 @ref{GNAT Project Manager}, describes how to use project files
762 to organize large projects.
763
764 @item
765 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
766 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
767 way to navigate through sources.
768
769 @item
770 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
771 version of an Ada source file with control over casing, indentation,
772 comment placement, and other elements of program presentation style.
773
774 @item
775 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
776 metrics for an Ada source file, such as the number of types and subprograms,
777 and assorted complexity measures.
778
779 @item
780 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
781 file name krunching utility, used to handle shortened
782 file names on operating systems with a limit on the length of names.
783
784 @item
785 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
786 preprocessor utility that allows a single source file to be used to
787 generate multiple or parameterized source files, by means of macro
788 substitution.
789
790 @ifset vms
791 @item
792 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
793 a tool for rebuilding the GNAT run time with user-supplied
794 configuration pragmas.
795 @end ifset
796
797 @item
798 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
799 utility that displays information about compiled units, including dependences
800 on the corresponding sources files, and consistency of compilations.
801
802 @item
803 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
804 to delete files that are produced by the compiler, binder and linker.
805
806 @ifclear vms
807 @item
808 @ref{GNAT and Libraries}, describes the process of creating and using
809 Libraries with GNAT. It also describes how to recompile the GNAT run-time
810 library.
811
812 @item
813 @ref{Using the GNU make Utility}, describes some techniques for using
814 the GNAT toolset in Makefiles.
815 @end ifclear
816
817 @item
818 @ref{Memory Management Issues}, describes some useful predefined storage pools
819 and in particular the GNAT Debug Pool facility, which helps detect incorrect
820 memory references.
821 @ifclear vms
822 It also describes @command{gnatmem}, a utility that monitors dynamic
823 allocation and deallocation and helps detect ``memory leaks''.
824 @end ifclear
825
826 @item
827 @ref{Stack Related Facilities}, describes some useful tools associated with
828 stack checking and analysis.
829
830 @item
831 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
832 a utility that checks Ada code against a set of rules.
833
834 @item
835 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
836 a utility that generates empty but compilable bodies for library units.
837
838 @item
839 @ref{Other Utility Programs}, discusses several other GNAT utilities,
840 including @code{gnathtml}.
841
842 @item
843 @ref{Running and Debugging Ada Programs}, describes how to run and debug
844 Ada programs.
845
846 @ifset vms
847 @item
848 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
849 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
850 developed by Digital Equipment Corporation and currently supported by HP.}
851 for OpenVMS Alpha. This product was formerly known as DEC Ada,
852 @cindex DEC Ada
853 and for
854 historical compatibility reasons, the relevant libraries still use the
855 DEC prefix.
856 @end ifset
857
858 @item
859 @ref{Platform-Specific Information for the Run-Time Libraries},
860 describes the various run-time
861 libraries supported by GNAT on various platforms and explains how to
862 choose a particular library.
863
864 @item
865 @ref{Example of Binder Output File}, shows the source code for the binder
866 output file for a sample program.
867
868 @item
869 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
870 you deal with elaboration order issues.
871
872 @item
873 @ref{Inline Assembler}, shows how to use the inline assembly facility
874 in an Ada program.
875
876 @item
877 @ref{Compatibility and Porting Guide}, contains sections on compatibility
878 of GNAT with other Ada development environments (including Ada 83 systems),
879 to assist in porting code from those environments.
880
881 @ifset unw
882 @item
883 @ref{Microsoft Windows Topics}, presents information relevant to the
884 Microsoft Windows platform.
885 @end ifset
886 @end itemize
887
888 @c *************************************************
889 @node What You Should Know before Reading This Guide
890 @c *************************************************
891 @unnumberedsec What You Should Know before Reading This Guide
892
893 @cindex Ada 95 Language Reference Manual
894 @cindex Ada 2005 Language Reference Manual
895 @noindent
896 This guide assumes a basic familiarity with the Ada 95 language, as
897 described in the International Standard ANSI/ISO/IEC-8652:1995, January
898 1995.
899 It does not require knowledge of the new features introduced by Ada 2005,
900 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
901 and Amendment 1).
902 Both reference manuals are included in the GNAT documentation
903 package.
904
905 @node Related Information
906 @unnumberedsec Related Information
907
908 @noindent
909 For further information about related tools, refer to the following
910 documents:
911
912 @itemize @bullet
913 @item
914 @cite{GNAT Reference Manual}, which contains all reference
915 material for the GNAT implementation of Ada.
916
917 @ifset unw
918 @item
919 @cite{Using the GNAT Programming Studio}, which describes the GPS
920 Integrated Development Environment.
921
922 @item
923 @cite{GNAT Programming Studio Tutorial}, which introduces the
924 main GPS features through examples.
925 @end ifset
926
927 @item
928 @cite{Ada 95 Reference Manual}, which contains reference
929 material for the Ada 95 programming language.
930
931 @item
932 @cite{Ada 2005 Reference Manual}, which contains reference
933 material for the Ada 2005 programming language.
934
935 @item
936 @cite{Debugging with GDB}
937 @ifset vms
938 , located in the GNU:[DOCS] directory,
939 @end ifset
940 contains all details on the use of the GNU source-level debugger.
941
942 @item
943 @cite{GNU Emacs Manual}
944 @ifset vms
945 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
946 @end ifset
947 contains full information on the extensible editor and programming
948 environment Emacs.
949
950 @end itemize
951
952 @c **************
953 @node Conventions
954 @unnumberedsec Conventions
955 @cindex Conventions
956 @cindex Typographical conventions
957
958 @noindent
959 Following are examples of the typographical and graphic conventions used
960 in this guide:
961
962 @itemize @bullet
963 @item
964 @code{Functions}, @code{utility program names}, @code{standard names},
965 and @code{classes}.
966
967 @item
968 @samp{Option flags}
969
970 @item
971 @file{File Names}, @file{button names}, and @file{field names}.
972
973 @item
974 @var{Variables}.
975
976 @item
977 @emph{Emphasis}.
978
979 @item
980 [optional information or parameters]
981
982 @item
983 Examples are described by text
984 @smallexample
985 and then shown this way.
986 @end smallexample
987 @end itemize
988
989 @noindent
990 Commands that are entered by the user are preceded in this manual by the
991 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
992 uses this sequence as a prompt, then the commands will appear exactly as
993 you see them in the manual. If your system uses some other prompt, then
994 the command will appear with the @code{$} replaced by whatever prompt
995 character you are using.
996
997 @ifset unw
998 Full file names are shown with the ``@code{/}'' character
999 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1000 If you are using GNAT on a Windows platform, please note that
1001 the ``@code{\}'' character should be used instead.
1002 @end ifset
1003
1004 @c ****************************
1005 @node Getting Started with GNAT
1006 @chapter Getting Started with GNAT
1007
1008 @noindent
1009 This chapter describes some simple ways of using GNAT to build
1010 executable Ada programs.
1011 @ifset unw
1012 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1013 show how to use the command line environment.
1014 @ref{Introduction to GPS}, provides a brief
1015 introduction to the GNAT Programming Studio, a visually-oriented
1016 Integrated Development Environment for GNAT.
1017 GPS offers a graphical ``look and feel'', support for development in
1018 other programming languages, comprehensive browsing features, and
1019 many other capabilities.
1020 For information on GPS please refer to
1021 @cite{Using the GNAT Programming Studio}.
1022 @end ifset
1023
1024 @menu
1025 * Running GNAT::
1026 * Running a Simple Ada Program::
1027 * Running a Program with Multiple Units::
1028 * Using the gnatmake Utility::
1029 @ifset vms
1030 * Editing with Emacs::
1031 @end ifset
1032 @ifclear vms
1033 * Introduction to GPS::
1034 @end ifclear
1035 @end menu
1036
1037 @node Running GNAT
1038 @section Running GNAT
1039
1040 @noindent
1041 Three steps are needed to create an executable file from an Ada source
1042 file:
1043
1044 @enumerate
1045 @item
1046 The source file(s) must be compiled.
1047 @item
1048 The file(s) must be bound using the GNAT binder.
1049 @item
1050 All appropriate object files must be linked to produce an executable.
1051 @end enumerate
1052
1053 @noindent
1054 All three steps are most commonly handled by using the @command{gnatmake}
1055 utility program that, given the name of the main program, automatically
1056 performs the necessary compilation, binding and linking steps.
1057
1058 @node Running a Simple Ada Program
1059 @section Running a Simple Ada Program
1060
1061 @noindent
1062 Any text editor may be used to prepare an Ada program.
1063 (If @code{Emacs} is
1064 used, the optional Ada mode may be helpful in laying out the program.)
1065 The
1066 program text is a normal text file. We will assume in our initial
1067 example that you have used your editor to prepare the following
1068 standard format text file:
1069
1070 @smallexample @c ada
1071 @cartouche
1072 with Ada.Text_IO; use Ada.Text_IO;
1073 procedure Hello is
1074 begin
1075    Put_Line ("Hello WORLD!");
1076 end Hello;
1077 @end cartouche
1078 @end smallexample
1079
1080 @noindent
1081 This file should be named @file{hello.adb}.
1082 With the normal default file naming conventions, GNAT requires
1083 that each file
1084 contain a single compilation unit whose file name is the
1085 unit name,
1086 with periods replaced by hyphens; the
1087 extension is @file{ads} for a
1088 spec and @file{adb} for a body.
1089 You can override this default file naming convention by use of the
1090 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1091 Alternatively, if you want to rename your files according to this default
1092 convention, which is probably more convenient if you will be using GNAT
1093 for all your compilations, then the @code{gnatchop} utility
1094 can be used to generate correctly-named source files
1095 (@pxref{Renaming Files Using gnatchop}).
1096
1097 You can compile the program using the following command (@code{$} is used
1098 as the command prompt in the examples in this document):
1099
1100 @smallexample
1101 $ gcc -c hello.adb
1102 @end smallexample
1103
1104 @noindent
1105 @command{gcc} is the command used to run the compiler. This compiler is
1106 capable of compiling programs in several languages, including Ada and
1107 C. It assumes that you have given it an Ada program if the file extension is
1108 either @file{.ads} or @file{.adb}, and it will then call
1109 the GNAT compiler to compile the specified file.
1110
1111 @ifclear vms
1112 The @option{-c} switch is required. It tells @command{gcc} to only do a
1113 compilation. (For C programs, @command{gcc} can also do linking, but this
1114 capability is not used directly for Ada programs, so the @option{-c}
1115 switch must always be present.)
1116 @end ifclear
1117
1118 This compile command generates a file
1119 @file{hello.o}, which is the object
1120 file corresponding to your Ada program. It also generates
1121 an ``Ada Library Information'' file @file{hello.ali},
1122 which contains additional information used to check
1123 that an Ada program is consistent.
1124 To build an executable file,
1125 use @code{gnatbind} to bind the program
1126 and @command{gnatlink} to link it. The
1127 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1128 @file{ALI} file, but the default extension of @file{.ali} can
1129 be omitted. This means that in the most common case, the argument
1130 is simply the name of the main program:
1131
1132 @smallexample
1133 $ gnatbind hello
1134 $ gnatlink hello
1135 @end smallexample
1136
1137 @noindent
1138 A simpler method of carrying out these steps is to use
1139 @command{gnatmake},
1140 a master program that invokes all the required
1141 compilation, binding and linking tools in the correct order. In particular,
1142 @command{gnatmake} automatically recompiles any sources that have been
1143 modified since they were last compiled, or sources that depend
1144 on such modified sources, so that ``version skew'' is avoided.
1145 @cindex Version skew (avoided by @command{gnatmake})
1146
1147 @smallexample
1148 $ gnatmake hello.adb
1149 @end smallexample
1150
1151 @noindent
1152 The result is an executable program called @file{hello}, which can be
1153 run by entering:
1154
1155 @smallexample
1156 $ ^hello^RUN HELLO^
1157 @end smallexample
1158
1159 @noindent
1160 assuming that the current directory is on the search path
1161 for executable programs.
1162
1163 @noindent
1164 and, if all has gone well, you will see
1165
1166 @smallexample
1167 Hello WORLD!
1168 @end smallexample
1169
1170 @noindent
1171 appear in response to this command.
1172
1173 @c ****************************************
1174 @node Running a Program with Multiple Units
1175 @section Running a Program with Multiple Units
1176
1177 @noindent
1178 Consider a slightly more complicated example that has three files: a
1179 main program, and the spec and body of a package:
1180
1181 @smallexample @c ada
1182 @cartouche
1183 @group
1184 package Greetings is
1185    procedure Hello;
1186    procedure Goodbye;
1187 end Greetings;
1188
1189 with Ada.Text_IO; use Ada.Text_IO;
1190 package body Greetings is
1191    procedure Hello is
1192    begin
1193       Put_Line ("Hello WORLD!");
1194    end Hello;
1195
1196    procedure Goodbye is
1197    begin
1198       Put_Line ("Goodbye WORLD!");
1199    end Goodbye;
1200 end Greetings;
1201 @end group
1202
1203 @group
1204 with Greetings;
1205 procedure Gmain is
1206 begin
1207    Greetings.Hello;
1208    Greetings.Goodbye;
1209 end Gmain;
1210 @end group
1211 @end cartouche
1212 @end smallexample
1213
1214 @noindent
1215 Following the one-unit-per-file rule, place this program in the
1216 following three separate files:
1217
1218 @table @file
1219 @item greetings.ads
1220 spec of package @code{Greetings}
1221
1222 @item greetings.adb
1223 body of package @code{Greetings}
1224
1225 @item gmain.adb
1226 body of main program
1227 @end table
1228
1229 @noindent
1230 To build an executable version of
1231 this program, we could use four separate steps to compile, bind, and link
1232 the program, as follows:
1233
1234 @smallexample
1235 $ gcc -c gmain.adb
1236 $ gcc -c greetings.adb
1237 $ gnatbind gmain
1238 $ gnatlink gmain
1239 @end smallexample
1240
1241 @noindent
1242 Note that there is no required order of compilation when using GNAT.
1243 In particular it is perfectly fine to compile the main program first.
1244 Also, it is not necessary to compile package specs in the case where
1245 there is an accompanying body; you only need to compile the body. If you want
1246 to submit these files to the compiler for semantic checking and not code
1247 generation, then use the
1248 @option{-gnatc} switch:
1249
1250 @smallexample
1251 $ gcc -c greetings.ads -gnatc
1252 @end smallexample
1253
1254 @noindent
1255 Although the compilation can be done in separate steps as in the
1256 above example, in practice it is almost always more convenient
1257 to use the @command{gnatmake} tool. All you need to know in this case
1258 is the name of the main program's source file. The effect of the above four
1259 commands can be achieved with a single one:
1260
1261 @smallexample
1262 $ gnatmake gmain.adb
1263 @end smallexample
1264
1265 @noindent
1266 In the next section we discuss the advantages of using @command{gnatmake} in
1267 more detail.
1268
1269 @c *****************************
1270 @node Using the gnatmake Utility
1271 @section Using the @command{gnatmake} Utility
1272
1273 @noindent
1274 If you work on a program by compiling single components at a time using
1275 @command{gcc}, you typically keep track of the units you modify. In order to
1276 build a consistent system, you compile not only these units, but also any
1277 units that depend on the units you have modified.
1278 For example, in the preceding case,
1279 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1280 you edit @file{greetings.ads}, you must recompile both
1281 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1282 units that depend on @file{greetings.ads}.
1283
1284 @code{gnatbind} will warn you if you forget one of these compilation
1285 steps, so that it is impossible to generate an inconsistent program as a
1286 result of forgetting to do a compilation. Nevertheless it is tedious and
1287 error-prone to keep track of dependencies among units.
1288 One approach to handle the dependency-bookkeeping is to use a
1289 makefile. However, makefiles present maintenance problems of their own:
1290 if the dependencies change as you change the program, you must make
1291 sure that the makefile is kept up-to-date manually, which is also an
1292 error-prone process.
1293
1294 The @command{gnatmake} utility takes care of these details automatically.
1295 Invoke it using either one of the following forms:
1296
1297 @smallexample
1298 $ gnatmake gmain.adb
1299 $ gnatmake ^gmain^GMAIN^
1300 @end smallexample
1301
1302 @noindent
1303 The argument is the name of the file containing the main program;
1304 you may omit the extension. @command{gnatmake}
1305 examines the environment, automatically recompiles any files that need
1306 recompiling, and binds and links the resulting set of object files,
1307 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1308 In a large program, it
1309 can be extremely helpful to use @command{gnatmake}, because working out by hand
1310 what needs to be recompiled can be difficult.
1311
1312 Note that @command{gnatmake}
1313 takes into account all the Ada rules that
1314 establish dependencies among units. These include dependencies that result
1315 from inlining subprogram bodies, and from
1316 generic instantiation. Unlike some other
1317 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1318 found by the compiler on a previous compilation, which may possibly
1319 be wrong when sources change. @command{gnatmake} determines the exact set of
1320 dependencies from scratch each time it is run.
1321
1322 @ifset vms
1323 @node Editing with Emacs
1324 @section Editing with Emacs
1325 @cindex Emacs
1326
1327 @noindent
1328 Emacs is an extensible self-documenting text editor that is available in a
1329 separate VMSINSTAL kit.
1330
1331 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1332 click on the Emacs Help menu and run the Emacs Tutorial.
1333 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1334 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1335
1336 Documentation on Emacs and other tools is available in Emacs under the
1337 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1338 use the middle mouse button to select a topic (e.g. Emacs).
1339
1340 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1341 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1342 get to the Emacs manual.
1343 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1344 prompt.
1345
1346 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1347 which is sufficiently extensible to provide for a complete programming
1348 environment and shell for the sophisticated user.
1349 @end ifset
1350
1351 @ifclear vms
1352 @node Introduction to GPS
1353 @section Introduction to GPS
1354 @cindex GPS (GNAT Programming Studio)
1355 @cindex GNAT Programming Studio (GPS)
1356 @noindent
1357 Although the command line interface (@command{gnatmake}, etc.) alone
1358 is sufficient, a graphical Interactive Development
1359 Environment can make it easier for you to compose, navigate, and debug
1360 programs.  This section describes the main features of GPS
1361 (``GNAT Programming Studio''), the GNAT graphical IDE.
1362 You will see how to use GPS to build and debug an executable, and
1363 you will also learn some of the basics of the GNAT ``project'' facility.
1364
1365 GPS enables you to do much more than is presented here;
1366 e.g., you can produce a call graph, interface to a third-party
1367 Version Control System, and inspect the generated assembly language
1368 for a program.
1369 Indeed, GPS also supports languages other than Ada.
1370 Such additional information, and an explanation of all of the GPS menu
1371 items. may be found in the on-line help, which includes
1372 a user's guide and a tutorial (these are also accessible from the GNAT
1373 startup menu).
1374
1375 @menu
1376 * Building a New Program with GPS::
1377 * Simple Debugging with GPS::
1378 @end menu
1379
1380 @node Building a New Program with GPS
1381 @subsection Building a New Program with GPS
1382 @noindent
1383 GPS invokes the GNAT compilation tools using information
1384 contained in a @emph{project} (also known as a @emph{project file}):
1385 a collection of properties such
1386 as source directories, identities of main subprograms, tool switches, etc.,
1387 and their associated values.
1388 See @ref{GNAT Project Manager} for details.
1389 In order to run GPS, you will need to either create a new project
1390 or else open an existing one.
1391
1392 This section will explain how you can use GPS to create a project,
1393 to associate Ada source files with a project, and to build and run
1394 programs.
1395
1396 @enumerate
1397 @item @emph{Creating a project}
1398
1399 Invoke GPS, either from the command line or the platform's IDE.
1400 After it starts, GPS will display a ``Welcome'' screen with three
1401 radio buttons:
1402
1403 @itemize @bullet
1404 @item
1405 @code{Start with default project in directory}
1406
1407 @item
1408 @code{Create new project with wizard}
1409
1410 @item
1411 @code{Open existing project}
1412 @end itemize
1413
1414 @noindent
1415 Select @code{Create new project with wizard} and press @code{OK}.
1416 A new window will appear.  In the text box labeled with
1417 @code{Enter the name of the project to create}, type @file{sample}
1418 as the project name.
1419 In the next box, browse to choose the directory in which you
1420 would like to create the project file.
1421 After selecting an appropriate directory, press @code{Forward}.
1422
1423 A window will appear with the title
1424 @code{Version Control System Configuration}.
1425 Simply press @code{Forward}.
1426
1427 A window will appear with the title
1428 @code{Please select the source directories for this project}.
1429 The directory that you specified for the project file will be selected
1430 by default as the one to use for sources; simply press @code{Forward}.
1431
1432 A window will appear with the title
1433 @code{Please select the build directory for this project}.
1434 The directory that you specified for the project file will be selected
1435 by default for object files and executables;
1436 simply press @code{Forward}.
1437
1438 A window will appear with the title
1439 @code{Please select the main units for this project}.
1440 You will supply this information later, after creating the source file.
1441 Simply press @code{Forward} for now.
1442
1443 A window will appear with the title
1444 @code{Please select the switches to build the project}.
1445 Press @code{Apply}.  This will create a project file named
1446 @file{sample.prj} in the directory that you had specified.
1447
1448 @item @emph{Creating and saving the source file}
1449
1450 After you create the new project, a GPS window will appear, which is
1451 partitioned into two main sections:
1452
1453 @itemize @bullet
1454 @item
1455 A @emph{Workspace area}, initially greyed out, which you will use for
1456 creating and editing source files
1457
1458 @item
1459 Directly below, a @emph{Messages area}, which initially displays a
1460 ``Welcome'' message.
1461 (If the Messages area is not visible, drag its border upward to expand it.)
1462 @end itemize
1463
1464 @noindent
1465 Select @code{File} on the menu bar, and then the @code{New} command.
1466 The Workspace area will become white, and you can now
1467 enter the source program explicitly.
1468 Type the following text
1469
1470 @smallexample @c ada
1471 @group
1472 with Ada.Text_IO; use Ada.Text_IO;
1473 procedure Hello is
1474 begin
1475   Put_Line("Hello from GPS!");
1476 end Hello;
1477 @end group
1478 @end smallexample
1479
1480 @noindent
1481 Select @code{File}, then @code{Save As}, and enter the source file name
1482 @file{hello.adb}.
1483 The file will be saved in the same directory you specified as the
1484 location of the default project file.
1485
1486 @item @emph{Updating the project file}
1487
1488 You need to add the new source file to the project.
1489 To do this, select
1490 the @code{Project} menu and then @code{Edit project properties}.
1491 Click the @code{Main files} tab on the left, and then the
1492 @code{Add} button.
1493 Choose @file{hello.adb} from the list, and press @code{Open}.
1494 The project settings window will reflect this action.
1495 Click @code{OK}.
1496
1497 @item @emph{Building and running the program}
1498
1499 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1500 and select @file{hello.adb}.
1501 The Messages window will display the resulting invocations of @command{gcc},
1502 @command{gnatbind}, and @command{gnatlink}
1503 (reflecting the default switch settings from the
1504 project file that you created) and then a ``successful compilation/build''
1505 message.
1506
1507 To run the program, choose the @code{Build} menu, then @code{Run}, and
1508 select @command{hello}.
1509 An @emph{Arguments Selection} window will appear.
1510 There are no command line arguments, so just click @code{OK}.
1511
1512 The Messages window will now display the program's output (the string
1513 @code{Hello from GPS}), and at the bottom of the GPS window a status
1514 update is displayed (@code{Run: hello}).
1515 Close the GPS window (or select @code{File}, then @code{Exit}) to
1516 terminate this GPS session.
1517 @end enumerate
1518
1519 @node Simple Debugging with GPS
1520 @subsection Simple Debugging with GPS
1521 @noindent
1522 This section illustrates basic debugging techniques (setting breakpoints,
1523 examining/modifying variables, single stepping).
1524
1525 @enumerate
1526 @item @emph{Opening a project}
1527
1528 Start GPS and select @code{Open existing project}; browse to
1529 specify the project file @file{sample.prj} that you had created in the
1530 earlier example.
1531
1532 @item @emph{Creating a source file}
1533
1534 Select @code{File}, then @code{New}, and type in the following program:
1535
1536 @smallexample @c ada
1537 @group
1538 with Ada.Text_IO; use Ada.Text_IO;
1539 procedure Example is
1540    Line : String (1..80);
1541    N    : Natural;
1542 begin
1543    Put_Line("Type a line of text at each prompt; an empty line to exit");
1544    loop
1545       Put(": ");
1546       Get_Line (Line, N);
1547       Put_Line (Line (1..N) );
1548       exit when N=0;
1549    end loop;
1550 end Example;
1551 @end group
1552 @end smallexample
1553
1554 @noindent
1555 Select @code{File}, then @code{Save as}, and enter the file name
1556 @file{example.adb}.
1557
1558 @item @emph{Updating the project file}
1559
1560 Add @code{Example} as a new main unit for the project:
1561 @enumerate a
1562 @item
1563 Select @code{Project}, then @code{Edit Project Properties}.
1564
1565 @item
1566 Select the @code{Main files} tab, click @code{Add}, then
1567 select the file @file{example.adb} from the list, and
1568 click @code{Open}.
1569 You will see the file name appear in the list of main units
1570
1571 @item
1572 Click @code{OK}
1573 @end enumerate
1574
1575 @item @emph{Building/running the executable}
1576
1577 To build the executable
1578 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1579
1580 Run the program to see its effect (in the Messages area).
1581 Each line that you enter is displayed; an empty line will
1582 cause the loop to exit and the program to terminate.
1583
1584 @item @emph{Debugging the program}
1585
1586 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1587 which are required for debugging, are on by default when you create
1588 a new project.
1589 Thus unless you intentionally remove these settings, you will be able
1590 to debug any program that you develop using GPS.
1591
1592 @enumerate a
1593 @item @emph{Initializing}
1594
1595 Select @code{Debug}, then @code{Initialize}, then @file{example}
1596
1597 @item @emph{Setting a breakpoint}
1598
1599 After performing the initialization step, you will observe a small
1600 icon to the right of each line number.
1601 This serves as a toggle for breakpoints; clicking the icon will
1602 set a breakpoint at the corresponding line (the icon will change to
1603 a red circle with an ``x''), and clicking it again
1604 will remove the breakpoint / reset the icon.
1605
1606 For purposes of this example, set a breakpoint at line 10 (the
1607 statement @code{Put_Line@ (Line@ (1..N));}
1608
1609 @item @emph{Starting program execution}
1610
1611 Select @code{Debug}, then @code{Run}.  When the
1612 @code{Program Arguments} window appears, click @code{OK}.
1613 A console window will appear; enter some line of text,
1614 e.g. @code{abcde}, at the prompt.
1615 The program will pause execution when it gets to the
1616 breakpoint, and the corresponding line is highlighted.
1617
1618 @item @emph{Examining a variable}
1619
1620 Move the mouse over one of the occurrences of the variable @code{N}.
1621 You will see the value (5) displayed, in ``tool tip'' fashion.
1622 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1623 You will see information about @code{N} appear in the @code{Debugger Data}
1624 pane, showing the value as 5.
1625
1626 @item @emph{Assigning a new value to a variable}
1627
1628 Right click on the @code{N} in the @code{Debugger Data} pane, and
1629 select @code{Set value of N}.
1630 When the input window appears, enter the value @code{4} and click
1631 @code{OK}.
1632 This value does not automatically appear in the @code{Debugger Data}
1633 pane; to see it, right click again on the @code{N} in the
1634 @code{Debugger Data} pane and select @code{Update value}.
1635 The new value, 4, will appear in red.
1636
1637 @item @emph{Single stepping}
1638
1639 Select @code{Debug}, then @code{Next}.
1640 This will cause the next statement to be executed, in this case the
1641 call of @code{Put_Line} with the string slice.
1642 Notice in the console window that the displayed string is simply
1643 @code{abcd} and not @code{abcde} which you had entered.
1644 This is because the upper bound of the slice is now 4 rather than 5.
1645
1646 @item @emph{Removing a breakpoint}
1647
1648 Toggle the breakpoint icon at line 10.
1649
1650 @item @emph{Resuming execution from a breakpoint}
1651
1652 Select @code{Debug}, then @code{Continue}.
1653 The program will reach the next iteration of the loop, and
1654 wait for input after displaying the prompt.
1655 This time, just hit the @kbd{Enter} key.
1656 The value of @code{N} will be 0, and the program will terminate.
1657 The console window will disappear.
1658 @end enumerate
1659 @end enumerate
1660 @end ifclear
1661
1662 @node The GNAT Compilation Model
1663 @chapter The GNAT Compilation Model
1664 @cindex GNAT compilation model
1665 @cindex Compilation model
1666
1667 @menu
1668 * Source Representation::
1669 * Foreign Language Representation::
1670 * File Naming Rules::
1671 * Using Other File Names::
1672 * Alternative File Naming Schemes::
1673 * Generating Object Files::
1674 * Source Dependencies::
1675 * The Ada Library Information Files::
1676 * Binding an Ada Program::
1677 * Mixed Language Programming::
1678 @ifclear vms
1679 * Building Mixed Ada & C++ Programs::
1680 * Comparison between GNAT and C/C++ Compilation Models::
1681 @end ifclear
1682 * Comparison between GNAT and Conventional Ada Library Models::
1683 @ifset vms
1684 * Placement of temporary files::
1685 @end ifset
1686 @end menu
1687
1688 @noindent
1689 This chapter describes the compilation model used by GNAT. Although
1690 similar to that used by other languages, such as C and C++, this model
1691 is substantially different from the traditional Ada compilation models,
1692 which are based on a library. The model is initially described without
1693 reference to the library-based model. If you have not previously used an
1694 Ada compiler, you need only read the first part of this chapter. The
1695 last section describes and discusses the differences between the GNAT
1696 model and the traditional Ada compiler models. If you have used other
1697 Ada compilers, this section will help you to understand those
1698 differences, and the advantages of the GNAT model.
1699
1700 @node Source Representation
1701 @section Source Representation
1702 @cindex Latin-1
1703
1704 @noindent
1705 Ada source programs are represented in standard text files, using
1706 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1707 7-bit ASCII set, plus additional characters used for
1708 representing foreign languages (@pxref{Foreign Language Representation}
1709 for support of non-USA character sets). The format effector characters
1710 are represented using their standard ASCII encodings, as follows:
1711
1712 @table @code
1713 @item VT
1714 @findex VT
1715 Vertical tab, @code{16#0B#}
1716
1717 @item HT
1718 @findex HT
1719 Horizontal tab, @code{16#09#}
1720
1721 @item CR
1722 @findex CR
1723 Carriage return, @code{16#0D#}
1724
1725 @item LF
1726 @findex LF
1727 Line feed, @code{16#0A#}
1728
1729 @item FF
1730 @findex FF
1731 Form feed, @code{16#0C#}
1732 @end table
1733
1734 @noindent
1735 Source files are in standard text file format. In addition, GNAT will
1736 recognize a wide variety of stream formats, in which the end of
1737 physical lines is marked by any of the following sequences:
1738 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1739 in accommodating files that are imported from other operating systems.
1740
1741 @cindex End of source file
1742 @cindex Source file, end
1743 @findex SUB
1744 The end of a source file is normally represented by the physical end of
1745 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1746 recognized as signalling the end of the source file. Again, this is
1747 provided for compatibility with other operating systems where this
1748 code is used to represent the end of file.
1749
1750 Each file contains a single Ada compilation unit, including any pragmas
1751 associated with the unit. For example, this means you must place a
1752 package declaration (a package @dfn{spec}) and the corresponding body in
1753 separate files. An Ada @dfn{compilation} (which is a sequence of
1754 compilation units) is represented using a sequence of files. Similarly,
1755 you will place each subunit or child unit in a separate file.
1756
1757 @node Foreign Language Representation
1758 @section Foreign Language Representation
1759
1760 @noindent
1761 GNAT supports the standard character sets defined in Ada as well as
1762 several other non-standard character sets for use in localized versions
1763 of the compiler (@pxref{Character Set Control}).
1764 @menu
1765 * Latin-1::
1766 * Other 8-Bit Codes::
1767 * Wide Character Encodings::
1768 @end menu
1769
1770 @node Latin-1
1771 @subsection Latin-1
1772 @cindex Latin-1
1773
1774 @noindent
1775 The basic character set is Latin-1. This character set is defined by ISO
1776 standard 8859, part 1. The lower half (character codes @code{16#00#}
1777 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1778 is used to represent additional characters. These include extended letters
1779 used by European languages, such as French accents, the vowels with umlauts
1780 used in German, and the extra letter A-ring used in Swedish.
1781
1782 @findex Ada.Characters.Latin_1
1783 For a complete list of Latin-1 codes and their encodings, see the source
1784 file of library unit @code{Ada.Characters.Latin_1} in file
1785 @file{a-chlat1.ads}.
1786 You may use any of these extended characters freely in character or
1787 string literals. In addition, the extended characters that represent
1788 letters can be used in identifiers.
1789
1790 @node Other 8-Bit Codes
1791 @subsection Other 8-Bit Codes
1792
1793 @noindent
1794 GNAT also supports several other 8-bit coding schemes:
1795
1796 @table @asis
1797 @item ISO 8859-2 (Latin-2)
1798 @cindex Latin-2
1799 @cindex ISO 8859-2
1800 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1801 equivalence.
1802
1803 @item ISO 8859-3 (Latin-3)
1804 @cindex Latin-3
1805 @cindex ISO 8859-3
1806 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1807 equivalence.
1808
1809 @item ISO 8859-4 (Latin-4)
1810 @cindex Latin-4
1811 @cindex ISO 8859-4
1812 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1813 equivalence.
1814
1815 @item ISO 8859-5 (Cyrillic)
1816 @cindex ISO 8859-5
1817 @cindex Cyrillic
1818 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1819 lowercase equivalence.
1820
1821 @item ISO 8859-15 (Latin-9)
1822 @cindex ISO 8859-15
1823 @cindex Latin-9
1824 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1825 lowercase equivalence
1826
1827 @item IBM PC (code page 437)
1828 @cindex code page 437
1829 This code page is the normal default for PCs in the U.S. It corresponds
1830 to the original IBM PC character set. This set has some, but not all, of
1831 the extended Latin-1 letters, but these letters do not have the same
1832 encoding as Latin-1. In this mode, these letters are allowed in
1833 identifiers with uppercase and lowercase equivalence.
1834
1835 @item IBM PC (code page 850)
1836 @cindex code page 850
1837 This code page is a modification of 437 extended to include all the
1838 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1839 mode, all these letters are allowed in identifiers with uppercase and
1840 lowercase equivalence.
1841
1842 @item Full Upper 8-bit
1843 Any character in the range 80-FF allowed in identifiers, and all are
1844 considered distinct. In other words, there are no uppercase and lowercase
1845 equivalences in this range. This is useful in conjunction with
1846 certain encoding schemes used for some foreign character sets (e.g.
1847 the typical method of representing Chinese characters on the PC).
1848
1849 @item No Upper-Half
1850 No upper-half characters in the range 80-FF are allowed in identifiers.
1851 This gives Ada 83 compatibility for identifier names.
1852 @end table
1853
1854 @noindent
1855 For precise data on the encodings permitted, and the uppercase and lowercase
1856 equivalences that are recognized, see the file @file{csets.adb} in
1857 the GNAT compiler sources. You will need to obtain a full source release
1858 of GNAT to obtain this file.
1859
1860 @node Wide Character Encodings
1861 @subsection Wide Character Encodings
1862
1863 @noindent
1864 GNAT allows wide character codes to appear in character and string
1865 literals, and also optionally in identifiers, by means of the following
1866 possible encoding schemes:
1867
1868 @table @asis
1869
1870 @item Hex Coding
1871 In this encoding, a wide character is represented by the following five
1872 character sequence:
1873
1874 @smallexample
1875 ESC a b c d
1876 @end smallexample
1877
1878 @noindent
1879 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1880 characters (using uppercase letters) of the wide character code. For
1881 example, ESC A345 is used to represent the wide character with code
1882 @code{16#A345#}.
1883 This scheme is compatible with use of the full Wide_Character set.
1884
1885 @item Upper-Half Coding
1886 @cindex Upper-Half Coding
1887 The wide character with encoding @code{16#abcd#} where the upper bit is on
1888 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1889 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1890 character, but is not required to be in the upper half. This method can
1891 be also used for shift-JIS or EUC, where the internal coding matches the
1892 external coding.
1893
1894 @item Shift JIS Coding
1895 @cindex Shift JIS Coding
1896 A wide character is represented by a two-character sequence,
1897 @code{16#ab#} and
1898 @code{16#cd#}, with the restrictions described for upper-half encoding as
1899 described above. The internal character code is the corresponding JIS
1900 character according to the standard algorithm for Shift-JIS
1901 conversion. Only characters defined in the JIS code set table can be
1902 used with this encoding method.
1903
1904 @item EUC Coding
1905 @cindex EUC Coding
1906 A wide character is represented by a two-character sequence
1907 @code{16#ab#} and
1908 @code{16#cd#}, with both characters being in the upper half. The internal
1909 character code is the corresponding JIS character according to the EUC
1910 encoding algorithm. Only characters defined in the JIS code set table
1911 can be used with this encoding method.
1912
1913 @item UTF-8 Coding
1914 A wide character is represented using
1915 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1916 10646-1/Am.2. Depending on the character value, the representation
1917 is a one, two, or three byte sequence:
1918 @smallexample
1919 @iftex
1920 @leftskip=.7cm
1921 @end iftex
1922 16#0000#-16#007f#: 2#0xxxxxxx#
1923 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1924 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1925
1926 @end smallexample
1927
1928 @noindent
1929 where the xxx bits correspond to the left-padded bits of the
1930 16-bit character value. Note that all lower half ASCII characters
1931 are represented as ASCII bytes and all upper half characters and
1932 other wide characters are represented as sequences of upper-half
1933 (The full UTF-8 scheme allows for encoding 31-bit characters as
1934 6-byte sequences, but in this implementation, all UTF-8 sequences
1935 of four or more bytes length will be treated as illegal).
1936 @item Brackets Coding
1937 In this encoding, a wide character is represented by the following eight
1938 character sequence:
1939
1940 @smallexample
1941 [ " a b c d " ]
1942 @end smallexample
1943
1944 @noindent
1945 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1946 characters (using uppercase letters) of the wide character code. For
1947 example, [``A345''] is used to represent the wide character with code
1948 @code{16#A345#}. It is also possible (though not required) to use the
1949 Brackets coding for upper half characters. For example, the code
1950 @code{16#A3#} can be represented as @code{[``A3'']}.
1951
1952 This scheme is compatible with use of the full Wide_Character set,
1953 and is also the method used for wide character encoding in the standard
1954 ACVC (Ada Compiler Validation Capability) test suite distributions.
1955
1956 @end table
1957
1958 @noindent
1959 Note: Some of these coding schemes do not permit the full use of the
1960 Ada character set. For example, neither Shift JIS, nor EUC allow the
1961 use of the upper half of the Latin-1 set.
1962
1963 @node File Naming Rules
1964 @section File Naming Rules
1965
1966 @noindent
1967 The default file name is determined by the name of the unit that the
1968 file contains. The name is formed by taking the full expanded name of
1969 the unit and replacing the separating dots with hyphens and using
1970 ^lowercase^uppercase^ for all letters.
1971
1972 An exception arises if the file name generated by the above rules starts
1973 with one of the characters
1974 @ifset vms
1975 A,G,I, or S,
1976 @end ifset
1977 @ifclear vms
1978 a,g,i, or s,
1979 @end ifclear
1980 and the second character is a
1981 minus. In this case, the character ^tilde^dollar sign^ is used in place
1982 of the minus. The reason for this special rule is to avoid clashes with
1983 the standard names for child units of the packages System, Ada,
1984 Interfaces, and GNAT, which use the prefixes
1985 @ifset vms
1986 S- A- I- and G-
1987 @end ifset
1988 @ifclear vms
1989 s- a- i- and g-
1990 @end ifclear
1991 respectively.
1992
1993 The file extension is @file{.ads} for a spec and
1994 @file{.adb} for a body. The following list shows some
1995 examples of these rules.
1996
1997 @table @file
1998 @item main.ads
1999 Main (spec)
2000 @item main.adb
2001 Main (body)
2002 @item arith_functions.ads
2003 Arith_Functions (package spec)
2004 @item arith_functions.adb
2005 Arith_Functions (package body)
2006 @item func-spec.ads
2007 Func.Spec (child package spec)
2008 @item func-spec.adb
2009 Func.Spec (child package body)
2010 @item main-sub.adb
2011 Sub (subunit of Main)
2012 @item ^a~bad.adb^A$BAD.ADB^
2013 A.Bad (child package body)
2014 @end table
2015
2016 @noindent
2017 Following these rules can result in excessively long
2018 file names if corresponding
2019 unit names are long (for example, if child units or subunits are
2020 heavily nested). An option is available to shorten such long file names
2021 (called file name ``krunching''). This may be particularly useful when
2022 programs being developed with GNAT are to be used on operating systems
2023 with limited file name lengths. @xref{Using gnatkr}.
2024
2025 Of course, no file shortening algorithm can guarantee uniqueness over
2026 all possible unit names; if file name krunching is used, it is your
2027 responsibility to ensure no name clashes occur. Alternatively you
2028 can specify the exact file names that you want used, as described
2029 in the next section. Finally, if your Ada programs are migrating from a
2030 compiler with a different naming convention, you can use the gnatchop
2031 utility to produce source files that follow the GNAT naming conventions.
2032 (For details @pxref{Renaming Files Using gnatchop}.)
2033
2034 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2035 systems, case is not significant. So for example on @code{Windows XP}
2036 if the canonical name is @code{main-sub.adb}, you can use the file name
2037 @code{Main-Sub.adb} instead. However, case is significant for other
2038 operating systems, so for example, if you want to use other than
2039 canonically cased file names on a Unix system, you need to follow
2040 the procedures described in the next section.
2041
2042 @node Using Other File Names
2043 @section Using Other File Names
2044 @cindex File names
2045
2046 @noindent
2047 In the previous section, we have described the default rules used by
2048 GNAT to determine the file name in which a given unit resides. It is
2049 often convenient to follow these default rules, and if you follow them,
2050 the compiler knows without being explicitly told where to find all
2051 the files it needs.
2052
2053 However, in some cases, particularly when a program is imported from
2054 another Ada compiler environment, it may be more convenient for the
2055 programmer to specify which file names contain which units. GNAT allows
2056 arbitrary file names to be used by means of the Source_File_Name pragma.
2057 The form of this pragma is as shown in the following examples:
2058 @cindex Source_File_Name pragma
2059
2060 @smallexample @c ada
2061 @cartouche
2062 pragma Source_File_Name (My_Utilities.Stacks,
2063   Spec_File_Name => "myutilst_a.ada");
2064 pragma Source_File_name (My_Utilities.Stacks,
2065   Body_File_Name => "myutilst.ada");
2066 @end cartouche
2067 @end smallexample
2068
2069 @noindent
2070 As shown in this example, the first argument for the pragma is the unit
2071 name (in this example a child unit). The second argument has the form
2072 of a named association. The identifier
2073 indicates whether the file name is for a spec or a body;
2074 the file name itself is given by a string literal.
2075
2076 The source file name pragma is a configuration pragma, which means that
2077 normally it will be placed in the @file{gnat.adc}
2078 file used to hold configuration
2079 pragmas that apply to a complete compilation environment.
2080 For more details on how the @file{gnat.adc} file is created and used
2081 see @ref{Handling of Configuration Pragmas}.
2082 @cindex @file{gnat.adc}
2083
2084 @ifclear vms
2085 GNAT allows completely arbitrary file names to be specified using the
2086 source file name pragma. However, if the file name specified has an
2087 extension other than @file{.ads} or @file{.adb} it is necessary to use
2088 a special syntax when compiling the file. The name in this case must be
2089 preceded by the special sequence @code{-x} followed by a space and the name
2090 of the language, here @code{ada}, as in:
2091
2092 @smallexample
2093 $ gcc -c -x ada peculiar_file_name.sim
2094 @end smallexample
2095 @end ifclear
2096
2097 @noindent
2098 @command{gnatmake} handles non-standard file names in the usual manner (the
2099 non-standard file name for the main program is simply used as the
2100 argument to gnatmake). Note that if the extension is also non-standard,
2101 then it must be included in the gnatmake command, it may not be omitted.
2102
2103 @node Alternative File Naming Schemes
2104 @section Alternative File Naming Schemes
2105 @cindex File naming schemes, alternative
2106 @cindex File names
2107
2108 In the previous section, we described the use of the @code{Source_File_Name}
2109 pragma to allow arbitrary names to be assigned to individual source files.
2110 However, this approach requires one pragma for each file, and especially in
2111 large systems can result in very long @file{gnat.adc} files, and also create
2112 a maintenance problem.
2113
2114 GNAT also provides a facility for specifying systematic file naming schemes
2115 other than the standard default naming scheme previously described. An
2116 alternative scheme for naming is specified by the use of
2117 @code{Source_File_Name} pragmas having the following format:
2118 @cindex Source_File_Name pragma
2119
2120 @smallexample @c ada
2121 pragma Source_File_Name (
2122    Spec_File_Name  => FILE_NAME_PATTERN
2123  [,Casing          => CASING_SPEC]
2124  [,Dot_Replacement => STRING_LITERAL]);
2125
2126 pragma Source_File_Name (
2127    Body_File_Name  => FILE_NAME_PATTERN
2128  [,Casing          => CASING_SPEC]
2129  [,Dot_Replacement => STRING_LITERAL]);
2130
2131 pragma Source_File_Name (
2132    Subunit_File_Name  => FILE_NAME_PATTERN
2133  [,Casing             => CASING_SPEC]
2134  [,Dot_Replacement    => STRING_LITERAL]);
2135
2136 FILE_NAME_PATTERN ::= STRING_LITERAL
2137 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2138 @end smallexample
2139
2140 @noindent
2141 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2142 It contains a single asterisk character, and the unit name is substituted
2143 systematically for this asterisk. The optional parameter
2144 @code{Casing} indicates
2145 whether the unit name is to be all upper-case letters, all lower-case letters,
2146 or mixed-case. If no
2147 @code{Casing} parameter is used, then the default is all
2148 ^lower-case^upper-case^.
2149
2150 The optional @code{Dot_Replacement} string is used to replace any periods
2151 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2152 argument is used then separating dots appear unchanged in the resulting
2153 file name.
2154 Although the above syntax indicates that the
2155 @code{Casing} argument must appear
2156 before the @code{Dot_Replacement} argument, but it
2157 is also permissible to write these arguments in the opposite order.
2158
2159 As indicated, it is possible to specify different naming schemes for
2160 bodies, specs, and subunits. Quite often the rule for subunits is the
2161 same as the rule for bodies, in which case, there is no need to give
2162 a separate @code{Subunit_File_Name} rule, and in this case the
2163 @code{Body_File_name} rule is used for subunits as well.
2164
2165 The separate rule for subunits can also be used to implement the rather
2166 unusual case of a compilation environment (e.g. a single directory) which
2167 contains a subunit and a child unit with the same unit name. Although
2168 both units cannot appear in the same partition, the Ada Reference Manual
2169 allows (but does not require) the possibility of the two units coexisting
2170 in the same environment.
2171
2172 The file name translation works in the following steps:
2173
2174 @itemize @bullet
2175
2176 @item
2177 If there is a specific @code{Source_File_Name} pragma for the given unit,
2178 then this is always used, and any general pattern rules are ignored.
2179
2180 @item
2181 If there is a pattern type @code{Source_File_Name} pragma that applies to
2182 the unit, then the resulting file name will be used if the file exists. If
2183 more than one pattern matches, the latest one will be tried first, and the
2184 first attempt resulting in a reference to a file that exists will be used.
2185
2186 @item
2187 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2188 for which the corresponding file exists, then the standard GNAT default
2189 naming rules are used.
2190
2191 @end itemize
2192
2193 @noindent
2194 As an example of the use of this mechanism, consider a commonly used scheme
2195 in which file names are all lower case, with separating periods copied
2196 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2197 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2198 two pragmas appear:
2199
2200 @smallexample @c ada
2201 pragma Source_File_Name
2202   (Spec_File_Name => "*.1.ada");
2203 pragma Source_File_Name
2204   (Body_File_Name => "*.2.ada");
2205 @end smallexample
2206
2207 @noindent
2208 The default GNAT scheme is actually implemented by providing the following
2209 default pragmas internally:
2210
2211 @smallexample @c ada
2212 pragma Source_File_Name
2213   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2214 pragma Source_File_Name
2215   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2216 @end smallexample
2217
2218 @noindent
2219 Our final example implements a scheme typically used with one of the
2220 Ada 83 compilers, where the separator character for subunits was ``__''
2221 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2222 by adding @file{.ADA}, and subunits by
2223 adding @file{.SEP}. All file names were
2224 upper case. Child units were not present of course since this was an
2225 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2226 the same double underscore separator for child units.
2227
2228 @smallexample @c ada
2229 pragma Source_File_Name
2230   (Spec_File_Name => "*_.ADA",
2231    Dot_Replacement => "__",
2232    Casing = Uppercase);
2233 pragma Source_File_Name
2234   (Body_File_Name => "*.ADA",
2235    Dot_Replacement => "__",
2236    Casing = Uppercase);
2237 pragma Source_File_Name
2238   (Subunit_File_Name => "*.SEP",
2239    Dot_Replacement => "__",
2240    Casing = Uppercase);
2241 @end smallexample
2242
2243 @node Generating Object Files
2244 @section Generating Object Files
2245
2246 @noindent
2247 An Ada program consists of a set of source files, and the first step in
2248 compiling the program is to generate the corresponding object files.
2249 These are generated by compiling a subset of these source files.
2250 The files you need to compile are the following:
2251
2252 @itemize @bullet
2253 @item
2254 If a package spec has no body, compile the package spec to produce the
2255 object file for the package.
2256
2257 @item
2258 If a package has both a spec and a body, compile the body to produce the
2259 object file for the package. The source file for the package spec need
2260 not be compiled in this case because there is only one object file, which
2261 contains the code for both the spec and body of the package.
2262
2263 @item
2264 For a subprogram, compile the subprogram body to produce the object file
2265 for the subprogram. The spec, if one is present, is as usual in a
2266 separate file, and need not be compiled.
2267
2268 @item
2269 @cindex Subunits
2270 In the case of subunits, only compile the parent unit. A single object
2271 file is generated for the entire subunit tree, which includes all the
2272 subunits.
2273
2274 @item
2275 Compile child units independently of their parent units
2276 (though, of course, the spec of all the ancestor unit must be present in order
2277 to compile a child unit).
2278
2279 @item
2280 @cindex Generics
2281 Compile generic units in the same manner as any other units. The object
2282 files in this case are small dummy files that contain at most the
2283 flag used for elaboration checking. This is because GNAT always handles generic
2284 instantiation by means of macro expansion. However, it is still necessary to
2285 compile generic units, for dependency checking and elaboration purposes.
2286 @end itemize
2287
2288 @noindent
2289 The preceding rules describe the set of files that must be compiled to
2290 generate the object files for a program. Each object file has the same
2291 name as the corresponding source file, except that the extension is
2292 @file{.o} as usual.
2293
2294 You may wish to compile other files for the purpose of checking their
2295 syntactic and semantic correctness. For example, in the case where a
2296 package has a separate spec and body, you would not normally compile the
2297 spec. However, it is convenient in practice to compile the spec to make
2298 sure it is error-free before compiling clients of this spec, because such
2299 compilations will fail if there is an error in the spec.
2300
2301 GNAT provides an option for compiling such files purely for the
2302 purposes of checking correctness; such compilations are not required as
2303 part of the process of building a program. To compile a file in this
2304 checking mode, use the @option{-gnatc} switch.
2305
2306 @node Source Dependencies
2307 @section Source Dependencies
2308
2309 @noindent
2310 A given object file clearly depends on the source file which is compiled
2311 to produce it. Here we are using @dfn{depends} in the sense of a typical
2312 @code{make} utility; in other words, an object file depends on a source
2313 file if changes to the source file require the object file to be
2314 recompiled.
2315 In addition to this basic dependency, a given object may depend on
2316 additional source files as follows:
2317
2318 @itemize @bullet
2319 @item
2320 If a file being compiled @code{with}'s a unit @var{X}, the object file
2321 depends on the file containing the spec of unit @var{X}. This includes
2322 files that are @code{with}'ed implicitly either because they are parents
2323 of @code{with}'ed child units or they are run-time units required by the
2324 language constructs used in a particular unit.
2325
2326 @item
2327 If a file being compiled instantiates a library level generic unit, the
2328 object file depends on both the spec and body files for this generic
2329 unit.
2330
2331 @item
2332 If a file being compiled instantiates a generic unit defined within a
2333 package, the object file depends on the body file for the package as
2334 well as the spec file.
2335
2336 @item
2337 @findex Inline
2338 @cindex @option{-gnatn} switch
2339 If a file being compiled contains a call to a subprogram for which
2340 pragma @code{Inline} applies and inlining is activated with the
2341 @option{-gnatn} switch, the object file depends on the file containing the
2342 body of this subprogram as well as on the file containing the spec. Note
2343 that for inlining to actually occur as a result of the use of this switch,
2344 it is necessary to compile in optimizing mode.
2345
2346 @cindex @option{-gnatN} switch
2347 The use of @option{-gnatN} activates a more extensive inlining optimization
2348 that is performed by the front end of the compiler. This inlining does
2349 not require that the code generation be optimized. Like @option{-gnatn},
2350 the use of this switch generates additional dependencies.
2351 Note that
2352 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2353 to specify both options.
2354
2355 @item
2356 If an object file @file{O} depends on the proper body of a subunit through
2357 inlining or instantiation, it depends on the parent unit of the subunit.
2358 This means that any modification of the parent unit or one of its subunits
2359 affects the compilation of @file{O}.
2360
2361 @item
2362 The object file for a parent unit depends on all its subunit body files.
2363
2364 @item
2365 The previous two rules meant that for purposes of computing dependencies and
2366 recompilation, a body and all its subunits are treated as an indivisible whole.
2367
2368 @noindent
2369 These rules are applied transitively: if unit @code{A} @code{with}'s
2370 unit @code{B}, whose elaboration calls an inlined procedure in package
2371 @code{C}, the object file for unit @code{A} will depend on the body of
2372 @code{C}, in file @file{c.adb}.
2373
2374 The set of dependent files described by these rules includes all the
2375 files on which the unit is semantically dependent, as dictated by the
2376 Ada language standard. However, it is a superset of what the
2377 standard describes, because it includes generic, inline, and subunit
2378 dependencies.
2379
2380 An object file must be recreated by recompiling the corresponding source
2381 file if any of the source files on which it depends are modified. For
2382 example, if the @code{make} utility is used to control compilation,
2383 the rule for an Ada object file must mention all the source files on
2384 which the object file depends, according to the above definition.
2385 The determination of the necessary
2386 recompilations is done automatically when one uses @command{gnatmake}.
2387 @end itemize
2388
2389 @node The Ada Library Information Files
2390 @section The Ada Library Information Files
2391 @cindex Ada Library Information files
2392 @cindex @file{ALI} files
2393
2394 @noindent
2395 Each compilation actually generates two output files. The first of these
2396 is the normal object file that has a @file{.o} extension. The second is a
2397 text file containing full dependency information. It has the same
2398 name as the source file, but an @file{.ali} extension.
2399 This file is known as the Ada Library Information (@file{ALI}) file.
2400 The following information is contained in the @file{ALI} file.
2401
2402 @itemize @bullet
2403 @item
2404 Version information (indicates which version of GNAT was used to compile
2405 the unit(s) in question)
2406
2407 @item
2408 Main program information (including priority and time slice settings,
2409 as well as the wide character encoding used during compilation).
2410
2411 @item
2412 List of arguments used in the @command{gcc} command for the compilation
2413
2414 @item
2415 Attributes of the unit, including configuration pragmas used, an indication
2416 of whether the compilation was successful, exception model used etc.
2417
2418 @item
2419 A list of relevant restrictions applying to the unit (used for consistency)
2420 checking.
2421
2422 @item
2423 Categorization information (e.g. use of pragma @code{Pure}).
2424
2425 @item
2426 Information on all @code{with}'ed units, including presence of
2427 @code{Elaborate} or @code{Elaborate_All} pragmas.
2428
2429 @item
2430 Information from any @code{Linker_Options} pragmas used in the unit
2431
2432 @item
2433 Information on the use of @code{Body_Version} or @code{Version}
2434 attributes in the unit.
2435
2436 @item
2437 Dependency information. This is a list of files, together with
2438 time stamp and checksum information. These are files on which
2439 the unit depends in the sense that recompilation is required
2440 if any of these units are modified.
2441
2442 @item
2443 Cross-reference data. Contains information on all entities referenced
2444 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2445 provide cross-reference information.
2446
2447 @end itemize
2448
2449 @noindent
2450 For a full detailed description of the format of the @file{ALI} file,
2451 see the source of the body of unit @code{Lib.Writ}, contained in file
2452 @file{lib-writ.adb} in the GNAT compiler sources.
2453
2454 @node Binding an Ada Program
2455 @section Binding an Ada Program
2456
2457 @noindent
2458 When using languages such as C and C++, once the source files have been
2459 compiled the only remaining step in building an executable program
2460 is linking the object modules together. This means that it is possible to
2461 link an inconsistent version of a program, in which two units have
2462 included different versions of the same header.
2463
2464 The rules of Ada do not permit such an inconsistent program to be built.
2465 For example, if two clients have different versions of the same package,
2466 it is illegal to build a program containing these two clients.
2467 These rules are enforced by the GNAT binder, which also determines an
2468 elaboration order consistent with the Ada rules.
2469
2470 The GNAT binder is run after all the object files for a program have
2471 been created. It is given the name of the main program unit, and from
2472 this it determines the set of units required by the program, by reading the
2473 corresponding ALI files. It generates error messages if the program is
2474 inconsistent or if no valid order of elaboration exists.
2475
2476 If no errors are detected, the binder produces a main program, in Ada by
2477 default, that contains calls to the elaboration procedures of those
2478 compilation unit that require them, followed by
2479 a call to the main program. This Ada program is compiled to generate the
2480 object file for the main program. The name of
2481 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2482 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2483 main program unit.
2484
2485 Finally, the linker is used to build the resulting executable program,
2486 using the object from the main program from the bind step as well as the
2487 object files for the Ada units of the program.
2488
2489 @node Mixed Language Programming
2490 @section Mixed Language Programming
2491 @cindex Mixed Language Programming
2492
2493 @noindent
2494 This section describes how to develop a mixed-language program,
2495 specifically one that comprises units in both Ada and C.
2496
2497 @menu
2498 * Interfacing to C::
2499 * Calling Conventions::
2500 @end menu
2501
2502 @node Interfacing to C
2503 @subsection Interfacing to C
2504 @noindent
2505 Interfacing Ada with a foreign language such as C involves using
2506 compiler directives to import and/or export entity definitions in each
2507 language---using @code{extern} statements in C, for instance, and the
2508 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2509 A full treatment of these topics is provided in Appendix B, section 1
2510 of the Ada Reference Manual.
2511
2512 There are two ways to build a program using GNAT that contains some Ada
2513 sources and some foreign language sources, depending on whether or not
2514 the main subprogram is written in Ada.  Here is a source example with
2515 the main subprogram in Ada:
2516
2517 @smallexample
2518 /* file1.c */
2519 #include <stdio.h>
2520
2521 void print_num (int num)
2522 @{
2523   printf ("num is %d.\n", num);
2524   return;
2525 @}
2526
2527 /* file2.c */
2528
2529 /* num_from_Ada is declared in my_main.adb */
2530 extern int num_from_Ada;
2531
2532 int get_num (void)
2533 @{
2534   return num_from_Ada;
2535 @}
2536 @end smallexample
2537
2538 @smallexample @c ada
2539 --  my_main.adb
2540 procedure My_Main is
2541
2542    --  Declare then export an Integer entity called num_from_Ada
2543    My_Num : Integer := 10;
2544    pragma Export (C, My_Num, "num_from_Ada");
2545
2546    --  Declare an Ada function spec for Get_Num, then use
2547    --  C function get_num for the implementation.
2548    function Get_Num return Integer;
2549    pragma Import (C, Get_Num, "get_num");
2550
2551    --  Declare an Ada procedure spec for Print_Num, then use
2552    --  C function print_num for the implementation.
2553    procedure Print_Num (Num : Integer);
2554    pragma Import (C, Print_Num, "print_num");
2555
2556 begin
2557    Print_Num (Get_Num);
2558 end My_Main;
2559 @end smallexample
2560
2561 @enumerate
2562 @item
2563 To build this example, first compile the foreign language files to
2564 generate object files:
2565 @smallexample
2566 ^gcc -c file1.c^gcc -c FILE1.C^
2567 ^gcc -c file2.c^gcc -c FILE2.C^
2568 @end smallexample
2569
2570 @item
2571 Then, compile the Ada units to produce a set of object files and ALI
2572 files:
2573 @smallexample
2574 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2575 @end smallexample
2576
2577 @item
2578 Run the Ada binder on the Ada main program:
2579 @smallexample
2580 gnatbind my_main.ali
2581 @end smallexample
2582
2583 @item
2584 Link the Ada main program, the Ada objects and the other language
2585 objects:
2586 @smallexample
2587 gnatlink my_main.ali file1.o file2.o
2588 @end smallexample
2589 @end enumerate
2590
2591 The last three steps can be grouped in a single command:
2592 @smallexample
2593 gnatmake my_main.adb -largs file1.o file2.o
2594 @end smallexample
2595
2596 @cindex Binder output file
2597 @noindent
2598 If the main program is in a language other than Ada, then you may have
2599 more than one entry point into the Ada subsystem. You must use a special
2600 binder option to generate callable routines that initialize and
2601 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2602 Calls to the initialization and finalization routines must be inserted
2603 in the main program, or some other appropriate point in the code. The
2604 call to initialize the Ada units must occur before the first Ada
2605 subprogram is called, and the call to finalize the Ada units must occur
2606 after the last Ada subprogram returns. The binder will place the
2607 initialization and finalization subprograms into the
2608 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2609 sources.  To illustrate, we have the following example:
2610
2611 @smallexample
2612 /* main.c */
2613 extern void adainit (void);
2614 extern void adafinal (void);
2615 extern int add (int, int);
2616 extern int sub (int, int);
2617
2618 int main (int argc, char *argv[])
2619 @{
2620   int a = 21, b = 7;
2621
2622   adainit();
2623
2624   /* Should print "21 + 7 = 28" */
2625   printf ("%d + %d = %d\n", a, b, add (a, b));
2626   /* Should print "21 - 7 = 14" */
2627   printf ("%d - %d = %d\n", a, b, sub (a, b));
2628
2629   adafinal();
2630 @}
2631 @end smallexample
2632
2633 @smallexample @c ada
2634 --  unit1.ads
2635 package Unit1 is
2636    function Add (A, B : Integer) return Integer;
2637    pragma Export (C, Add, "add");
2638 end Unit1;
2639
2640 --  unit1.adb
2641 package body Unit1 is
2642    function Add (A, B : Integer) return Integer is
2643    begin
2644       return A + B;
2645    end Add;
2646 end Unit1;
2647
2648 --  unit2.ads
2649 package Unit2 is
2650    function Sub (A, B : Integer) return Integer;
2651    pragma Export (C, Sub, "sub");
2652 end Unit2;
2653
2654 --  unit2.adb
2655 package body Unit2 is
2656    function Sub (A, B : Integer) return Integer is
2657    begin
2658       return A - B;
2659    end Sub;
2660 end Unit2;
2661 @end smallexample
2662
2663 @enumerate
2664 @item
2665 The build procedure for this application is similar to the last
2666 example's.  First, compile the foreign language files to generate object
2667 files:
2668 @smallexample
2669 ^gcc -c main.c^gcc -c main.c^
2670 @end smallexample
2671
2672 @item
2673 Next, compile the Ada units to produce a set of object files and ALI
2674 files:
2675 @smallexample
2676 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2677 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2678 @end smallexample
2679
2680 @item
2681 Run the Ada binder on every generated ALI file.  Make sure to use the
2682 @option{-n} option to specify a foreign main program:
2683 @smallexample
2684 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2685 @end smallexample
2686
2687 @item
2688 Link the Ada main program, the Ada objects and the foreign language
2689 objects. You need only list the last ALI file here:
2690 @smallexample
2691 gnatlink unit2.ali main.o -o exec_file
2692 @end smallexample
2693
2694 This procedure yields a binary executable called @file{exec_file}.
2695 @end enumerate
2696
2697 @noindent
2698 Depending on the circumstances (for example when your non-Ada main object
2699 does not provide symbol @code{main}), you may also need to instruct the
2700 GNAT linker not to include the standard startup objects by passing the
2701 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2702
2703 @node Calling Conventions
2704 @subsection Calling Conventions
2705 @cindex Foreign Languages
2706 @cindex Calling Conventions
2707 GNAT follows standard calling sequence conventions and will thus interface
2708 to any other language that also follows these conventions. The following
2709 Convention identifiers are recognized by GNAT:
2710
2711 @table @code
2712 @cindex Interfacing to Ada
2713 @cindex Other Ada compilers
2714 @cindex Convention Ada
2715 @item Ada
2716 This indicates that the standard Ada calling sequence will be
2717 used and all Ada data items may be passed without any limitations in the
2718 case where GNAT is used to generate both the caller and callee. It is also
2719 possible to mix GNAT generated code and code generated by another Ada
2720 compiler. In this case, the data types should be restricted to simple
2721 cases, including primitive types. Whether complex data types can be passed
2722 depends on the situation. Probably it is safe to pass simple arrays, such
2723 as arrays of integers or floats. Records may or may not work, depending
2724 on whether both compilers lay them out identically. Complex structures
2725 involving variant records, access parameters, tasks, or protected types,
2726 are unlikely to be able to be passed.
2727
2728 Note that in the case of GNAT running
2729 on a platform that supports HP Ada 83, a higher degree of compatibility
2730 can be guaranteed, and in particular records are layed out in an identical
2731 manner in the two compilers. Note also that if output from two different
2732 compilers is mixed, the program is responsible for dealing with elaboration
2733 issues. Probably the safest approach is to write the main program in the
2734 version of Ada other than GNAT, so that it takes care of its own elaboration
2735 requirements, and then call the GNAT-generated adainit procedure to ensure
2736 elaboration of the GNAT components. Consult the documentation of the other
2737 Ada compiler for further details on elaboration.
2738
2739 However, it is not possible to mix the tasking run time of GNAT and
2740 HP Ada 83, All the tasking operations must either be entirely within
2741 GNAT compiled sections of the program, or entirely within HP Ada 83
2742 compiled sections of the program.
2743
2744 @cindex Interfacing to Assembly
2745 @cindex Convention Assembler
2746 @item Assembler
2747 Specifies assembler as the convention. In practice this has the
2748 same effect as convention Ada (but is not equivalent in the sense of being
2749 considered the same convention).
2750
2751 @cindex Convention Asm
2752 @findex Asm
2753 @item Asm
2754 Equivalent to Assembler.
2755
2756 @cindex Interfacing to COBOL
2757 @cindex Convention COBOL
2758 @findex COBOL
2759 @item COBOL
2760 Data will be passed according to the conventions described
2761 in section B.4 of the Ada Reference Manual.
2762
2763 @findex C
2764 @cindex Interfacing to C
2765 @cindex Convention C
2766 @item C
2767 Data will be passed according to the conventions described
2768 in section B.3 of the Ada Reference Manual.
2769
2770 A note on interfacing to a C ``varargs'' function:
2771 @findex C varargs function
2772 @cindex Interfacing to C varargs function
2773 @cindex varargs function interfaces
2774
2775 @itemize @bullet
2776 @item
2777 In C, @code{varargs} allows a function to take a variable number of
2778 arguments. There is no direct equivalent in this to Ada. One
2779 approach that can be used is to create a C wrapper for each
2780 different profile and then interface to this C wrapper. For
2781 example, to print an @code{int} value using @code{printf},
2782 create a C function @code{printfi} that takes two arguments, a
2783 pointer to a string and an int, and calls @code{printf}.
2784 Then in the Ada program, use pragma @code{Import} to
2785 interface to @code{printfi}.
2786
2787 @item
2788 It may work on some platforms to directly interface to
2789 a @code{varargs} function by providing a specific Ada profile
2790 for a particular call. However, this does not work on
2791 all platforms, since there is no guarantee that the
2792 calling sequence for a two argument normal C function
2793 is the same as for calling a @code{varargs} C function with
2794 the same two arguments.
2795 @end itemize
2796
2797 @cindex Convention Default
2798 @findex Default
2799 @item Default
2800 Equivalent to C.
2801
2802 @cindex Convention External
2803 @findex External
2804 @item External
2805 Equivalent to C.
2806
2807 @ifclear vms
2808 @findex C++
2809 @cindex Interfacing to C++
2810 @cindex Convention C++
2811 @item C_Plus_Plus (or CPP)
2812 This stands for C++. For most purposes this is identical to C.
2813 See the separate description of the specialized GNAT pragmas relating to
2814 C++ interfacing for further details.
2815 @end ifclear
2816
2817 @findex Fortran
2818 @cindex Interfacing to Fortran
2819 @cindex Convention Fortran
2820 @item Fortran
2821 Data will be passed according to the conventions described
2822 in section B.5 of the Ada Reference Manual.
2823
2824 @item Intrinsic
2825 This applies to an intrinsic operation, as defined in the Ada
2826 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2827 this means that the body of the subprogram is provided by the compiler itself,
2828 usually by means of an efficient code sequence, and that the user does not
2829 supply an explicit body for it. In an application program, the pragma can
2830 only be applied to the following two sets of names, which the GNAT compiler
2831 recognizes.
2832
2833 @itemize @bullet
2834 @item
2835 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2836 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2837 two formal parameters. The
2838 first one must be a signed integer type or a modular type with a binary
2839 modulus, and the second parameter must be of type Natural.
2840 The return type must be the same as the type of the first argument. The size
2841 of this type can only be 8, 16, 32, or 64.
2842 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2843 The corresponding operator declaration must have parameters and result type
2844 that have the same root numeric type (for example, all three are long_float
2845 types). This simplifies the definition of operations that use type checking
2846 to perform dimensional checks:
2847
2848 @smallexample @c ada
2849 type Distance is new Long_Float;
2850 type Time     is new Long_Float;
2851 type Velocity is new Long_Float;
2852 function "/" (D : Distance; T : Time)
2853   return Velocity;
2854 pragma Import (Intrinsic, "/");
2855 @end smallexample
2856
2857 @noindent
2858 This common idiom is often programmed with a generic definition and an
2859 explicit body. The pragma makes it simpler to introduce such declarations.
2860 It incurs no overhead in compilation time or code size, because it is
2861 implemented as a single machine instruction.
2862 @end itemize
2863 @noindent
2864
2865 @ifset unw
2866 @findex Stdcall
2867 @cindex Convention Stdcall
2868 @item Stdcall
2869 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2870 and specifies that the @code{Stdcall} calling sequence will be used,
2871 as defined by the NT API. Nevertheless, to ease building
2872 cross-platform bindings this convention will be handled as a @code{C} calling
2873 convention on non Windows platforms.
2874
2875 @findex DLL
2876 @cindex Convention DLL
2877 @item DLL
2878 This is equivalent to @code{Stdcall}.
2879
2880 @findex Win32
2881 @cindex Convention Win32
2882 @item Win32
2883 This is equivalent to @code{Stdcall}.
2884 @end ifset
2885
2886 @findex Stubbed
2887 @cindex Convention Stubbed
2888 @item Stubbed
2889 This is a special convention that indicates that the compiler
2890 should provide a stub body that raises @code{Program_Error}.
2891 @end table
2892
2893 @noindent
2894 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2895 that can be used to parametrize conventions and allow additional synonyms
2896 to be specified. For example if you have legacy code in which the convention
2897 identifier Fortran77 was used for Fortran, you can use the configuration
2898 pragma:
2899
2900 @smallexample @c ada
2901 pragma Convention_Identifier (Fortran77, Fortran);
2902 @end smallexample
2903
2904 @noindent
2905 And from now on the identifier Fortran77 may be used as a convention
2906 identifier (for example in an @code{Import} pragma) with the same
2907 meaning as Fortran.
2908
2909 @ifclear vms
2910 @node Building Mixed Ada & C++ Programs
2911 @section Building Mixed Ada and C++ Programs
2912
2913 @noindent
2914 A programmer inexperienced with mixed-language development may find that
2915 building an application containing both Ada and C++ code can be a
2916 challenge.  This section gives a few
2917 hints that should make this task easier. The first section addresses
2918 the differences between interfacing with C and interfacing with C++.
2919 The second section
2920 looks into the delicate problem of linking the complete application from
2921 its Ada and C++ parts. The last section gives some hints on how the GNAT
2922 run-time library can be adapted in order to allow inter-language dispatching
2923 with a new C++ compiler.
2924
2925 @menu
2926 * Interfacing to C++::
2927 * Linking a Mixed C++ & Ada Program::
2928 * A Simple Example::
2929 * Interfacing with C++ at the Class Level::
2930 @end menu
2931
2932 @node Interfacing to C++
2933 @subsection Interfacing to C++
2934
2935 @noindent
2936 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2937 generating code that is compatible with the G++ Application Binary
2938 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2939
2940 @noindent
2941 Interfacing can be done at 3 levels: simple data, subprograms, and
2942 classes. In the first two cases, GNAT offers a specific @var{Convention
2943 C_Plus_Plus} (or @var{CPP}) that behaves exactly like @var{Convention C}.
2944 Usually, C++ mangles the names of subprograms, and currently, GNAT does
2945 not provide any help to solve the demangling problem. This problem can be
2946 addressed in two ways:
2947 @itemize @bullet
2948 @item
2949 by modifying the C++ code in order to force a C convention using
2950 the @code{extern "C"} syntax.
2951
2952 @item
2953 by figuring out the mangled name and use it as the Link_Name argument of
2954 the pragma import.
2955 @end itemize
2956
2957 @noindent
2958 Interfacing at the class level can be achieved by using the GNAT specific
2959 pragmas such as @code{CPP_Constructor}. See the GNAT Reference Manual for
2960 additional information.
2961
2962 @node Linking a Mixed C++ & Ada Program
2963 @subsection Linking a Mixed C++ & Ada Program
2964
2965 @noindent
2966 Usually the linker of the C++ development system must be used to link
2967 mixed applications because most C++ systems will resolve elaboration
2968 issues (such as calling constructors on global class instances)
2969 transparently during the link phase. GNAT has been adapted to ease the
2970 use of a foreign linker for the last phase. Three cases can be
2971 considered:
2972 @enumerate
2973
2974 @item
2975 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2976 The C++ linker can simply be called by using the C++ specific driver
2977 called @code{c++}. Note that this setup is not very common because it
2978 may involve recompiling the whole GCC tree from sources, which makes it
2979 harder to upgrade the compilation system for one language without
2980 destabilizing the other.
2981
2982 @smallexample
2983 $ c++ -c file1.C
2984 $ c++ -c file2.C
2985 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
2986 @end smallexample
2987
2988 @item
2989 Using GNAT and G++ from two different GCC installations: If both
2990 compilers are on the PATH, the previous method may be used. It is
2991 important to note that environment variables such as C_INCLUDE_PATH,
2992 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
2993 at the same time and may make one of the two compilers operate
2994 improperly if set during invocation of the wrong compiler.  It is also
2995 very important that the linker uses the proper @file{libgcc.a} GCC
2996 library -- that is, the one from the C++ compiler installation. The
2997 implicit link command as suggested in the gnatmake command from the
2998 former example can be replaced by an explicit link command with the
2999 full-verbosity option in order to verify which library is used:
3000 @smallexample
3001 $ gnatbind ada_unit
3002 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3003 @end smallexample
3004 If there is a problem due to interfering environment variables, it can
3005 be worked around by using an intermediate script. The following example
3006 shows the proper script to use when GNAT has not been installed at its
3007 default location and g++ has been installed at its default location:
3008
3009 @smallexample
3010 $ cat ./my_script
3011 #!/bin/sh
3012 unset BINUTILS_ROOT
3013 unset GCC_ROOT
3014 c++ $*
3015 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3016 @end smallexample
3017
3018 @item
3019 Using a non-GNU C++ compiler: The commands previously described can be
3020 used to insure that the C++ linker is used. Nonetheless, you need to add
3021 a few more parameters to the link command line, depending on the exception
3022 mechanism used.
3023
3024 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3025 to the libgcc libraries are required:
3026
3027 @smallexample
3028 $ cat ./my_script
3029 #!/bin/sh
3030 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3031 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3032 @end smallexample
3033
3034 Where CC is the name of the non-GNU C++ compiler.
3035
3036 If the @code{zero cost} exception mechanism is used, and the platform
3037 supports automatic registration of exception tables (e.g. Solaris or IRIX),
3038 paths to more objects are required:
3039
3040 @smallexample
3041 $ cat ./my_script
3042 #!/bin/sh
3043 CC `gcc -print-file-name=crtbegin.o` $* \
3044 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3045 `gcc -print-file-name=crtend.o`
3046 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3047 @end smallexample
3048
3049 If the @code{zero cost} exception mechanism is used, and the platform
3050 doesn't support automatic registration of exception tables (e.g. HP-UX,
3051 Tru64 or AIX), the simple approach described above will not work and
3052 a pre-linking phase using GNAT will be necessary.
3053
3054 @end enumerate
3055
3056 @node A Simple Example
3057 @subsection  A Simple Example
3058 @noindent
3059 The following example, provided as part of the GNAT examples, shows how
3060 to achieve procedural interfacing between Ada and C++ in both
3061 directions. The C++ class A has two methods. The first method is exported
3062 to Ada by the means of an extern C wrapper function. The second method
3063 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3064 a limited record with a layout comparable to the C++ class. The Ada
3065 subprogram, in turn, calls the C++ method. So, starting from the C++
3066 main program, the process passes back and forth between the two
3067 languages.
3068
3069 @noindent
3070 Here are the compilation commands:
3071 @smallexample
3072 $ gnatmake -c simple_cpp_interface
3073 $ c++ -c cpp_main.C
3074 $ c++ -c ex7.C
3075 $ gnatbind -n simple_cpp_interface
3076 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3077       -lstdc++ ex7.o cpp_main.o
3078 @end smallexample
3079
3080 @noindent
3081 Here are the corresponding sources:
3082 @smallexample
3083
3084 //cpp_main.C
3085
3086 #include "ex7.h"
3087
3088 extern "C" @{
3089   void adainit (void);
3090   void adafinal (void);
3091   void method1 (A *t);
3092 @}
3093
3094 void method1 (A *t)
3095 @{
3096   t->method1 ();
3097 @}
3098
3099 int main ()
3100 @{
3101   A obj;
3102   adainit ();
3103   obj.method2 (3030);
3104   adafinal ();
3105 @}
3106
3107 //ex7.h
3108
3109 class Origin @{
3110  public:
3111   int o_value;
3112 @};
3113 class A : public Origin @{
3114  public:
3115   void method1 (void);
3116   void method2 (int v);
3117   A();
3118   int   a_value;
3119 @};
3120
3121 //ex7.C
3122
3123 #include "ex7.h"
3124 #include <stdio.h>
3125
3126 extern "C" @{ void ada_method2 (A *t, int v);@}
3127
3128 void A::method1 (void)
3129 @{
3130   a_value = 2020;
3131   printf ("in A::method1, a_value = %d \n",a_value);
3132
3133 @}
3134
3135 void A::method2 (int v)
3136 @{
3137    ada_method2 (this, v);
3138    printf ("in A::method2, a_value = %d \n",a_value);
3139
3140 @}
3141
3142 A::A(void)
3143 @{
3144    a_value = 1010;
3145   printf ("in A::A, a_value = %d \n",a_value);
3146 @}
3147 @end smallexample
3148
3149 @smallexample @c ada
3150 -- Ada sources
3151 package body Simple_Cpp_Interface is
3152
3153    procedure Ada_Method2 (This : in out A; V : Integer) is
3154    begin
3155       Method1 (This);
3156       This.A_Value := V;
3157    end Ada_Method2;
3158
3159 end Simple_Cpp_Interface;
3160
3161 with System;
3162 package Simple_Cpp_Interface is
3163    type A is limited
3164       record
3165          Vptr    : System.Address;
3166          O_Value : Integer;
3167          A_Value : Integer;
3168       end record;
3169    pragma Convention (C, A);
3170
3171    procedure Method1 (This : in out A);
3172    pragma Import (C, Method1);
3173
3174    procedure Ada_Method2 (This : in out A; V : Integer);
3175    pragma Export (C, Ada_Method2);
3176
3177 end Simple_Cpp_Interface;
3178 @end smallexample
3179
3180 @node Interfacing with C++ at the Class Level
3181 @subsection Interfacing with C++ at the Class Level
3182 @noindent
3183 In this section we demonstrate the GNAT features for interfacing with
3184 C++ by means of an example making use of Ada 2005 abstract interface
3185 types. This example consists of a classification of animals; classes
3186 have been used to model our main classification of animals, and
3187 interfaces provide support for the management of secondary
3188 classifications. We first demonstrate a case in which the types and
3189 constructors are defined on the C++ side and imported from the Ada
3190 side, and latter the reverse case.
3191
3192 The root of our derivation will be the @code{Animal} class, with a
3193 single private attribute (the @code{Age} of the animal) and two public
3194 primitives to set and get the value of this attribute.
3195
3196 @smallexample
3197 @b{class} Animal @{
3198  @b{public}:
3199    @b{virtual} void Set_Age (int New_Age);
3200    @b{virtual} int Age ();
3201  @b{private}:
3202    int Age_Count;
3203 @};
3204 @end smallexample
3205
3206 Abstract interface types are defined in C++ by means of classes with pure
3207 virtual functions and no data members. In our example we will use two
3208 interfaces that provide support for the common management of @code{Carnivore}
3209 and @code{Domestic} animals:
3210
3211 @smallexample
3212 @b{class} Carnivore @{
3213 @b{public}:
3214    @b{virtual} int Number_Of_Teeth () = 0;
3215 @};
3216
3217 @b{class} Domestic @{
3218 @b{public}:
3219    @b{virtual void} Set_Owner (char* Name) = 0;
3220 @};
3221 @end smallexample
3222
3223 Using these declarations, we can now say that a @code{Dog} is an animal that is
3224 both Carnivore and Domestic, that is:
3225
3226 @smallexample
3227 @b{class} Dog : Animal, Carnivore, Domestic @{
3228  @b{public}:
3229    @b{virtual} int  Number_Of_Teeth ();
3230    @b{virtual} void Set_Owner (char* Name);
3231
3232    Dog(); // Constructor
3233  @b{private}:
3234    int  Tooth_Count;
3235    char *Owner;
3236 @};
3237 @end smallexample
3238
3239 In the following examples we will assume that the previous declarations are
3240 located in a file named @code{animals.h}. The following package demonstrates
3241 how to import these C++ declarations from the Ada side:
3242
3243 @smallexample @c ada
3244 with Interfaces.C.Strings; use Interfaces.C.Strings;
3245 package Animals is
3246   type Carnivore is interface;
3247   pragma Convention (C_Plus_Plus, Carnivore);
3248   function Number_Of_Teeth (X : Carnivore)
3249      return Natural is abstract;
3250
3251   type Domestic is interface;
3252   pragma Convention (C_Plus_Plus, Set_Owner);
3253   procedure Set_Owner
3254     (X    : in out Domestic;
3255      Name : Chars_Ptr) is abstract;
3256
3257   type Animal is tagged record
3258     Age : Natural := 0;
3259   end record;
3260   pragma Import (C_Plus_Plus, Animal);
3261
3262   procedure Set_Age (X : in out Animal; Age : Integer);
3263   pragma Import (C_Plus_Plus, Set_Age);
3264
3265   function Age (X : Animal) return Integer;
3266   pragma Import (C_Plus_Plus, Age);
3267
3268   type Dog is new Animal and Carnivore and Domestic with record
3269     Tooth_Count : Natural;
3270     Owner       : String (1 .. 30);
3271   end record;
3272   pragma Import (C_Plus_Plus, Dog);
3273
3274   function Number_Of_Teeth (A : Dog) return Integer;
3275   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3276
3277   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3278   pragma Import (C_Plus_Plus, Set_Owner);
3279
3280   function New_Dog return Dog'Class;
3281   pragma CPP_Constructor (New_Dog);
3282   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3283 end Animals;
3284 @end smallexample
3285
3286 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3287 interfacing with these C++ classes is easy. The only requirement is that all
3288 the primitives and components must be declared exactly in the same order in
3289 the two languages.
3290
3291 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3292 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3293 the arguments to the called primitives will be the same as for C++. For the
3294 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3295 to indicate that they have been defined on the C++ side; this is required
3296 because the dispatch table associated with these tagged types will be built
3297 in the C++ side and therefore will not contain the predefined Ada primitives
3298 which Ada would otherwise expect.
3299
3300 As the reader can see there is no need to indicate the C++ mangled names
3301 associated with each subprogram because it is assumed that all the calls to
3302 these primitives will be dispatching calls. The only exception is the
3303 constructor, which must be registered with the compiler by means of
3304 @code{pragma CPP_Constructor} and needs to provide its associated C++
3305 mangled name because the Ada compiler generates direct calls to it.
3306
3307 With the above packages we can now declare objects of type Dog on the Ada side
3308 and dispatch calls to the corresponding subprograms on the C++ side. We can
3309 also extend the tagged type Dog with further fields and primitives, and
3310 override some of its C++ primitives on the Ada side. For example, here we have
3311 a type derivation defined on the Ada side that inherits all the dispatching
3312 primitives of the ancestor from the C++ side.
3313
3314 @smallexample
3315 @b{with} Animals; @b{use} Animals;
3316 @b{package} Vaccinated_Animals @b{is}
3317   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3318   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3319 @b{end} Vaccinated_Animals;
3320 @end smallexample
3321
3322 It is important to note that, because of the ABI compatibility, the programmer
3323 does not need to add any further information to indicate either the object
3324 layout or the dispatch table entry associated with each dispatching operation.
3325
3326 Now let us define all the types and constructors on the Ada side and export
3327 them to C++, using the same hierarchy of our previous example:
3328
3329 @smallexample @c ada
3330 with Interfaces.C.Strings;
3331 use Interfaces.C.Strings;
3332 package Animals is
3333   type Carnivore is interface;
3334   pragma Convention (C_Plus_Plus, Carnivore);
3335   function Number_Of_Teeth (X : Carnivore)
3336      return Natural is abstract;
3337
3338   type Domestic is interface;
3339   pragma Convention (C_Plus_Plus, Set_Owner);
3340   procedure Set_Owner
3341     (X    : in out Domestic;
3342      Name : Chars_Ptr) is abstract;
3343
3344   type Animal is tagged record
3345     Age : Natural := 0;
3346   end record;
3347   pragma Convention (C_Plus_Plus, Animal);
3348
3349   procedure Set_Age (X : in out Animal; Age : Integer);
3350   pragma Export (C_Plus_Plus, Set_Age);
3351
3352   function Age (X : Animal) return Integer;
3353   pragma Export (C_Plus_Plus, Age);
3354
3355   type Dog is new Animal and Carnivore and Domestic with record
3356     Tooth_Count : Natural;
3357     Owner       : String (1 .. 30);
3358   end record;
3359   pragma Convention (C_Plus_Plus, Dog);
3360
3361   function Number_Of_Teeth (A : Dog) return Integer;
3362   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3363
3364   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3365   pragma Export (C_Plus_Plus, Set_Owner);
3366
3367   function New_Dog return Dog'Class;
3368   pragma Export (C_Plus_Plus, New_Dog);
3369 end Animals;
3370 @end smallexample
3371
3372 Compared with our previous example the only difference is the use of
3373 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3374 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3375 nothing else to be done; as explained above, the only requirement is that all
3376 the primitives and components are declared in exactly the same order.
3377
3378 For completeness, let us see a brief C++ main program that uses the
3379 declarations available in @code{animals.h} (presented in our first example) to
3380 import and use the declarations from the Ada side, properly initializing and
3381 finalizing the Ada run-time system along the way:
3382
3383 @smallexample
3384 @b{#include} "animals.h"
3385 @b{#include} <iostream>
3386 @b{using namespace} std;
3387
3388 void Check_Carnivore (Carnivore *obj) @{ ... @}
3389 void Check_Domestic (Domestic *obj)   @{ ... @}
3390 void Check_Animal (Animal *obj)       @{ ... @}
3391 void Check_Dog (Dog *obj)             @{ ... @}
3392
3393 @b{extern} "C" @{
3394   void adainit (void);
3395   void adafinal (void);
3396   Dog* new_dog ();
3397 @}
3398
3399 void test ()
3400 @{
3401   Dog *obj = new_dog();  // Ada constructor
3402   Check_Carnivore (obj); // Check secondary DT
3403   Check_Domestic (obj);  // Check secondary DT
3404   Check_Animal (obj);    // Check primary DT
3405   Check_Dog (obj);       // Check primary DT
3406 @}
3407
3408 int main ()
3409 @{
3410   adainit ();  test();  adafinal ();
3411   return 0;
3412 @}
3413 @end smallexample
3414
3415 @node Comparison between GNAT and C/C++ Compilation Models
3416 @section Comparison between GNAT and C/C++ Compilation Models
3417
3418 @noindent
3419 The GNAT model of compilation is close to the C and C++ models. You can
3420 think of Ada specs as corresponding to header files in C. As in C, you
3421 don't need to compile specs; they are compiled when they are used. The
3422 Ada @code{with} is similar in effect to the @code{#include} of a C
3423 header.
3424
3425 One notable difference is that, in Ada, you may compile specs separately
3426 to check them for semantic and syntactic accuracy. This is not always
3427 possible with C headers because they are fragments of programs that have
3428 less specific syntactic or semantic rules.
3429
3430 The other major difference is the requirement for running the binder,
3431 which performs two important functions. First, it checks for
3432 consistency. In C or C++, the only defense against assembling
3433 inconsistent programs lies outside the compiler, in a makefile, for
3434 example. The binder satisfies the Ada requirement that it be impossible
3435 to construct an inconsistent program when the compiler is used in normal
3436 mode.
3437
3438 @cindex Elaboration order control
3439 The other important function of the binder is to deal with elaboration
3440 issues. There are also elaboration issues in C++ that are handled
3441 automatically. This automatic handling has the advantage of being
3442 simpler to use, but the C++ programmer has no control over elaboration.
3443 Where @code{gnatbind} might complain there was no valid order of
3444 elaboration, a C++ compiler would simply construct a program that
3445 malfunctioned at run time.
3446 @end ifclear
3447
3448 @node Comparison between GNAT and Conventional Ada Library Models
3449 @section Comparison between GNAT and Conventional Ada Library Models
3450
3451 @noindent
3452 This section is intended for Ada programmers who have
3453 used an Ada compiler implementing the traditional Ada library
3454 model, as described in the Ada Reference Manual.
3455
3456 @cindex GNAT library
3457 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3458 source files themselves acts as the library. Compiling Ada programs does
3459 not generate any centralized information, but rather an object file and
3460 a ALI file, which are of interest only to the binder and linker.
3461 In a traditional system, the compiler reads information not only from
3462 the source file being compiled, but also from the centralized library.
3463 This means that the effect of a compilation depends on what has been
3464 previously compiled. In particular:
3465
3466 @itemize @bullet
3467 @item
3468 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3469 to the version of the unit most recently compiled into the library.
3470
3471 @item
3472 Inlining is effective only if the necessary body has already been
3473 compiled into the library.
3474
3475 @item
3476 Compiling a unit may obsolete other units in the library.
3477 @end itemize
3478
3479 @noindent
3480 In GNAT, compiling one unit never affects the compilation of any other
3481 units because the compiler reads only source files. Only changes to source
3482 files can affect the results of a compilation. In particular:
3483
3484 @itemize @bullet
3485 @item
3486 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3487 to the source version of the unit that is currently accessible to the
3488 compiler.
3489
3490 @item
3491 @cindex Inlining
3492 Inlining requires the appropriate source files for the package or
3493 subprogram bodies to be available to the compiler. Inlining is always
3494 effective, independent of the order in which units are complied.
3495
3496 @item
3497 Compiling a unit never affects any other compilations. The editing of
3498 sources may cause previous compilations to be out of date if they
3499 depended on the source file being modified.
3500 @end itemize
3501
3502 @noindent
3503 The most important result of these differences is that order of compilation
3504 is never significant in GNAT. There is no situation in which one is
3505 required to do one compilation before another. What shows up as order of
3506 compilation requirements in the traditional Ada library becomes, in
3507 GNAT, simple source dependencies; in other words, there is only a set
3508 of rules saying what source files must be present when a file is
3509 compiled.
3510
3511 @ifset vms
3512 @node Placement of temporary files
3513 @section Placement of temporary files
3514 @cindex Temporary files (user control over placement)
3515
3516 @noindent
3517 GNAT creates temporary files in the directory designated by the environment
3518 variable @env{TMPDIR}.
3519 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3520 for detailed information on how environment variables are resolved.
3521 For most users the easiest way to make use of this feature is to simply
3522 define @env{TMPDIR} as a job level logical name).
3523 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3524 for compiler temporary files, then you can include something like the
3525 following command in your @file{LOGIN.COM} file:
3526
3527 @smallexample
3528 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3529 @end smallexample
3530
3531 @noindent
3532 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3533 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3534 designated by @env{TEMP}.
3535 If none of these environment variables are defined then GNAT uses the
3536 directory designated by the logical name @code{SYS$SCRATCH:}
3537 (by default the user's home directory). If all else fails
3538 GNAT uses the current directory for temporary files.
3539 @end ifset
3540
3541 @c *************************
3542 @node Compiling Using gcc
3543 @chapter Compiling Using @command{gcc}
3544
3545 @noindent
3546 This chapter discusses how to compile Ada programs using the @command{gcc}
3547 command. It also describes the set of switches
3548 that can be used to control the behavior of the compiler.
3549 @menu
3550 * Compiling Programs::
3551 * Switches for gcc::
3552 * Search Paths and the Run-Time Library (RTL)::
3553 * Order of Compilation Issues::
3554 * Examples::
3555 @end menu
3556
3557 @node Compiling Programs
3558 @section Compiling Programs
3559
3560 @noindent
3561 The first step in creating an executable program is to compile the units
3562 of the program using the @command{gcc} command. You must compile the
3563 following files:
3564
3565 @itemize @bullet
3566 @item
3567 the body file (@file{.adb}) for a library level subprogram or generic
3568 subprogram
3569
3570 @item
3571 the spec file (@file{.ads}) for a library level package or generic
3572 package that has no body
3573
3574 @item
3575 the body file (@file{.adb}) for a library level package
3576 or generic package that has a body
3577
3578 @end itemize
3579
3580 @noindent
3581 You need @emph{not} compile the following files
3582
3583 @itemize @bullet
3584
3585 @item
3586 the spec of a library unit which has a body
3587
3588 @item
3589 subunits
3590 @end itemize
3591
3592 @noindent
3593 because they are compiled as part of compiling related units. GNAT
3594 package specs
3595 when the corresponding body is compiled, and subunits when the parent is
3596 compiled.
3597
3598 @cindex cannot generate code
3599 If you attempt to compile any of these files, you will get one of the
3600 following error messages (where fff is the name of the file you compiled):
3601
3602 @smallexample
3603 cannot generate code for file @var{fff} (package spec)
3604 to check package spec, use -gnatc
3605
3606 cannot generate code for file @var{fff} (missing subunits)
3607 to check parent unit, use -gnatc
3608
3609 cannot generate code for file @var{fff} (subprogram spec)
3610 to check subprogram spec, use -gnatc
3611
3612 cannot generate code for file @var{fff} (subunit)
3613 to check subunit, use -gnatc
3614 @end smallexample
3615
3616 @noindent
3617 As indicated by the above error messages, if you want to submit
3618 one of these files to the compiler to check for correct semantics
3619 without generating code, then use the @option{-gnatc} switch.
3620
3621 The basic command for compiling a file containing an Ada unit is
3622
3623 @smallexample
3624 $ gcc -c [@var{switches}] @file{file name}
3625 @end smallexample
3626
3627 @noindent
3628 where @var{file name} is the name of the Ada file (usually
3629 having an extension
3630 @file{.ads} for a spec or @file{.adb} for a body).
3631 @ifclear vms
3632 You specify the
3633 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3634 @end ifclear
3635 The result of a successful compilation is an object file, which has the
3636 same name as the source file but an extension of @file{.o} and an Ada
3637 Library Information (ALI) file, which also has the same name as the
3638 source file, but with @file{.ali} as the extension. GNAT creates these
3639 two output files in the current directory, but you may specify a source
3640 file in any directory using an absolute or relative path specification
3641 containing the directory information.
3642
3643 @findex gnat1
3644 @command{gcc} is actually a driver program that looks at the extensions of
3645 the file arguments and loads the appropriate compiler. For example, the
3646 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3647 These programs are in directories known to the driver program (in some
3648 configurations via environment variables you set), but need not be in
3649 your path. The @command{gcc} driver also calls the assembler and any other
3650 utilities needed to complete the generation of the required object
3651 files.
3652
3653 It is possible to supply several file names on the same @command{gcc}
3654 command. This causes @command{gcc} to call the appropriate compiler for
3655 each file. For example, the following command lists three separate
3656 files to be compiled:
3657
3658 @smallexample
3659 $ gcc -c x.adb y.adb z.c
3660 @end smallexample
3661
3662 @noindent
3663 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3664 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3665 The compiler generates three object files @file{x.o}, @file{y.o} and
3666 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3667 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3668 @ifclear vms
3669 except for
3670 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3671 @end ifclear
3672
3673 @node Switches for gcc
3674 @section Switches for @command{gcc}
3675
3676 @noindent
3677 The @command{gcc} command accepts switches that control the
3678 compilation process. These switches are fully described in this section.
3679 First we briefly list all the switches, in alphabetical order, then we
3680 describe the switches in more detail in functionally grouped sections.
3681
3682 More switches exist for GCC than those documented here, especially
3683 for specific targets. However, their use is not recommended as
3684 they may change code generation in ways that are incompatible with
3685 the Ada run-time library, or can cause inconsistencies between
3686 compilation units.
3687
3688 @menu
3689 * Output and Error Message Control::
3690 * Warning Message Control::
3691 * Debugging and Assertion Control::
3692 * Validity Checking::
3693 * Style Checking::
3694 * Run-Time Checks::
3695 * Using gcc for Syntax Checking::
3696 * Using gcc for Semantic Checking::
3697 * Compiling Different Versions of Ada::
3698 * Character Set Control::
3699 * File Naming Control::
3700 * Subprogram Inlining Control::
3701 * Auxiliary Output Control::
3702 * Debugging Control::
3703 * Exception Handling Control::
3704 * Units to Sources Mapping Files::
3705 * Integrated Preprocessing::
3706 * Code Generation Control::
3707 @ifset vms
3708 * Return Codes::
3709 @end ifset
3710 @end menu
3711
3712 @table @option
3713 @c !sort!
3714 @ifclear vms
3715 @cindex @option{-b} (@command{gcc})
3716 @item -b @var{target}
3717 Compile your program to run on @var{target}, which is the name of a
3718 system configuration. You must have a GNAT cross-compiler built if
3719 @var{target} is not the same as your host system.
3720
3721 @item -B@var{dir}
3722 @cindex @option{-B} (@command{gcc})
3723 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3724 from @var{dir} instead of the default location. Only use this switch
3725 when multiple versions of the GNAT compiler are available. See the
3726 @command{gcc} manual page for further details. You would normally use the
3727 @option{-b} or @option{-V} switch instead.
3728
3729 @item -c
3730 @cindex @option{-c} (@command{gcc})
3731 Compile. Always use this switch when compiling Ada programs.
3732
3733 Note: for some other languages when using @command{gcc}, notably in
3734 the case of C and C++, it is possible to use
3735 use @command{gcc} without a @option{-c} switch to
3736 compile and link in one step. In the case of GNAT, you
3737 cannot use this approach, because the binder must be run
3738 and @command{gcc} cannot be used to run the GNAT binder.
3739 @end ifclear
3740
3741 @item -fno-inline
3742 @cindex @option{-fno-inline} (@command{gcc})
3743 Suppresses all back-end inlining, even if other optimization or inlining
3744 switches are set.
3745 This includes suppression of inlining that results
3746 from the use of the pragma @code{Inline_Always}.
3747 See also @option{-gnatn} and @option{-gnatN}.
3748
3749 @item -fno-strict-aliasing
3750 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3751 Causes the compiler to avoid assumptions regarding non-aliasing
3752 of objects of different types. See
3753 @ref{Optimization and Strict Aliasing} for details.
3754
3755 @item -fstack-check
3756 @cindex @option{-fstack-check} (@command{gcc})
3757 Activates stack checking.
3758 See @ref{Stack Overflow Checking} for details.
3759
3760 @item -fstack-usage
3761 @cindex @option{-fstack-usage} (@command{gcc})
3762 Makes the compiler output stack usage information for the program, on a
3763 per-function basis. See @ref{Static Stack Usage Analysis} for details.
3764
3765 @item -fcallgraph-info[=su]
3766 @cindex @option{-fcallgraph-info} (@command{gcc})
3767 Makes the compiler output callgraph information for the program, on a
3768 per-file basis.  The information is generated in the VCG format.  It can
3769 be decorated with stack-usage per-node information.
3770
3771 @item ^-g^/DEBUG^
3772 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3773 Generate debugging information. This information is stored in the object
3774 file and copied from there to the final executable file by the linker,
3775 where it can be read by the debugger. You must use the
3776 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3777
3778 @item -gnat83
3779 @cindex @option{-gnat83} (@command{gcc})
3780 Enforce Ada 83 restrictions.
3781
3782 @item -gnat95
3783 @cindex @option{-gnat95} (@command{gcc})
3784 Enforce Ada 95 restrictions.
3785
3786 @item -gnat05
3787 @cindex @option{-gnat05} (@command{gcc})
3788 Allow full Ada 2005 features.
3789
3790 @item -gnata
3791 @cindex @option{-gnata} (@command{gcc})
3792 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3793 activated. Note that these pragmas can also be controlled using the
3794 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3795
3796 @item -gnatA
3797 @cindex @option{-gnatA} (@command{gcc})
3798 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3799 it will be ignored.
3800
3801 @item -gnatb
3802 @cindex @option{-gnatb} (@command{gcc})
3803 Generate brief messages to @file{stderr} even if verbose mode set.
3804
3805 @item -gnatc
3806 @cindex @option{-gnatc} (@command{gcc})
3807 Check syntax and semantics only (no code generation attempted).
3808
3809 @item -gnatd
3810 @cindex @option{-gnatd} (@command{gcc})
3811 Specify debug options for the compiler. The string of characters after
3812 the @option{-gnatd} specify the specific debug options. The possible
3813 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3814 compiler source file @file{debug.adb} for details of the implemented
3815 debug options. Certain debug options are relevant to applications
3816 programmers, and these are documented at appropriate points in this
3817 users guide.
3818
3819 @item -gnatD
3820 @cindex @option{-gnatD} (@command{gcc})
3821 Create expanded source files for source level debugging. This switch
3822 also suppress generation of cross-reference information
3823 (see @option{-gnatx}).
3824
3825 @item -gnatec=@var{path}
3826 @cindex @option{-gnatec} (@command{gcc})
3827 Specify a configuration pragma file
3828 @ifclear vms
3829 (the equal sign is optional)
3830 @end ifclear
3831 (@pxref{The Configuration Pragmas Files}).
3832
3833 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3834 @cindex @option{-gnateD} (@command{gcc})
3835 Defines a symbol, associated with value, for preprocessing.
3836 (@pxref{Integrated Preprocessing}).
3837
3838 @item -gnatef
3839 @cindex @option{-gnatef} (@command{gcc})
3840 Display full source path name in brief error messages.
3841
3842 @item -gnatem=@var{path}
3843 @cindex @option{-gnatem} (@command{gcc})
3844 Specify a mapping file
3845 @ifclear vms
3846 (the equal sign is optional)
3847 @end ifclear
3848 (@pxref{Units to Sources Mapping Files}).
3849
3850 @item -gnatep=@var{file}
3851 @cindex @option{-gnatep} (@command{gcc})
3852 Specify a preprocessing data file
3853 @ifclear vms
3854 (the equal sign is optional)
3855 @end ifclear
3856 (@pxref{Integrated Preprocessing}).
3857
3858 @item -gnatE
3859 @cindex @option{-gnatE} (@command{gcc})
3860 Full dynamic elaboration checks.
3861
3862 @item -gnatf
3863 @cindex @option{-gnatf} (@command{gcc})
3864 Full errors. Multiple errors per line, all undefined references, do not
3865 attempt to suppress cascaded errors.
3866
3867 @item -gnatF
3868 @cindex @option{-gnatF} (@command{gcc})
3869 Externals names are folded to all uppercase.
3870
3871 @item ^-gnatg^/GNAT_INTERNAL^
3872 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
3873 Internal GNAT implementation mode. This should not be used for
3874 applications programs, it is intended only for use by the compiler
3875 and its run-time library. For documentation, see the GNAT sources.
3876 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
3877 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
3878 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
3879 so that all standard warnings and all standard style options are turned on.
3880 All warnings and style error messages are treated as errors.
3881
3882 @item -gnatG
3883 @cindex @option{-gnatG} (@command{gcc})
3884 List generated expanded code in source form.
3885
3886 @item ^-gnath^/HELP^
3887 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3888 Output usage information. The output is written to @file{stdout}.
3889
3890 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3891 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3892 Identifier character set
3893 @ifclear vms
3894 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3895 @end ifclear
3896 @ifset vms
3897 For details of the possible selections for @var{c},
3898 see @ref{Character Set Control}.
3899 @end ifset
3900
3901 @item -gnatjnn
3902 @cindex @option{-gnatjnn} (@command{gcc})
3903 Reformat error messages to fit on nn character lines
3904
3905 @item -gnatk=@var{n}
3906 @cindex @option{-gnatk} (@command{gcc})
3907 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3908
3909 @item -gnatl
3910 @cindex @option{-gnatl} (@command{gcc})
3911 Output full source listing with embedded error messages.
3912
3913 @item -gnatL
3914 @cindex @option{-gnatL} (@command{gcc})
3915 Used in conjunction with -gnatG or -gnatD to intersperse original
3916 source lines (as comment lines with line numbers) in the expanded
3917 source output.
3918
3919 @item -gnatm=@var{n}
3920 @cindex @option{-gnatm} (@command{gcc})
3921 Limit number of detected error or warning messages to @var{n}
3922 where @var{n} is in the range 1..999_999. The default setting if
3923 no switch is given is 9999. Compilation is terminated if this
3924 limit is exceeded. The equal sign here is optional.
3925
3926 @item -gnatn
3927 @cindex @option{-gnatn} (@command{gcc})
3928 Activate inlining for subprograms for which
3929 pragma @code{inline} is specified. This inlining is performed
3930 by the GCC back-end.
3931
3932 @item -gnatN
3933 @cindex @option{-gnatN} (@command{gcc})
3934 Activate front end inlining for subprograms for which
3935 pragma @code{Inline} is specified. This inlining is performed
3936 by the front end and will be visible in the
3937 @option{-gnatG} output.
3938 In some cases, this has proved more effective than the back end
3939 inlining resulting from the use of
3940 @option{-gnatn}.
3941 Note that
3942 @option{-gnatN} automatically implies
3943 @option{-gnatn} so it is not necessary
3944 to specify both options. There are a few cases that the back-end inlining
3945 catches that cannot be dealt with in the front-end.
3946
3947 @item -gnato
3948 @cindex @option{-gnato} (@command{gcc})
3949 Enable numeric overflow checking (which is not normally enabled by
3950 default). Not that division by zero is a separate check that is not
3951 controlled by this switch (division by zero checking is on by default).
3952
3953 @item -gnatp
3954 @cindex @option{-gnatp} (@command{gcc})
3955 Suppress all checks.
3956
3957 @item -gnatP
3958 @cindex @option{-gnatP} (@command{gcc})
3959 Enable polling. This is required on some systems (notably Windows NT) to
3960 obtain asynchronous abort and asynchronous transfer of control capability.
3961 See the description of pragma Polling in the GNAT Reference Manual for
3962 full details.
3963
3964 @item -gnatq
3965 @cindex @option{-gnatq} (@command{gcc})
3966 Don't quit; try semantics, even if parse errors.
3967
3968 @item -gnatQ
3969 @cindex @option{-gnatQ} (@command{gcc})
3970 Don't quit; generate @file{ALI} and tree files even if illegalities.
3971
3972 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3973 @cindex @option{-gnatR} (@command{gcc})
3974 Output representation information for declared types and objects.
3975
3976 @item -gnats
3977 @cindex @option{-gnats} (@command{gcc})
3978 Syntax check only.
3979
3980 @item -gnatS
3981 @cindex @option{-gnatS} (@command{gcc})
3982 Print package Standard.
3983
3984 @item -gnatt
3985 @cindex @option{-gnatt} (@command{gcc})
3986 Generate tree output file.
3987
3988 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3989 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
3990 All compiler tables start at @var{nnn} times usual starting size.
3991
3992 @item -gnatu
3993 @cindex @option{-gnatu} (@command{gcc})
3994 List units for this compilation.
3995
3996 @item -gnatU
3997 @cindex @option{-gnatU} (@command{gcc})
3998 Tag all error messages with the unique string ``error:''
3999
4000 @item -gnatv
4001 @cindex @option{-gnatv} (@command{gcc})
4002 Verbose mode. Full error output with source lines to @file{stdout}.
4003
4004 @item -gnatV
4005 @cindex @option{-gnatV} (@command{gcc})
4006 Control level of validity checking. See separate section describing
4007 this feature.
4008
4009 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
4010 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4011 Warning mode where
4012 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4013 the exact warnings that
4014 are enabled or disabled (@pxref{Warning Message Control}).
4015
4016 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4017 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4018 Wide character encoding method
4019 @ifclear vms
4020 (@var{e}=n/h/u/s/e/8).
4021 @end ifclear
4022 @ifset vms
4023 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4024 @end ifset
4025
4026 @item -gnatx
4027 @cindex @option{-gnatx} (@command{gcc})
4028 Suppress generation of cross-reference information.
4029
4030 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
4031 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4032 Enable built-in style checks (@pxref{Style Checking}).
4033
4034 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4035 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4036 Distribution stub generation and compilation
4037 @ifclear vms
4038 (@var{m}=r/c for receiver/caller stubs).
4039 @end ifclear
4040 @ifset vms
4041 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4042 to be generated and compiled).
4043 @end ifset
4044
4045 @item ^-I^/SEARCH=^@var{dir}
4046 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4047 @cindex RTL
4048 Direct GNAT to search the @var{dir} directory for source files needed by
4049 the current compilation
4050 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4051
4052 @item ^-I-^/NOCURRENT_DIRECTORY^
4053 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4054 @cindex RTL
4055 Except for the source file named in the command line, do not look for source
4056 files in the directory containing the source file named in the command line
4057 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4058
4059 @ifclear vms
4060 @item -mbig-switch
4061 @cindex @option{-mbig-switch} (@command{gcc})
4062 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4063 This standard gcc switch causes the compiler to use larger offsets in its
4064 jump table representation for @code{case} statements.
4065 This may result in less efficient code, but is sometimes necessary
4066 (for example on HP-UX targets)
4067 @cindex HP-UX and @option{-mbig-switch} option
4068 in order to compile large and/or nested @code{case} statements.
4069
4070 @item -o @var{file}
4071 @cindex @option{-o} (@command{gcc})
4072 This switch is used in @command{gcc} to redirect the generated object file
4073 and its associated ALI file. Beware of this switch with GNAT, because it may
4074 cause the object file and ALI file to have different names which in turn
4075 may confuse the binder and the linker.
4076 @end ifclear
4077
4078 @item -nostdinc
4079 @cindex @option{-nostdinc} (@command{gcc})
4080 Inhibit the search of the default location for the GNAT Run Time
4081 Library (RTL) source files.
4082
4083 @item -nostdlib
4084 @cindex @option{-nostdlib} (@command{gcc})
4085 Inhibit the search of the default location for the GNAT Run Time
4086 Library (RTL) ALI files.
4087
4088 @ifclear vms
4089 @item -O[@var{n}]
4090 @cindex @option{-O} (@command{gcc})
4091 @var{n} controls the optimization level.
4092
4093 @table @asis
4094 @item n = 0
4095 No optimization, the default setting if no @option{-O} appears
4096
4097 @item n = 1
4098 Normal optimization, the default if you specify @option{-O} without
4099 an operand. A good compromise between code quality and compilation
4100 time.
4101
4102 @item n = 2
4103 Extensive optimization, may improve execution time, possibly at the cost of
4104 substantially increased compilation time.
4105
4106 @item n = 3
4107 Same as @option{-O2}, and also includes inline expansion for small subprograms
4108 in the same unit.
4109
4110 @item n = s
4111 Optimize space usage
4112 @end table
4113
4114 @noindent
4115 See also @ref{Optimization Levels}.
4116 @end ifclear
4117
4118 @ifset vms
4119 @item  /NOOPTIMIZE
4120 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4121 Equivalent to @option{/OPTIMIZE=NONE}.
4122 This is the default behavior in the absence of an @option{/OPTIMIZE}
4123 qualifier.
4124
4125 @item /OPTIMIZE[=(keyword[,...])]
4126 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4127 Selects the level of optimization for your program. The supported
4128 keywords are as follows:
4129 @table @code
4130 @item   ALL
4131 Perform most optimizations, including those that
4132 are expensive.
4133 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4134 without keyword options.
4135
4136 @item   NONE
4137 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4138
4139 @item SOME
4140 Perform some optimizations, but omit ones that are costly.
4141
4142 @item   DEVELOPMENT
4143 Same as @code{SOME}.
4144
4145 @item INLINING
4146 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4147 automatic inlining of small subprograms within a unit
4148
4149 @item   UNROLL_LOOPS
4150 Try to unroll loops. This keyword may be specified together with
4151 any keyword above other than @code{NONE}. Loop unrolling
4152 usually, but not always, improves the performance of programs.
4153
4154 @item SPACE
4155 Optimize space usage
4156 @end table
4157
4158 @noindent
4159 See also @ref{Optimization Levels}.
4160 @end ifset
4161
4162 @ifclear vms
4163 @item -pass-exit-codes
4164 @cindex @option{-pass-exit-codes} (@command{gcc})
4165 Catch exit codes from the compiler and use the most meaningful as
4166 exit status.
4167 @end ifclear
4168
4169 @item --RTS=@var{rts-path}
4170 @cindex @option{--RTS} (@command{gcc})
4171 Specifies the default location of the runtime library. Same meaning as the
4172 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4173
4174 @item ^-S^/ASM^
4175 @cindex @option{^-S^/ASM^} (@command{gcc})
4176 ^Used in place of @option{-c} to^Used to^
4177 cause the assembler source file to be
4178 generated, using @file{^.s^.S^} as the extension,
4179 instead of the object file.
4180 This may be useful if you need to examine the generated assembly code.
4181
4182 @item ^-fverbose-asm^/VERBOSE_ASM^
4183 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4184 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4185 to cause the generated assembly code file to be annotated with variable
4186 names, making it significantly easier to follow.
4187
4188 @item ^-v^/VERBOSE^
4189 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4190 Show commands generated by the @command{gcc} driver. Normally used only for
4191 debugging purposes or if you need to be sure what version of the
4192 compiler you are executing.
4193
4194 @ifclear vms
4195 @item -V @var{ver}
4196 @cindex @option{-V} (@command{gcc})
4197 Execute @var{ver} version of the compiler. This is the @command{gcc}
4198 version, not the GNAT version.
4199 @end ifclear
4200
4201 @item ^-w^NO_BACK_END_WARNINGS^
4202 @cindex @option{-w} (@command{gcc})
4203 Turn off warnings generated by the back end of the compiler. Use of
4204 this switch also causes the default for front end warnings to be set
4205 to suppress (as though @option{-gnatws} had appeared at the start of
4206 the options.
4207
4208 @end table
4209
4210 @ifclear vms
4211 @c Combining qualifiers does not work on VMS
4212 You may combine a sequence of GNAT switches into a single switch. For
4213 example, the combined switch
4214
4215 @cindex Combining GNAT switches
4216 @smallexample
4217 -gnatofi3
4218 @end smallexample
4219
4220 @noindent
4221 is equivalent to specifying the following sequence of switches:
4222
4223 @smallexample
4224 -gnato -gnatf -gnati3
4225 @end smallexample
4226 @end ifclear
4227
4228 @noindent
4229 The following restrictions apply to the combination of switches
4230 in this manner:
4231
4232 @itemize @bullet
4233 @item
4234 The switch @option{-gnatc} if combined with other switches must come
4235 first in the string.
4236
4237 @item
4238 The switch @option{-gnats} if combined with other switches must come
4239 first in the string.
4240
4241 @item
4242 The switches
4243 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4244 may not be combined with any other switches.
4245
4246 @ifclear vms
4247 @item
4248 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4249 switch), then all further characters in the switch are interpreted
4250 as style modifiers (see description of @option{-gnaty}).
4251
4252 @item
4253 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4254 switch), then all further characters in the switch are interpreted
4255 as debug flags (see description of @option{-gnatd}).
4256
4257 @item
4258 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4259 switch), then all further characters in the switch are interpreted
4260 as warning mode modifiers (see description of @option{-gnatw}).
4261
4262 @item
4263 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4264 switch), then all further characters in the switch are interpreted
4265 as validity checking options (see description of @option{-gnatV}).
4266 @end ifclear
4267 @end itemize
4268
4269 @node Output and Error Message Control
4270 @subsection Output and Error Message Control
4271 @findex stderr
4272
4273 @noindent
4274 The standard default format for error messages is called ``brief format''.
4275 Brief format messages are written to @file{stderr} (the standard error
4276 file) and have the following form:
4277
4278 @smallexample
4279 e.adb:3:04: Incorrect spelling of keyword "function"
4280 e.adb:4:20: ";" should be "is"
4281 @end smallexample
4282
4283 @noindent
4284 The first integer after the file name is the line number in the file,
4285 and the second integer is the column number within the line.
4286 @ifclear vms
4287 @code{GPS} can parse the error messages
4288 and point to the referenced character.
4289 @end ifclear
4290 The following switches provide control over the error message
4291 format:
4292
4293 @table @option
4294 @c !sort!
4295 @item -gnatv
4296 @cindex @option{-gnatv} (@command{gcc})
4297 @findex stdout
4298 @ifclear vms
4299 The v stands for verbose.
4300 @end ifclear
4301 The effect of this setting is to write long-format error
4302 messages to @file{stdout} (the standard output file.
4303 The same program compiled with the
4304 @option{-gnatv} switch would generate:
4305
4306 @smallexample
4307 @cartouche
4308 3. funcion X (Q : Integer)
4309    |
4310 >>> Incorrect spelling of keyword "function"
4311 4. return Integer;
4312                  |
4313 >>> ";" should be "is"
4314 @end cartouche
4315 @end smallexample
4316
4317 @noindent
4318 The vertical bar indicates the location of the error, and the @samp{>>>}
4319 prefix can be used to search for error messages. When this switch is
4320 used the only source lines output are those with errors.
4321
4322 @item -gnatl
4323 @cindex @option{-gnatl} (@command{gcc})
4324 @ifclear vms
4325 The @code{l} stands for list.
4326 @end ifclear
4327 This switch causes a full listing of
4328 the file to be generated. In the case where a body is
4329 compiled, the corresponding spec is also listed, along
4330 with any subunits. Typical output from compiling a package
4331 body @file{p.adb} might look like:
4332
4333 @smallexample @c ada
4334 @cartouche
4335  Compiling: p.adb
4336
4337      1. package body p is
4338      2.    procedure a;
4339      3.    procedure a is separate;
4340      4. begin
4341      5.    null
4342                |
4343         >>> missing ";"
4344
4345      6. end;
4346
4347 Compiling: p.ads
4348
4349      1. package p is
4350      2.    pragma Elaborate_Body
4351                                 |
4352         >>> missing ";"
4353
4354      3. end p;
4355
4356 Compiling: p-a.adb
4357
4358      1. separate p
4359                 |
4360         >>> missing "("
4361
4362      2. procedure a is
4363      3. begin
4364      4.    null
4365                |
4366         >>> missing ";"
4367
4368      5. end;
4369 @end cartouche
4370 @end smallexample
4371
4372 @noindent
4373 @findex stderr
4374 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4375 standard output is redirected, a brief summary is written to
4376 @file{stderr} (standard error) giving the number of error messages and
4377 warning messages generated.
4378
4379 @item -^gnatl^OUTPUT_FILE^=file
4380 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4381 This has the same effect as @code{-gnatl} except that the output is
4382 written to a file instead of to standard output. If the given name
4383 @file{fname} does not start with a period, then it is the full name
4384 of the file to be written. If @file{fname} is an extension, it is
4385 appended to the name of the file being compiled. For example, if
4386 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4387 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4388
4389 @item -gnatU
4390 @cindex @option{-gnatU} (@command{gcc})
4391 This switch forces all error messages to be preceded by the unique
4392 string ``error:''. This means that error messages take a few more
4393 characters in space, but allows easy searching for and identification
4394 of error messages.
4395
4396 @item -gnatb
4397 @cindex @option{-gnatb} (@command{gcc})
4398 @ifclear vms
4399 The @code{b} stands for brief.
4400 @end ifclear
4401 This switch causes GNAT to generate the
4402 brief format error messages to @file{stderr} (the standard error
4403 file) as well as the verbose
4404 format message or full listing (which as usual is written to
4405 @file{stdout} (the standard output file).
4406
4407 @item -gnatm=@var{n}
4408 @cindex @option{-gnatm} (@command{gcc})
4409 @ifclear vms
4410 The @code{m} stands for maximum.
4411 @end ifclear
4412 @var{n} is a decimal integer in the
4413 range of 1 to 999 and limits the number of error messages to be
4414 generated. For example, using @option{-gnatm2} might yield
4415
4416 @smallexample
4417 e.adb:3:04: Incorrect spelling of keyword "function"
4418 e.adb:5:35: missing ".."
4419 fatal error: maximum errors reached
4420 compilation abandoned
4421 @end smallexample
4422
4423 @noindent
4424 Note that the equal sign is optional, so the switches
4425 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4426
4427 @item -gnatf
4428 @cindex @option{-gnatf} (@command{gcc})
4429 @cindex Error messages, suppressing
4430 @ifclear vms
4431 The @code{f} stands for full.
4432 @end ifclear
4433 Normally, the compiler suppresses error messages that are likely to be
4434 redundant. This switch causes all error
4435 messages to be generated. In particular, in the case of
4436 references to undefined variables. If a given variable is referenced
4437 several times, the normal format of messages is
4438 @smallexample
4439 e.adb:7:07: "V" is undefined (more references follow)
4440 @end smallexample
4441
4442 @noindent
4443 where the parenthetical comment warns that there are additional
4444 references to the variable @code{V}. Compiling the same program with the
4445 @option{-gnatf} switch yields
4446
4447 @smallexample
4448 e.adb:7:07: "V" is undefined
4449 e.adb:8:07: "V" is undefined
4450 e.adb:8:12: "V" is undefined
4451 e.adb:8:16: "V" is undefined
4452 e.adb:9:07: "V" is undefined
4453 e.adb:9:12: "V" is undefined
4454 @end smallexample
4455
4456 @noindent
4457 The @option{-gnatf} switch also generates additional information for
4458 some error messages.  Some examples are:
4459
4460 @itemize @bullet
4461 @item
4462 Full details on entities not available in high integrity mode
4463 @item
4464 Details on possibly non-portable unchecked conversion
4465 @item
4466 List possible interpretations for ambiguous calls
4467 @item
4468 Additional details on incorrect parameters
4469 @end itemize
4470
4471 @item -gnatjnn
4472 @cindex @option{-gnatjnn} (@command{gcc})
4473 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4474 with continuation lines are treated as though the continuation lines were
4475 separate messages (and so a warning with two continuation lines counts as
4476 three warnings, and is listed as three separate messages).
4477
4478 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4479 messages are output in a different manner. A message and all its continuation
4480 lines are treated as a unit, and count as only one warning or message in the
4481 statistics totals. Furthermore, the message is reformatted so that no line
4482 is longer than nn characters.
4483
4484 @item -gnatq
4485 @cindex @option{-gnatq} (@command{gcc})
4486 @ifclear vms
4487 The @code{q} stands for quit (really ``don't quit'').
4488 @end ifclear
4489 In normal operation mode, the compiler first parses the program and
4490 determines if there are any syntax errors. If there are, appropriate
4491 error messages are generated and compilation is immediately terminated.
4492 This switch tells
4493 GNAT to continue with semantic analysis even if syntax errors have been
4494 found. This may enable the detection of more errors in a single run. On
4495 the other hand, the semantic analyzer is more likely to encounter some
4496 internal fatal error when given a syntactically invalid tree.
4497
4498 @item -gnatQ
4499 @cindex @option{-gnatQ} (@command{gcc})
4500 In normal operation mode, the @file{ALI} file is not generated if any
4501 illegalities are detected in the program. The use of @option{-gnatQ} forces
4502 generation of the @file{ALI} file. This file is marked as being in
4503 error, so it cannot be used for binding purposes, but it does contain
4504 reasonably complete cross-reference information, and thus may be useful
4505 for use by tools (e.g. semantic browsing tools or integrated development
4506 environments) that are driven from the @file{ALI} file. This switch
4507 implies @option{-gnatq}, since the semantic phase must be run to get a
4508 meaningful ALI file.
4509
4510 In addition, if @option{-gnatt} is also specified, then the tree file is
4511 generated even if there are illegalities. It may be useful in this case
4512 to also specify @option{-gnatq} to ensure that full semantic processing
4513 occurs. The resulting tree file can be processed by ASIS, for the purpose
4514 of providing partial information about illegal units, but if the error
4515 causes the tree to be badly malformed, then ASIS may crash during the
4516 analysis.
4517
4518 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4519 being in error, @command{gnatmake} will attempt to recompile the source when it
4520 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4521
4522 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4523 since ALI files are never generated if @option{-gnats} is set.
4524
4525 @end table
4526
4527 @node Warning Message Control
4528 @subsection Warning Message Control
4529 @cindex Warning messages
4530 @noindent
4531 In addition to error messages, which correspond to illegalities as defined
4532 in the Ada Reference Manual, the compiler detects two kinds of warning
4533 situations.
4534
4535 First, the compiler considers some constructs suspicious and generates a
4536 warning message to alert you to a possible error. Second, if the
4537 compiler detects a situation that is sure to raise an exception at
4538 run time, it generates a warning message. The following shows an example
4539 of warning messages:
4540 @smallexample
4541 e.adb:4:24: warning: creation of object may raise Storage_Error
4542 e.adb:10:17: warning: static value out of range
4543 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4544 @end smallexample
4545
4546 @noindent
4547 GNAT considers a large number of situations as appropriate
4548 for the generation of warning messages. As always, warnings are not
4549 definite indications of errors. For example, if you do an out-of-range
4550 assignment with the deliberate intention of raising a
4551 @code{Constraint_Error} exception, then the warning that may be
4552 issued does not indicate an error. Some of the situations for which GNAT
4553 issues warnings (at least some of the time) are given in the following
4554 list. This list is not complete, and new warnings are often added to
4555 subsequent versions of GNAT. The list is intended to give a general idea
4556 of the kinds of warnings that are generated.
4557
4558 @itemize @bullet
4559 @item
4560 Possible infinitely recursive calls
4561
4562 @item
4563 Out-of-range values being assigned
4564
4565 @item
4566 Possible order of elaboration problems
4567
4568 @item
4569 Unreachable code
4570
4571 @item
4572 Address clauses with possibly unaligned values, or where an attempt is
4573 made to overlay a smaller variable with a larger one.
4574
4575 @item
4576 Fixed-point type declarations with a null range
4577
4578 @item
4579 Direct_IO or Sequential_IO instantiated with a type that has access values
4580
4581 @item
4582 Variables that are never assigned a value
4583
4584 @item
4585 Variables that are referenced before being initialized
4586
4587 @item
4588 Task entries with no corresponding @code{accept} statement
4589
4590 @item
4591 Duplicate accepts for the same task entry in a @code{select}
4592
4593 @item
4594 Objects that take too much storage
4595
4596 @item
4597 Unchecked conversion between types of differing sizes
4598
4599 @item
4600 Missing @code{return} statement along some execution path in a function
4601
4602 @item
4603 Incorrect (unrecognized) pragmas
4604
4605 @item
4606 Incorrect external names
4607
4608 @item
4609 Allocation from empty storage pool
4610
4611 @item
4612 Potentially blocking operation in protected type
4613
4614 @item
4615 Suspicious parenthesization of expressions
4616
4617 @item
4618 Mismatching bounds in an aggregate
4619
4620 @item
4621 Attempt to return local value by reference
4622
4623 @item
4624 Premature instantiation of a generic body
4625
4626 @item
4627 Attempt to pack aliased components
4628
4629 @item
4630 Out of bounds array subscripts
4631
4632 @item
4633 Wrong length on string assignment
4634
4635 @item
4636 Violations of style rules if style checking is enabled
4637
4638 @item
4639 Unused @code{with} clauses
4640
4641 @item
4642 @code{Bit_Order} usage that does not have any effect
4643
4644 @item
4645 @code{Standard.Duration} used to resolve universal fixed expression
4646
4647 @item
4648 Dereference of possibly null value
4649
4650 @item
4651 Declaration that is likely to cause storage error
4652
4653 @item
4654 Internal GNAT unit @code{with}'ed by application unit
4655
4656 @item
4657 Values known to be out of range at compile time
4658
4659 @item
4660 Unreferenced labels and variables
4661
4662 @item
4663 Address overlays that could clobber memory
4664
4665 @item
4666 Unexpected initialization when address clause present
4667
4668 @item
4669 Bad alignment for address clause
4670
4671 @item
4672 Useless type conversions
4673
4674 @item
4675 Redundant assignment statements and other redundant constructs
4676
4677 @item
4678 Useless exception handlers
4679
4680 @item
4681 Accidental hiding of name by child unit
4682
4683 @item
4684 Access before elaboration detected at compile time
4685
4686 @item
4687 A range in a @code{for} loop that is known to be null or might be null
4688
4689 @end itemize
4690
4691 @noindent
4692 The following section lists compiler switches that are available
4693 to control the handling of warning messages. It is also possible
4694 to exercise much finer control over what warnings are issued and
4695 suppressed using the GNAT pragma Warnings, which is documented
4696 in the GNAT Reference manual.
4697
4698 @table @option
4699 @c !sort!
4700 @item -gnatwa
4701 @emph{Activate all optional errors.}
4702 @cindex @option{-gnatwa} (@command{gcc})
4703 This switch activates most optional warning messages, see remaining list
4704 in this section for details on optional warning messages that can be
4705 individually controlled.  The warnings that are not turned on by this
4706 switch are
4707 @option{-gnatwd} (implicit dereferencing),
4708 @option{-gnatwh} (hiding),
4709 @option{-gnatwl} (elaboration warnings),
4710 and @option{-gnatwt} (tracking of deleted conditional code).
4711 All other optional warnings are turned on.
4712
4713 @item -gnatwA
4714 @emph{Suppress all optional errors.}
4715 @cindex @option{-gnatwA} (@command{gcc})
4716 This switch suppresses all optional warning messages, see remaining list
4717 in this section for details on optional warning messages that can be
4718 individually controlled.
4719
4720 @item -gnatwb
4721 @emph{Activate warnings on bad fixed values.}
4722 @cindex @option{-gnatwb} (@command{gcc})
4723 @cindex Bad fixed values
4724 @cindex Fixed-point Small value
4725 @cindex Small value
4726 This switch activates warnings for static fixed-point expressions whose
4727 value is not an exact multiple of Small. Such values are implementation
4728 dependent, since an implementation is free to choose either of the multiples
4729 that surround the value. GNAT always chooses the closer one, but this is not
4730 required behavior, and it is better to specify a value that is an exact
4731 multiple, ensuring predictable execution. The default is that such warnings
4732 are not generated.
4733
4734 @item -gnatwB
4735 @emph{Suppress warnings on bad fixed values.}
4736 @cindex @option{-gnatwB} (@command{gcc})
4737 This switch suppresses warnings for static fixed-point expressions whose
4738 value is not an exact multiple of Small.
4739
4740 @item -gnatwc
4741 @emph{Activate warnings on conditionals.}
4742 @cindex @option{-gnatwc} (@command{gcc})
4743 @cindex Conditionals, constant
4744 This switch activates warnings for conditional expressions used in
4745 tests that are known to be True or False at compile time. The default
4746 is that such warnings are not generated.
4747 Note that this warning does
4748 not get issued for the use of boolean variables or constants whose
4749 values are known at compile time, since this is a standard technique
4750 for conditional compilation in Ada, and this would generate too many
4751 false positive warnings.
4752
4753 This warning option also activates a special test for comparisons using
4754 the operators ``>='' and`` <=''.
4755 If the compiler can tell that only the equality condition is possible,
4756 then it will warn that the ``>'' or ``<'' part of the test
4757 is useless and that the operator could be replaced by ``=''.
4758 An example would be comparing a @code{Natural} variable <= 0.
4759
4760 This warning can also be turned on using @option{-gnatwa}.
4761
4762 @item -gnatwC
4763 @emph{Suppress warnings on conditionals.}
4764 @cindex @option{-gnatwC} (@command{gcc})
4765 This switch suppresses warnings for conditional expressions used in
4766 tests that are known to be True or False at compile time.
4767
4768 @item -gnatw.c
4769 @emph{Activate warnings on missing component clauses.}
4770 @cindex @option{-gnatw.c} (@command{gcc})
4771 @cindex Component clause, missing
4772 This switch activates warnings for record components where a record
4773 representation clause is present and has component clauses for the
4774 majority, but not all, of the components. A warning is given for each
4775 component for which no component clause is present.
4776
4777 This warning can also be turned on using @option{-gnatwa}.
4778
4779 @item -gnatw.C
4780 @emph{Suppress warnings on missing component clauses.}
4781 @cindex @option{-gnatwC} (@command{gcc})
4782 This switch suppresses warnings for record components that are
4783 missing a component clause in the situation described above.
4784
4785 @item -gnatwd
4786 @emph{Activate warnings on implicit dereferencing.}
4787 @cindex @option{-gnatwd} (@command{gcc})
4788 If this switch is set, then the use of a prefix of an access type
4789 in an indexed component, slice, or selected component without an
4790 explicit @code{.all} will generate a warning. With this warning
4791 enabled, access checks occur only at points where an explicit
4792 @code{.all} appears in the source code (assuming no warnings are
4793 generated as a result of this switch). The default is that such
4794 warnings are not generated.
4795 Note that @option{-gnatwa} does not affect the setting of
4796 this warning option.
4797
4798 @item -gnatwD
4799 @emph{Suppress warnings on implicit dereferencing.}
4800 @cindex @option{-gnatwD} (@command{gcc})
4801 @cindex Implicit dereferencing
4802 @cindex Dereferencing, implicit
4803 This switch suppresses warnings for implicit dereferences in
4804 indexed components, slices, and selected components.
4805
4806 @item -gnatwe
4807 @emph{Treat warnings as errors.}
4808 @cindex @option{-gnatwe} (@command{gcc})
4809 @cindex Warnings, treat as error
4810 This switch causes warning messages to be treated as errors.
4811 The warning string still appears, but the warning messages are counted
4812 as errors, and prevent the generation of an object file.
4813
4814 @item -gnatwf
4815 @emph{Activate warnings on unreferenced formals.}
4816 @cindex @option{-gnatwf} (@command{gcc})
4817 @cindex Formals, unreferenced
4818 This switch causes a warning to be generated if a formal parameter
4819 is not referenced in the body of the subprogram. This warning can
4820 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
4821 default is that these warnings are not generated.
4822
4823 @item -gnatwF
4824 @emph{Suppress warnings on unreferenced formals.}
4825 @cindex @option{-gnatwF} (@command{gcc})
4826 This switch suppresses warnings for unreferenced formal
4827 parameters. Note that the
4828 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4829 effect of warning on unreferenced entities other than subprogram
4830 formals.
4831
4832 @item -gnatwg
4833 @emph{Activate warnings on unrecognized pragmas.}
4834 @cindex @option{-gnatwg} (@command{gcc})
4835 @cindex Pragmas, unrecognized
4836 This switch causes a warning to be generated if an unrecognized
4837 pragma is encountered. Apart from issuing this warning, the
4838 pragma is ignored and has no effect. This warning can
4839 also be turned on using @option{-gnatwa}. The default
4840 is that such warnings are issued (satisfying the Ada Reference
4841 Manual requirement that such warnings appear).
4842
4843 @item -gnatwG
4844 @emph{Suppress warnings on unrecognized pragmas.}
4845 @cindex @option{-gnatwG} (@command{gcc})
4846 This switch suppresses warnings for unrecognized pragmas.
4847
4848 @item -gnatwh
4849 @emph{Activate warnings on hiding.}
4850 @cindex @option{-gnatwh} (@command{gcc})
4851 @cindex Hiding of Declarations
4852 This switch activates warnings on hiding declarations.
4853 A declaration is considered hiding
4854 if it is for a non-overloadable entity, and it declares an entity with the
4855 same name as some other entity that is directly or use-visible. The default
4856 is that such warnings are not generated.
4857 Note that @option{-gnatwa} does not affect the setting of this warning option.
4858
4859 @item -gnatwH
4860 @emph{Suppress warnings on hiding.}
4861 @cindex @option{-gnatwH} (@command{gcc})
4862 This switch suppresses warnings on hiding declarations.
4863
4864 @item -gnatwi
4865 @emph{Activate warnings on implementation units.}
4866 @cindex @option{-gnatwi} (@command{gcc})
4867 This switch activates warnings for a @code{with} of an internal GNAT
4868 implementation unit, defined as any unit from the @code{Ada},
4869 @code{Interfaces}, @code{GNAT},
4870 ^^@code{DEC},^ or @code{System}
4871 hierarchies that is not
4872 documented in either the Ada Reference Manual or the GNAT
4873 Programmer's Reference Manual. Such units are intended only
4874 for internal implementation purposes and should not be @code{with}'ed
4875 by user programs. The default is that such warnings are generated
4876 This warning can also be turned on using @option{-gnatwa}.
4877
4878 @item -gnatwI
4879 @emph{Disable warnings on implementation units.}
4880 @cindex @option{-gnatwI} (@command{gcc})
4881 This switch disables warnings for a @code{with} of an internal GNAT
4882 implementation unit.
4883
4884 @item -gnatwj
4885 @emph{Activate warnings on obsolescent features (Annex J).}
4886 @cindex @option{-gnatwj} (@command{gcc})
4887 @cindex Features, obsolescent
4888 @cindex Obsolescent features
4889 If this warning option is activated, then warnings are generated for
4890 calls to subprograms marked with @code{pragma Obsolescent} and
4891 for use of features in Annex J of the Ada Reference Manual. In the
4892 case of Annex J, not all features are flagged. In particular use
4893 of the renamed packages (like @code{Text_IO}) and use of package
4894 @code{ASCII} are not flagged, since these are very common and
4895 would generate many annoying positive warnings. The default is that
4896 such warnings are not generated. This warning is also turned on by
4897 the use of @option{-gnatwa}.
4898
4899 In addition to the above cases, warnings are also generated for
4900 GNAT features that have been provided in past versions but which
4901 have been superseded (typically by features in the new Ada standard).
4902 For example, @code{pragma Ravenscar} will be flagged since its
4903 function is replaced by @code{pragma Profile(Ravenscar)}.
4904
4905 Note that this warning option functions differently from the
4906 restriction @code{No_Obsolescent_Features} in two respects.
4907 First, the restriction applies only to annex J features.
4908 Second, the restriction does flag uses of package @code{ASCII}.
4909
4910 @item -gnatwJ
4911 @emph{Suppress warnings on obsolescent features (Annex J).}
4912 @cindex @option{-gnatwJ} (@command{gcc})
4913 This switch disables warnings on use of obsolescent features.
4914
4915 @item -gnatwk
4916 @emph{Activate warnings on variables that could be constants.}
4917 @cindex @option{-gnatwk} (@command{gcc})
4918 This switch activates warnings for variables that are initialized but
4919 never modified, and then could be declared constants. The default is that
4920 such warnings are not given.
4921 This warning can also be turned on using @option{-gnatwa}.
4922
4923 @item -gnatwK
4924 @emph{Suppress warnings on variables that could be constants.}
4925 @cindex @option{-gnatwK} (@command{gcc})
4926 This switch disables warnings on variables that could be declared constants.
4927
4928 @item -gnatwl
4929 @emph{Activate warnings for missing elaboration pragmas.}
4930 @cindex @option{-gnatwl} (@command{gcc})
4931 @cindex Elaboration, warnings
4932 This switch activates warnings on missing
4933 @code{Elaborate_All} and @code{Elaborate} pragmas.
4934 See the section in this guide on elaboration checking for details on
4935 when such pragmas should be used. Warnings are also generated if you
4936 are using the static mode of elaboration, and a @code{pragma Elaborate}
4937 is encountered. The default is that such warnings
4938 are not generated.
4939 This warning is not automatically turned on by the use of @option{-gnatwa}.
4940
4941 @item -gnatwL
4942 @emph{Suppress warnings for missing elaboration pragmas.}
4943 @cindex @option{-gnatwL} (@command{gcc})
4944 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
4945 See the section in this guide on elaboration checking for details on
4946 when such pragmas should be used.
4947
4948 @item -gnatwm
4949 @emph{Activate warnings on modified but unreferenced variables.}
4950 @cindex @option{-gnatwm} (@command{gcc})
4951 This switch activates warnings for variables that are assigned (using
4952 an initialization value or with one or more assignment statements) but
4953 whose value is never read. The warning is suppressed for volatile
4954 variables and also for variables that are renamings of other variables
4955 or for which an address clause is given.
4956 This warning can also be turned on using @option{-gnatwa}.
4957 The default is that these warnings are not given.
4958
4959 @item -gnatwM
4960 @emph{Disable warnings on modified but unreferenced variables.}
4961 @cindex @option{-gnatwM} (@command{gcc})
4962 This switch disables warnings for variables that are assigned or
4963 initialized, but never read.
4964
4965 @item -gnatwn
4966 @emph{Set normal warnings mode.}
4967 @cindex @option{-gnatwn} (@command{gcc})
4968 This switch sets normal warning mode, in which enabled warnings are
4969 issued and treated as warnings rather than errors. This is the default
4970 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4971 an explicit @option{-gnatws} or
4972 @option{-gnatwe}. It also cancels the effect of the
4973 implicit @option{-gnatwe} that is activated by the
4974 use of @option{-gnatg}.
4975
4976 @item -gnatwo
4977 @emph{Activate warnings on address clause overlays.}
4978 @cindex @option{-gnatwo} (@command{gcc})
4979 @cindex Address Clauses, warnings
4980 This switch activates warnings for possibly unintended initialization
4981 effects of defining address clauses that cause one variable to overlap
4982 another. The default is that such warnings are generated.
4983 This warning can also be turned on using @option{-gnatwa}.
4984
4985 @item -gnatwO
4986 @emph{Suppress warnings on address clause overlays.}
4987 @cindex @option{-gnatwO} (@command{gcc})
4988 This switch suppresses warnings on possibly unintended initialization
4989 effects of defining address clauses that cause one variable to overlap
4990 another.
4991
4992 @item -gnatwp
4993 @emph{Activate warnings on ineffective pragma Inlines.}
4994 @cindex @option{-gnatwp} (@command{gcc})
4995 @cindex Inlining, warnings
4996 This switch activates warnings for failure of front end inlining
4997 (activated by @option{-gnatN}) to inline a particular call. There are
4998 many reasons for not being able to inline a call, including most
4999 commonly that the call is too complex to inline. The default is
5000 that such warnings are not given.
5001 This warning can also be turned on using @option{-gnatwa}.
5002 Warnings on ineffective inlining by the gcc back-end can be activated
5003 separately, using the gcc switch -Winline.
5004
5005 @item -gnatwP
5006 @emph{Suppress warnings on ineffective pragma Inlines.}
5007 @cindex @option{-gnatwP} (@command{gcc})
5008 This switch suppresses warnings on ineffective pragma Inlines. If the
5009 inlining mechanism cannot inline a call, it will simply ignore the
5010 request silently.
5011
5012 @item -gnatwq
5013 @emph{Activate warnings on questionable missing parentheses.}
5014 @cindex @option{-gnatwq} (@command{gcc})
5015 @cindex Parentheses, warnings
5016 This switch activates warnings for cases where parentheses are not used and
5017 the result is potential ambiguity from a readers point of view. For example
5018 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5019 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5020 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5021 follow the rule of always parenthesizing to make the association clear, and
5022 this warning switch warns if such parentheses are not present. The default
5023 is that these warnings are given.
5024 This warning can also be turned on using @option{-gnatwa}.
5025
5026 @item -gnatwQ
5027 @emph{Suppress warnings on questionable missing parentheses.}
5028 @cindex @option{-gnatwQ} (@command{gcc})
5029 This switch suppresses warnings for cases where the association is not
5030 clear and the use of parentheses is preferred.
5031
5032 @item -gnatwr
5033 @emph{Activate warnings on redundant constructs.}
5034 @cindex @option{-gnatwr} (@command{gcc})
5035 This switch activates warnings for redundant constructs. The following
5036 is the current list of constructs regarded as redundant:
5037
5038 @itemize @bullet
5039 @item
5040 Assignment of an item to itself.
5041 @item
5042 Type conversion that converts an expression to its own type.
5043 @item
5044 Use of the attribute @code{Base} where @code{typ'Base} is the same
5045 as @code{typ}.
5046 @item
5047 Use of pragma @code{Pack} when all components are placed by a record
5048 representation clause.
5049 @item
5050 Exception handler containing only a reraise statement (raise with no
5051 operand) which has no effect.
5052 @item
5053 Use of the operator abs on an operand that is known at compile time
5054 to be non-negative
5055 @item
5056 Comparison of boolean expressions to an explicit True value.
5057 @end itemize
5058
5059 This warning can also be turned on using @option{-gnatwa}.
5060 The default is that warnings for redundant constructs are not given.
5061
5062 @item -gnatwR
5063 @emph{Suppress warnings on redundant constructs.}
5064 @cindex @option{-gnatwR} (@command{gcc})
5065 This switch suppresses warnings for redundant constructs.
5066
5067 @item -gnatws
5068 @emph{Suppress all warnings.}
5069 @cindex @option{-gnatws} (@command{gcc})
5070 This switch completely suppresses the
5071 output of all warning messages from the GNAT front end.
5072 Note that it does not suppress warnings from the @command{gcc} back end.
5073 To suppress these back end warnings as well, use the switch @option{-w}
5074 in addition to @option{-gnatws}.
5075
5076 @item -gnatwt
5077 @emph{Activate warnings for tracking of deleted conditional code.}
5078 @cindex @option{-gnatwt} (@command{gcc})
5079 @cindex Deactivated code, warnings
5080 @cindex Deleted code, warnings
5081 This switch activates warnings for tracking of code in conditionals (IF and
5082 CASE statements) that is detected to be dead code which cannot be executed, and
5083 which is removed by the front end. This warning is off by default, and is not
5084 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5085 useful for detecting deactivated code in certified applications.
5086
5087 @item -gnatwT
5088 @emph{Suppress warnings for tracking of deleted conditional code.}
5089 @cindex @option{-gnatwT} (@command{gcc})
5090 This switch suppresses warnings for tracking of deleted conditional code.
5091
5092 @item -gnatwu
5093 @emph{Activate warnings on unused entities.}
5094 @cindex @option{-gnatwu} (@command{gcc})
5095 This switch activates warnings to be generated for entities that
5096 are declared but not referenced, and for units that are @code{with}'ed
5097 and not
5098 referenced. In the case of packages, a warning is also generated if
5099 no entities in the package are referenced. This means that if the package
5100 is referenced but the only references are in @code{use}
5101 clauses or @code{renames}
5102 declarations, a warning is still generated. A warning is also generated
5103 for a generic package that is @code{with}'ed but never instantiated.
5104 In the case where a package or subprogram body is compiled, and there
5105 is a @code{with} on the corresponding spec
5106 that is only referenced in the body,
5107 a warning is also generated, noting that the
5108 @code{with} can be moved to the body. The default is that
5109 such warnings are not generated.
5110 This switch also activates warnings on unreferenced formals
5111 (it includes the effect of @option{-gnatwf}).
5112 This warning can also be turned on using @option{-gnatwa}.
5113
5114 @item -gnatwU
5115 @emph{Suppress warnings on unused entities.}
5116 @cindex @option{-gnatwU} (@command{gcc})
5117 This switch suppresses warnings for unused entities and packages.
5118 It also turns off warnings on unreferenced formals (and thus includes
5119 the effect of @option{-gnatwF}).
5120
5121 @item -gnatwv
5122 @emph{Activate warnings on unassigned variables.}
5123 @cindex @option{-gnatwv} (@command{gcc})
5124 @cindex Unassigned variable warnings
5125 This switch activates warnings for access to variables which
5126 may not be properly initialized. The default is that
5127 such warnings are generated.
5128 This warning can also be turned on using @option{-gnatwa}.
5129
5130 @item -gnatwV
5131 @emph{Suppress warnings on unassigned variables.}
5132 @cindex @option{-gnatwV} (@command{gcc})
5133 This switch suppresses warnings for access to variables which
5134 may not be properly initialized.
5135 For variables of a composite type, the warning can also be suppressed in
5136 Ada 2005 by using a default initialization with a box. For example, if
5137 Table is an array of records whose components are only partially uninitialized,
5138 then the following code:
5139
5140 @smallexample @c ada
5141    Tab : Table := (others => <>);
5142 @end smallexample
5143
5144 will suppress warnings on subsequent statements that access components
5145 of variable Tab.
5146
5147 @item -gnatww
5148 @emph{Activate warnings on wrong low bound assumption.}
5149 @cindex @option{-gnatww} (@command{gcc})
5150 @cindex String indexing warnings
5151 This switch activates warnings for indexing an unconstrained string parameter
5152 with a literal or S'Length. This is a case where the code is assuming that the
5153 low bound is one, which is in general not true (for example when a slice is
5154 passed). The default is that such warnings are generated.
5155 This warning can also be turned on using @option{-gnatwa}.
5156
5157 @item -gnatwW
5158 @emph{Suppress warnings on wrong low bound assumption.}
5159 @cindex @option{-gnatwW} (@command{gcc})
5160 This switch activates warnings for indexing an unconstrained string parameter
5161 with a literal or S'Length. This warning can also be suppressed by providing
5162 an Assert pragma that checks the low bound, for example:
5163
5164 @smallexample @c ada
5165    procedure K (S : String) is
5166       pragma Assert (S'First = 1);
5167       ...
5168 @end smallexample
5169
5170 @item -gnatwx
5171 @emph{Activate warnings on Export/Import pragmas.}
5172 @cindex @option{-gnatwx} (@command{gcc})
5173 @cindex Export/Import pragma warnings
5174 This switch activates warnings on Export/Import pragmas when
5175 the compiler detects a possible conflict between the Ada and
5176 foreign language calling sequences. For example, the use of
5177 default parameters in a convention C procedure is dubious
5178 because the C compiler cannot supply the proper default, so
5179 a warning is issued. The default is that such warnings are
5180 generated.
5181 This warning can also be turned on using @option{-gnatwa}.
5182
5183 @item -gnatwX
5184 @emph{Suppress warnings on Export/Import pragmas.}
5185 @cindex @option{-gnatwX} (@command{gcc})
5186 This switch suppresses warnings on Export/Import pragmas.
5187 The sense of this is that you are telling the compiler that
5188 you know what you are doing in writing the pragma, and it
5189 should not complain at you.
5190
5191 @item -gnatw.x
5192 @emph{Activate warnings for No_Exception_Propagation mode.}
5193 @cindex @option{-gnatwm} (@command{gcc})
5194 This switch activates warnings for exception usage when pragma Restrictions
5195 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5196 explicit exception raises which are not covered by a local handler, and for
5197 exception handlers which do not cover a local raise. The default is that these
5198 warnings are given.
5199
5200 @item -gnatw.X
5201 @emph{Disable warnings for No_Exception_Propagation mode.}
5202 This switch disables warnings for exception usage when pragma Restrictions
5203 (No_Exception_Propagation) is in effect.
5204
5205 @item -gnatwy
5206 @emph{Activate warnings for Ada 2005 compatibility issues.}
5207 @cindex @option{-gnatwy} (@command{gcc})
5208 @cindex Ada 2005 compatibility issues warnings
5209 For the most part Ada 2005 is upwards compatible with Ada 95,
5210 but there are some exceptions (for example the fact that
5211 @code{interface} is now a reserved word in Ada 2005). This
5212 switch activates several warnings to help in identifying
5213 and correcting such incompatibilities. The default is that
5214 these warnings are generated. Note that at one point Ada 2005
5215 was called Ada 0Y, hence the choice of character.
5216 This warning can also be turned on using @option{-gnatwa}.
5217
5218 @item -gnatwY
5219 @emph{Disable warnings for Ada 2005 compatibility issues.}
5220 @cindex @option{-gnatwY} (@command{gcc})
5221 @cindex Ada 2005 compatibility issues warnings
5222 This switch suppresses several warnings intended to help in identifying
5223 incompatibilities between Ada 95 and Ada 2005.
5224
5225 @item -gnatwz
5226 @emph{Activate warnings on unchecked conversions.}
5227 @cindex @option{-gnatwz} (@command{gcc})
5228 @cindex Unchecked_Conversion warnings
5229 This switch activates warnings for unchecked conversions
5230 where the types are known at compile time to have different
5231 sizes. The default
5232 is that such warnings are generated.
5233 This warning can also be turned on using @option{-gnatwa}.
5234
5235 @item -gnatwZ
5236 @emph{Suppress warnings on unchecked conversions.}
5237 @cindex @option{-gnatwZ} (@command{gcc})
5238 This switch suppresses warnings for unchecked conversions
5239 where the types are known at compile time to have different
5240 sizes.
5241
5242 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5243 @cindex @option{-Wuninitialized}
5244 The warnings controlled by the @option{-gnatw} switch are generated by the
5245 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
5246 can provide additional warnings. One such useful warning is provided by
5247 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
5248 conjunction with turning on optimization mode. This causes the flow
5249 analysis circuits of the back end optimizer to output additional
5250 warnings about uninitialized variables.
5251
5252 @item ^-w^/NO_BACK_END_WARNINGS^
5253 @cindex @option{-w}
5254 This switch suppresses warnings from the @option{^gcc^GCC^} back end. The
5255 code generator detects a number of warning situations that are missed
5256 by the @option{GNAT} front end, and this switch can be used to suppress them.
5257 The use of this switch also sets the default front end warning mode to
5258 @option{-gnatws}, that is, front end warnings suppressed as well.
5259
5260 @end table
5261
5262 @noindent
5263 @ifclear vms
5264 A string of warning parameters can be used in the same parameter. For example:
5265
5266 @smallexample
5267 -gnatwaLe
5268 @end smallexample
5269
5270 @noindent
5271 will turn on all optional warnings except for elaboration pragma warnings,
5272 and also specify that warnings should be treated as errors.
5273 @end ifclear
5274 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5275
5276 @table @option
5277 @c !sort!
5278 @item -gnatwC
5279 @item -gnatwD
5280 @item -gnatwF
5281 @item -gnatwg
5282 @item -gnatwH
5283 @item -gnatwi
5284 @item -gnatwJ
5285 @item -gnatwK
5286 @item -gnatwL
5287 @item -gnatwM
5288 @item -gnatwn
5289 @item -gnatwo
5290 @item -gnatwP
5291 @item -gnatwR
5292 @item -gnatwU
5293 @item -gnatwv
5294 @item -gnatwz
5295 @item -gnatwx
5296
5297 @end table
5298
5299 @node Debugging and Assertion Control
5300 @subsection Debugging and Assertion Control
5301
5302 @table @option
5303 @item -gnata
5304 @cindex @option{-gnata} (@command{gcc})
5305 @findex Assert
5306 @findex Debug
5307 @cindex Assertions
5308
5309 @noindent
5310 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5311 are ignored. This switch, where @samp{a} stands for assert, causes
5312 @code{Assert} and @code{Debug} pragmas to be activated.
5313
5314 The pragmas have the form:
5315
5316 @smallexample
5317 @cartouche
5318    @b{pragma} Assert (@var{Boolean-expression} [,
5319                       @var{static-string-expression}])
5320    @b{pragma} Debug (@var{procedure call})
5321 @end cartouche
5322 @end smallexample
5323
5324 @noindent
5325 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5326 If the result is @code{True}, the pragma has no effect (other than
5327 possible side effects from evaluating the expression). If the result is
5328 @code{False}, the exception @code{Assert_Failure} declared in the package
5329 @code{System.Assertions} is
5330 raised (passing @var{static-string-expression}, if present, as the
5331 message associated with the exception). If no string expression is
5332 given the default is a string giving the file name and line number
5333 of the pragma.
5334
5335 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5336 @code{pragma Debug} may appear within a declaration sequence, allowing
5337 debugging procedures to be called between declarations.
5338
5339 @ifset vms
5340 @item /DEBUG[=debug-level]
5341 @itemx  /NODEBUG
5342 Specifies how much debugging information is to be included in
5343 the resulting object file where 'debug-level' is one of the following:
5344 @table @code
5345 @item   TRACEBACK
5346 Include both debugger symbol records and traceback
5347 the object file.
5348 This is the default setting.
5349 @item   ALL
5350 Include both debugger symbol records and traceback in
5351 object file.
5352 @item   NONE
5353 Excludes both debugger symbol records and traceback
5354 the object file. Same as /NODEBUG.
5355 @item   SYMBOLS
5356 Includes only debugger symbol records in the object
5357 file. Note that this doesn't include traceback information.
5358 @end table
5359 @end ifset
5360 @end table
5361
5362 @node Validity Checking
5363 @subsection Validity Checking
5364 @findex Validity Checking
5365
5366 @noindent
5367 The Ada Reference Manual has specific requirements for checking
5368 for invalid values. In particular, RM 13.9.1 requires that the
5369 evaluation of invalid values (for example from unchecked conversions),
5370 not result in erroneous execution. In GNAT, the result of such an
5371 evaluation in normal default mode is to either use the value
5372 unmodified, or to raise Constraint_Error in those cases where use
5373 of the unmodified value would cause erroneous execution. The cases
5374 where unmodified values might lead to erroneous execution are case
5375 statements (where a wild jump might result from an invalid value),
5376 and subscripts on the left hand side (where memory corruption could
5377 occur as a result of an invalid value).
5378
5379 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5380 checking mode.
5381 @ifclear vms
5382 The @code{x} argument is a string of letters that
5383 indicate validity checks that are performed or not performed in addition
5384 to the default checks described above.
5385 @end ifclear
5386 @ifset vms
5387 The options allowed for this qualifier
5388 indicate validity checks that are performed or not performed in addition
5389 to the default checks described above.
5390 @end ifset
5391
5392 @table @option
5393 @c !sort!
5394 @item -gnatVa
5395 @emph{All validity checks.}
5396 @cindex @option{-gnatVa} (@command{gcc})
5397 All validity checks are turned on.
5398 @ifclear vms
5399 That is, @option{-gnatVa} is
5400 equivalent to @option{gnatVcdfimorst}.
5401 @end ifclear
5402
5403 @item -gnatVc
5404 @emph{Validity checks for copies.}
5405 @cindex @option{-gnatVc} (@command{gcc})
5406 The right hand side of assignments, and the initializing values of
5407 object declarations are validity checked.
5408
5409 @item -gnatVd
5410 @emph{Default (RM) validity checks.}
5411 @cindex @option{-gnatVd} (@command{gcc})
5412 Some validity checks are done by default following normal Ada semantics
5413 (RM 13.9.1 (9-11)).
5414 A check is done in case statements that the expression is within the range
5415 of the subtype. If it is not, Constraint_Error is raised.
5416 For assignments to array components, a check is done that the expression used
5417 as index is within the range. If it is not, Constraint_Error is raised.
5418 Both these validity checks may be turned off using switch @option{-gnatVD}.
5419 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5420 switch @option{-gnatVd} will leave the checks turned on.
5421 Switch @option{-gnatVD} should be used only if you are sure that all such
5422 expressions have valid values. If you use this switch and invalid values
5423 are present, then the program is erroneous, and wild jumps or memory
5424 overwriting may occur.
5425
5426 @item -gnatVe
5427 @emph{Validity checks for elementary components.}
5428 @cindex @option{-gnatVe} (@command{gcc})
5429 In the absence of this switch, assignments to record or array components are
5430 not validity checked, even if validity checks for assignments generally
5431 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5432 require valid data, but assignment of individual components does. So for
5433 example, there is a difference between copying the elements of an array with a
5434 slice assignment, compared to assigning element by element in a loop. This
5435 switch allows you to turn off validity checking for components, even when they
5436 are assigned component by component.
5437
5438 @item -gnatVf
5439 @emph{Validity checks for floating-point values.}
5440 @cindex @option{-gnatVf} (@command{gcc})
5441 In the absence of this switch, validity checking occurs only for discrete
5442 values. If @option{-gnatVf} is specified, then validity checking also applies
5443 for floating-point values, and NaN's and infinities are considered invalid,
5444 as well as out of range values for constrained types. Note that this means
5445 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5446 in which floating-point values are checked depends on the setting of other
5447 options. For example,
5448 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5449 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5450 (the order does not matter) specifies that floating-point parameters of mode
5451 @code{in} should be validity checked.
5452
5453 @item -gnatVi
5454 @emph{Validity checks for @code{in} mode parameters}
5455 @cindex @option{-gnatVi} (@command{gcc})
5456 Arguments for parameters of mode @code{in} are validity checked in function
5457 and procedure calls at the point of call.
5458
5459 @item -gnatVm
5460 @emph{Validity checks for @code{in out} mode parameters.}
5461 @cindex @option{-gnatVm} (@command{gcc})
5462 Arguments for parameters of mode @code{in out} are validity checked in
5463 procedure calls at the point of call. The @code{'m'} here stands for
5464 modify, since this concerns parameters that can be modified by the call.
5465 Note that there is no specific option to test @code{out} parameters,
5466 but any reference within the subprogram will be tested in the usual
5467 manner, and if an invalid value is copied back, any reference to it
5468 will be subject to validity checking.
5469
5470 @item -gnatVn
5471 @emph{No validity checks.}
5472 @cindex @option{-gnatVn} (@command{gcc})
5473 This switch turns off all validity checking, including the default checking
5474 for case statements and left hand side subscripts. Note that the use of
5475 the switch @option{-gnatp} suppresses all run-time checks, including
5476 validity checks, and thus implies @option{-gnatVn}. When this switch
5477 is used, it cancels any other @option{-gnatV} previously issued.
5478
5479 @item -gnatVo
5480 @emph{Validity checks for operator and attribute operands.}
5481 @cindex @option{-gnatVo} (@command{gcc})
5482 Arguments for predefined operators and attributes are validity checked.
5483 This includes all operators in package @code{Standard},
5484 the shift operators defined as intrinsic in package @code{Interfaces}
5485 and operands for attributes such as @code{Pos}. Checks are also made
5486 on individual component values for composite comparisons, and on the
5487 expressions in type conversions and qualified expressions. Checks are
5488 also made on explicit ranges using .. (e.g. slices, loops etc).
5489
5490 @item -gnatVp
5491 @emph{Validity checks for parameters.}
5492 @cindex @option{-gnatVp} (@command{gcc})
5493 This controls the treatment of parameters within a subprogram (as opposed
5494 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5495 of parameters on a call. If either of these call options is used, then
5496 normally an assumption is made within a subprogram that the input arguments
5497 have been validity checking at the point of call, and do not need checking
5498 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5499 is not made, and parameters are not assumed to be valid, so their validity
5500 will be checked (or rechecked) within the subprogram.
5501
5502 @item -gnatVr
5503 @emph{Validity checks for function returns.}
5504 @cindex @option{-gnatVr} (@command{gcc})
5505 The expression in @code{return} statements in functions is validity
5506 checked.
5507
5508 @item -gnatVs
5509 @emph{Validity checks for subscripts.}
5510 @cindex @option{-gnatVs} (@command{gcc})
5511 All subscripts expressions are checked for validity, whether they appear
5512 on the right side or left side (in default mode only left side subscripts
5513 are validity checked).
5514
5515 @item -gnatVt
5516 @emph{Validity checks for tests.}
5517 @cindex @option{-gnatVt} (@command{gcc})
5518 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5519 statements are checked, as well as guard expressions in entry calls.
5520
5521 @end table
5522
5523 @noindent
5524 The @option{-gnatV} switch may be followed by
5525 ^a string of letters^a list of options^
5526 to turn on a series of validity checking options.
5527 For example,
5528 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5529 specifies that in addition to the default validity checking, copies and
5530 function return expressions are to be validity checked.
5531 In order to make it easier
5532 to specify the desired combination of effects,
5533 @ifclear vms
5534 the upper case letters @code{CDFIMORST} may
5535 be used to turn off the corresponding lower case option.
5536 @end ifclear
5537 @ifset vms
5538 the prefix @code{NO} on an option turns off the corresponding validity
5539 checking:
5540 @itemize @bullet
5541 @item @code{NOCOPIES}
5542 @item @code{NODEFAULT}
5543 @item @code{NOFLOATS}
5544 @item @code{NOIN_PARAMS}
5545 @item @code{NOMOD_PARAMS}
5546 @item @code{NOOPERANDS}
5547 @item @code{NORETURNS}
5548 @item @code{NOSUBSCRIPTS}
5549 @item @code{NOTESTS}
5550 @end itemize
5551 @end ifset
5552 Thus
5553 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5554 turns on all validity checking options except for
5555 checking of @code{@b{in out}} procedure arguments.
5556
5557 The specification of additional validity checking generates extra code (and
5558 in the case of @option{-gnatVa} the code expansion can be substantial.
5559 However, these additional checks can be very useful in detecting
5560 uninitialized variables, incorrect use of unchecked conversion, and other
5561 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5562 is useful in conjunction with the extra validity checking, since this
5563 ensures that wherever possible uninitialized variables have invalid values.
5564
5565 See also the pragma @code{Validity_Checks} which allows modification of
5566 the validity checking mode at the program source level, and also allows for
5567 temporary disabling of validity checks.
5568
5569 @node Style Checking
5570 @subsection Style Checking
5571 @findex Style checking
5572
5573 @noindent
5574 The @option{-gnaty^x^(option,option,...)^} switch
5575 @cindex @option{-gnaty} (@command{gcc})
5576 causes the compiler to
5577 enforce specified style rules. A limited set of style rules has been used
5578 in writing the GNAT sources themselves. This switch allows user programs
5579 to activate all or some of these checks. If the source program fails a
5580 specified style check, an appropriate warning message is given, preceded by
5581 the character sequence ``(style)''.
5582 @ifset vms
5583 @code{(option,option,...)} is a sequence of keywords
5584 @end ifset
5585 @ifclear vms
5586 The string @var{x} is a sequence of letters or digits
5587 @end ifclear
5588 indicating the particular style
5589 checks to be performed. The following checks are defined:
5590
5591 @table @option
5592 @c !sort!
5593 @item 1-9
5594 @emph{Specify indentation level.}
5595 If a digit from 1-9 appears
5596 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5597 then proper indentation is checked, with the digit indicating the
5598 indentation level required.
5599 The general style of required indentation is as specified by
5600 the examples in the Ada Reference Manual. Full line comments must be
5601 aligned with the @code{--} starting on a column that is a multiple of
5602 the alignment level.
5603
5604 @item ^a^ATTRIBUTE^
5605 @emph{Check attribute casing.}
5606 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5607 then attribute names, including the case of keywords such as @code{digits}
5608 used as attributes names, must be written in mixed case, that is, the
5609 initial letter and any letter following an underscore must be uppercase.
5610 All other letters must be lowercase.
5611
5612 @item ^A^ARRAY_INDEXES^
5613 @emph{Use of array index numbers in array attributes.}
5614 If the ^letter A^word ARRAY_INDEXES^ appears in the string after
5615 @option{-gnaty} then when using the array attributes First, Last, Range,
5616 or Length, the index number must be omitted for one-dimensional arrays
5617 and is required for multi-dimensional arrays.
5618
5619 @item ^b^BLANKS^
5620 @emph{Blanks not allowed at statement end.}
5621 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5622 trailing blanks are not allowed at the end of statements. The purpose of this
5623 rule, together with h (no horizontal tabs), is to enforce a canonical format
5624 for the use of blanks to separate source tokens.
5625
5626 @item ^c^COMMENTS^
5627 @emph{Check comments.}
5628 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5629 then comments must meet the following set of rules:
5630
5631 @itemize @bullet
5632
5633 @item
5634 The ``@code{--}'' that starts the column must either start in column one,
5635 or else at least one blank must precede this sequence.
5636
5637 @item
5638 Comments that follow other tokens on a line must have at least one blank
5639 following the ``@code{--}'' at the start of the comment.
5640
5641 @item
5642 Full line comments must have two blanks following the ``@code{--}'' that
5643 starts the comment, with the following exceptions.
5644
5645 @item
5646 A line consisting only of the ``@code{--}'' characters, possibly preceded
5647 by blanks is permitted.
5648
5649 @item
5650 A comment starting with ``@code{--x}'' where @code{x} is a special character
5651 is permitted.
5652 This allows proper processing of the output generated by specialized tools
5653 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5654 annotation
5655 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5656 special character is defined as being in one of the ASCII ranges
5657 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5658 Note that this usage is not permitted
5659 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5660
5661 @item
5662 A line consisting entirely of minus signs, possibly preceded by blanks, is
5663 permitted. This allows the construction of box comments where lines of minus
5664 signs are used to form the top and bottom of the box.
5665
5666 @item
5667 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5668 least one blank follows the initial ``@code{--}''. Together with the preceding
5669 rule, this allows the construction of box comments, as shown in the following
5670 example:
5671 @smallexample
5672 ---------------------------
5673 -- This is a box comment --
5674 -- with two text lines.  --
5675 ---------------------------
5676 @end smallexample
5677 @end itemize
5678
5679 @item ^d^DOS_LINE_ENDINGS^
5680 @emph{Check no DOS line terminators present.}
5681 If the ^letter d^word DOS_LINE_ENDINGS^ appears in the string after
5682 @option{-gnaty} then all lines must be terminated by a single ASCII.LF
5683 character (in particular the DOS line terminator sequence CR/LF is not
5684 allowed).
5685
5686 @item ^e^END^
5687 @emph{Check end/exit labels.}
5688 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5689 optional labels on @code{end} statements ending subprograms and on
5690 @code{exit} statements exiting named loops, are required to be present.
5691
5692 @item ^f^VTABS^
5693 @emph{No form feeds or vertical tabs.}
5694 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5695 neither form feeds nor vertical tab characters are permitted
5696 in the source text.
5697
5698 @item ^g^GNAT^
5699 @emph{GNAT style mode}
5700 If the ^letter g^word GNAT^ appears in the string after @option{-gnaty} then
5701 the set of style check switches is set to match that used by the GNAT sources.
5702 This may be useful when developing code that is eventually intended to be
5703 incorporated into GNAT. For further details, see GNAT sources.
5704
5705 @item ^h^HTABS^
5706 @emph{No horizontal tabs.}
5707 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5708 horizontal tab characters are not permitted in the source text.
5709 Together with the b (no blanks at end of line) check, this
5710 enforces a canonical form for the use of blanks to separate
5711 source tokens.
5712
5713 @item ^i^IF_THEN^
5714 @emph{Check if-then layout.}
5715 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5716 then the keyword @code{then} must appear either on the same
5717 line as corresponding @code{if}, or on a line on its own, lined
5718 up under the @code{if} with at least one non-blank line in between
5719 containing all or part of the condition to be tested.
5720
5721 @item ^I^IN_MODE^
5722 @emph{check mode IN keywords}
5723 If the ^letter I (upper case)^word IN_MODE^ appears in the string
5724 after @option{-gnaty} then mode @code{in} (the default mode) is not
5725 allowed to be given explicitly. @code{in out} is fine,
5726 but not @code{in} on its own.
5727
5728 @item ^k^KEYWORD^
5729 @emph{Check keyword casing.}
5730 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5731 all keywords must be in lower case (with the exception of keywords
5732 such as @code{digits} used as attribute names to which this check
5733 does not apply).
5734
5735 @item ^l^LAYOUT^
5736 @emph{Check layout.}
5737 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5738 layout of statement and declaration constructs must follow the
5739 recommendations in the Ada Reference Manual, as indicated by the
5740 form of the syntax rules. For example an @code{else} keyword must
5741 be lined up with the corresponding @code{if} keyword.
5742
5743 There are two respects in which the style rule enforced by this check
5744 option are more liberal than those in the Ada Reference Manual. First
5745 in the case of record declarations, it is permissible to put the
5746 @code{record} keyword on the same line as the @code{type} keyword, and
5747 then the @code{end} in @code{end record} must line up under @code{type}.
5748 This is also permitted when the type declaration is split on two lines.
5749 For example, any of the following three layouts is acceptable:
5750
5751 @smallexample @c ada
5752 @cartouche
5753 type q is record
5754    a : integer;
5755    b : integer;
5756 end record;
5757
5758 type q is
5759    record
5760       a : integer;
5761       b : integer;
5762    end record;
5763
5764 type q is
5765    record
5766       a : integer;
5767       b : integer;
5768 end record;
5769
5770 @end cartouche
5771 @end smallexample
5772
5773 @noindent
5774 Second, in the case of a block statement, a permitted alternative
5775 is to put the block label on the same line as the @code{declare} or
5776 @code{begin} keyword, and then line the @code{end} keyword up under
5777 the block label. For example both the following are permitted:
5778
5779 @smallexample @c ada
5780 @cartouche
5781 Block : declare
5782    A : Integer := 3;
5783 begin
5784    Proc (A, A);
5785 end Block;
5786
5787 Block :
5788    declare
5789       A : Integer := 3;
5790    begin
5791       Proc (A, A);
5792    end Block;
5793 @end cartouche
5794 @end smallexample
5795
5796 @noindent
5797 The same alternative format is allowed for loops. For example, both of
5798 the following are permitted:
5799
5800 @smallexample @c ada
5801 @cartouche
5802 Clear : while J < 10 loop
5803    A (J) := 0;
5804 end loop Clear;
5805
5806 Clear :
5807    while J < 10 loop
5808       A (J) := 0;
5809    end loop Clear;
5810 @end cartouche
5811 @end smallexample
5812
5813 @item ^Lnnn^MAX_NESTING=nnn^
5814 @emph{Set maximum nesting level}
5815 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5816 the range 0-999, appears in the string after @option{-gnaty} then the
5817 maximum level of nesting of constructs (including subprograms, loops,
5818 blocks, packages, and conditionals) may not exceed the given value. A
5819 value of zero disconnects this style check.
5820
5821 @item ^m^LINE_LENGTH^
5822 @emph{Check maximum line length.}
5823 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5824 then the length of source lines must not exceed 79 characters, including
5825 any trailing blanks. The value of 79 allows convenient display on an
5826 80 character wide device or window, allowing for possible special
5827 treatment of 80 character lines. Note that this count is of
5828 characters in the source text. This means that a tab character counts
5829 as one character in this count but a wide character sequence counts as
5830 a single character (however many bytes are needed in the encoding).
5831
5832 @item ^Mnnn^MAX_LENGTH=nnn^
5833 @emph{Set maximum line length.}
5834 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5835 the string after @option{-gnaty} then the length of lines must not exceed the
5836 given value. The maximum value that can be specified is 32767.
5837
5838 @item ^n^STANDARD_CASING^
5839 @emph{Check casing of entities in Standard.}
5840 If the ^letter n^word STANDARD_CASING^ appears in the string
5841 after @option{-gnaty} then any identifier from Standard must be cased
5842 to match the presentation in the Ada Reference Manual (for example,
5843 @code{Integer} and @code{ASCII.NUL}).
5844
5845 @item ^o^ORDERED_SUBPROGRAMS^
5846 @emph{Check order of subprogram bodies.}
5847 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5848 after @option{-gnaty} then all subprogram bodies in a given scope
5849 (e.g. a package body) must be in alphabetical order. The ordering
5850 rule uses normal Ada rules for comparing strings, ignoring casing
5851 of letters, except that if there is a trailing numeric suffix, then
5852 the value of this suffix is used in the ordering (e.g. Junk2 comes
5853 before Junk10).
5854
5855 @item ^p^PRAGMA^
5856 @emph{Check pragma casing.}
5857 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5858 pragma names must be written in mixed case, that is, the
5859 initial letter and any letter following an underscore must be uppercase.
5860 All other letters must be lowercase.
5861
5862 @item ^r^REFERENCES^
5863 @emph{Check references.}
5864 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5865 then all identifier references must be cased in the same way as the
5866 corresponding declaration. No specific casing style is imposed on
5867 identifiers. The only requirement is for consistency of references
5868 with declarations.
5869
5870 @item ^s^SPECS^
5871 @emph{Check separate specs.}
5872 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5873 separate declarations (``specs'') are required for subprograms (a
5874 body is not allowed to serve as its own declaration). The only
5875 exception is that parameterless library level procedures are
5876 not required to have a separate declaration. This exception covers
5877 the most frequent form of main program procedures.
5878
5879 @item ^t^TOKEN^
5880 @emph{Check token spacing.}
5881 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5882 the following token spacing rules are enforced:
5883
5884 @itemize @bullet
5885
5886 @item
5887 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5888
5889 @item
5890 The token @code{=>} must be surrounded by spaces.
5891
5892 @item
5893 The token @code{<>} must be preceded by a space or a left parenthesis.
5894
5895 @item
5896 Binary operators other than @code{**} must be surrounded by spaces.
5897 There is no restriction on the layout of the @code{**} binary operator.
5898
5899 @item
5900 Colon must be surrounded by spaces.
5901
5902 @item
5903 Colon-equal (assignment, initialization) must be surrounded by spaces.
5904
5905 @item
5906 Comma must be the first non-blank character on the line, or be
5907 immediately preceded by a non-blank character, and must be followed
5908 by a space.
5909
5910 @item
5911 If the token preceding a left parenthesis ends with a letter or digit, then
5912 a space must separate the two tokens.
5913
5914 @item
5915 A right parenthesis must either be the first non-blank character on
5916 a line, or it must be preceded by a non-blank character.
5917
5918 @item
5919 A semicolon must not be preceded by a space, and must not be followed by
5920 a non-blank character.
5921
5922 @item
5923 A unary plus or minus may not be followed by a space.
5924
5925 @item
5926 A vertical bar must be surrounded by spaces.
5927 @end itemize
5928
5929 @item ^u^UNNECESSARY_BLANK_LINES^
5930 @emph{Check unnecessary blank lines.}
5931 Check for unnecessary blank lines. A blank line is considered
5932 unnecessary if it appears at the end of the file, or if more than
5933 one blank line occurs in sequence.
5934
5935 @item ^x^XTRA_PARENS^
5936 @emph{Check extra parentheses.}
5937 Check for the use of an unnecessary extra level of parentheses (C-style)
5938 around conditions in @code{if} statements, @code{while} statements and
5939 @code{exit} statements.
5940
5941 @end table
5942
5943 @noindent
5944 In the above rules, appearing in column one is always permitted, that is,
5945 counts as meeting either a requirement for a required preceding space,
5946 or as meeting a requirement for no preceding space.
5947
5948 Appearing at the end of a line is also always permitted, that is, counts
5949 as meeting either a requirement for a following space, or as meeting
5950 a requirement for no following space.
5951
5952 @noindent
5953 If any of these style rules is violated, a message is generated giving
5954 details on the violation. The initial characters of such messages are
5955 always ``@code{(style)}''. Note that these messages are treated as warning
5956 messages, so they normally do not prevent the generation of an object
5957 file. The @option{-gnatwe} switch can be used to treat warning messages,
5958 including style messages, as fatal errors.
5959
5960 The switch
5961 @ifclear vms
5962 @option{-gnaty} on its own (that is not
5963 followed by any letters or digits),
5964 is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
5965 options enabled with the exception of @option{-gnatyo},
5966 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
5967 @end ifclear
5968 @ifset vms
5969 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5970 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
5971 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
5972 @end ifset
5973 an indentation level of 3 is set. This is similar to the standard
5974 checking option that is used for the GNAT sources.
5975
5976 The switch
5977 @ifclear vms
5978 @option{-gnatyN}
5979 @end ifclear
5980 @ifset vms
5981 /STYLE_CHECKS=NONE
5982 @end ifset
5983 clears any previously set style checks.
5984
5985 @node Run-Time Checks
5986 @subsection Run-Time Checks
5987 @cindex Division by zero
5988 @cindex Access before elaboration
5989 @cindex Checks, division by zero
5990 @cindex Checks, access before elaboration
5991 @cindex Checks, stack overflow checking
5992
5993 @noindent
5994 If you compile with the default options, GNAT will insert many run-time
5995 checks into the compiled code, including code that performs range
5996 checking against constraints, but not arithmetic overflow checking for
5997 integer operations (including division by zero), checks for access
5998 before elaboration on subprogram calls, or stack overflow checking. All
5999 other run-time checks, as required by the Ada Reference Manual, are
6000 generated by default. The following @command{gcc} switches refine this
6001 default behavior:
6002
6003 @table @option
6004 @c !sort!
6005 @item -gnatp
6006 @cindex @option{-gnatp} (@command{gcc})
6007 @cindex Suppressing checks
6008 @cindex Checks, suppressing
6009 @findex Suppress
6010 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
6011 had been present in the source. Validity checks are also suppressed (in
6012 other words @option{-gnatp} also implies @option{-gnatVn}.
6013 Use this switch to improve the performance
6014 of the code at the expense of safety in the presence of invalid data or
6015 program bugs.
6016
6017 @item -gnato
6018 @cindex @option{-gnato} (@command{gcc})
6019 @cindex Overflow checks
6020 @cindex Check, overflow
6021 Enables overflow checking for integer operations.
6022 This causes GNAT to generate slower and larger executable
6023 programs by adding code to check for overflow (resulting in raising
6024 @code{Constraint_Error} as required by standard Ada
6025 semantics). These overflow checks correspond to situations in which
6026 the true value of the result of an operation may be outside the base
6027 range of the result type. The following example shows the distinction:
6028
6029 @smallexample @c ada
6030 X1 : Integer := Integer'Last;
6031 X2 : Integer range 1 .. 5 := 5;
6032 X3 : Integer := Integer'Last;
6033 X4 : Integer range 1 .. 5 := 5;
6034 F  : Float := 2.0E+20;
6035 ...
6036 X1 := X1 + 1;
6037 X2 := X2 + 1;
6038 X3 := Integer (F);
6039 X4 := Integer (F);
6040 @end smallexample
6041
6042 @noindent
6043 Here the first addition results in a value that is outside the base range
6044 of Integer, and hence requires an overflow check for detection of the
6045 constraint error. Thus the first assignment to @code{X1} raises a
6046 @code{Constraint_Error} exception only if @option{-gnato} is set.
6047
6048 The second increment operation results in a violation
6049 of the explicit range constraint, and such range checks are always
6050 performed (unless specifically suppressed with a pragma @code{suppress}
6051 or the use of @option{-gnatp}).
6052
6053 The two conversions of @code{F} both result in values that are outside
6054 the base range of type @code{Integer} and thus will raise
6055 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6056 The fact that the result of the second conversion is assigned to
6057 variable @code{X4} with a restricted range is irrelevant, since the problem
6058 is in the conversion, not the assignment.
6059
6060 Basically the rule is that in the default mode (@option{-gnato} not
6061 used), the generated code assures that all integer variables stay
6062 within their declared ranges, or within the base range if there is
6063 no declared range. This prevents any serious problems like indexes
6064 out of range for array operations.
6065
6066 What is not checked in default mode is an overflow that results in
6067 an in-range, but incorrect value. In the above example, the assignments
6068 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6069 range of the target variable, but the result is wrong in the sense that
6070 it is too large to be represented correctly. Typically the assignment
6071 to @code{X1} will result in wrap around to the largest negative number.
6072 The conversions of @code{F} will result in some @code{Integer} value
6073 and if that integer value is out of the @code{X4} range then the
6074 subsequent assignment would generate an exception.
6075
6076 @findex Machine_Overflows
6077 Note that the @option{-gnato} switch does not affect the code generated
6078 for any floating-point operations; it applies only to integer
6079 semantics).
6080 For floating-point, GNAT has the @code{Machine_Overflows}
6081 attribute set to @code{False} and the normal mode of operation is to
6082 generate IEEE NaN and infinite values on overflow or invalid operations
6083 (such as dividing 0.0 by 0.0).
6084
6085 The reason that we distinguish overflow checking from other kinds of
6086 range constraint checking is that a failure of an overflow check can
6087 generate an incorrect value, but cannot cause erroneous behavior. This
6088 is unlike the situation with a constraint check on an array subscript,
6089 where failure to perform the check can result in random memory description,
6090 or the range check on a case statement, where failure to perform the check
6091 can cause a wild jump.
6092
6093 Note again that @option{-gnato} is off by default, so overflow checking is
6094 not performed in default mode. This means that out of the box, with the
6095 default settings, GNAT does not do all the checks expected from the
6096 language description in the Ada Reference Manual. If you want all constraint
6097 checks to be performed, as described in this Manual, then you must
6098 explicitly use the -gnato switch either on the @command{gnatmake} or
6099 @command{gcc} command.
6100
6101 @item -gnatE
6102 @cindex @option{-gnatE} (@command{gcc})
6103 @cindex Elaboration checks
6104 @cindex Check, elaboration
6105 Enables dynamic checks for access-before-elaboration
6106 on subprogram calls and generic instantiations.
6107 For full details of the effect and use of this switch,
6108 @xref{Compiling Using gcc}.
6109
6110 @item -fstack-check
6111 @cindex @option{-fstack-check} (@command{gcc})
6112 @cindex Stack Overflow Checking
6113 @cindex Checks, stack overflow checking
6114 Activates stack overflow checking. For full details of the effect and use of
6115 this switch see @ref{Stack Overflow Checking}.
6116 @end table
6117
6118 @findex Unsuppress
6119 @noindent
6120 The setting of these switches only controls the default setting of the
6121 checks. You may modify them using either @code{Suppress} (to remove
6122 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6123 the program source.
6124
6125 @node Using gcc for Syntax Checking
6126 @subsection Using @command{gcc} for Syntax Checking
6127 @table @option
6128 @item -gnats
6129 @cindex @option{-gnats} (@command{gcc})
6130 @ifclear vms
6131
6132 @noindent
6133 The @code{s} stands for ``syntax''.
6134 @end ifclear
6135
6136 Run GNAT in syntax checking only mode. For
6137 example, the command
6138
6139 @smallexample
6140 $ gcc -c -gnats x.adb
6141 @end smallexample
6142
6143 @noindent
6144 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6145 series of files in a single command
6146 @ifclear vms
6147 , and can use wild cards to specify such a group of files.
6148 Note that you must specify the @option{-c} (compile
6149 only) flag in addition to the @option{-gnats} flag.
6150 @end ifclear
6151 .
6152 You may use other switches in conjunction with @option{-gnats}. In
6153 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6154 format of any generated error messages.
6155
6156 When the source file is empty or contains only empty lines and/or comments,
6157 the output is a warning:
6158
6159 @smallexample
6160 $ gcc -c -gnats -x ada toto.txt
6161 toto.txt:1:01: warning: empty file, contains no compilation units
6162 $
6163 @end smallexample
6164
6165 Otherwise, the output is simply the error messages, if any. No object file or
6166 ALI file is generated by a syntax-only compilation. Also, no units other
6167 than the one specified are accessed. For example, if a unit @code{X}
6168 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6169 check only mode does not access the source file containing unit
6170 @code{Y}.
6171
6172 @cindex Multiple units, syntax checking
6173 Normally, GNAT allows only a single unit in a source file. However, this
6174 restriction does not apply in syntax-check-only mode, and it is possible
6175 to check a file containing multiple compilation units concatenated
6176 together. This is primarily used by the @code{gnatchop} utility
6177 (@pxref{Renaming Files Using gnatchop}).
6178 @end table
6179
6180 @node Using gcc for Semantic Checking
6181 @subsection Using @command{gcc} for Semantic Checking
6182 @table @option
6183 @item -gnatc
6184 @cindex @option{-gnatc} (@command{gcc})
6185
6186 @ifclear vms
6187 @noindent
6188 The @code{c} stands for ``check''.
6189 @end ifclear
6190 Causes the compiler to operate in semantic check mode,
6191 with full checking for all illegalities specified in the
6192 Ada Reference Manual, but without generation of any object code
6193 (no object file is generated).
6194
6195 Because dependent files must be accessed, you must follow the GNAT
6196 semantic restrictions on file structuring to operate in this mode:
6197
6198 @itemize @bullet
6199 @item
6200 The needed source files must be accessible
6201 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6202
6203 @item
6204 Each file must contain only one compilation unit.
6205
6206 @item
6207 The file name and unit name must match (@pxref{File Naming Rules}).
6208 @end itemize
6209
6210 The output consists of error messages as appropriate. No object file is
6211 generated. An @file{ALI} file is generated for use in the context of
6212 cross-reference tools, but this file is marked as not being suitable
6213 for binding (since no object file is generated).
6214 The checking corresponds exactly to the notion of
6215 legality in the Ada Reference Manual.
6216
6217 Any unit can be compiled in semantics-checking-only mode, including
6218 units that would not normally be compiled (subunits,
6219 and specifications where a separate body is present).
6220 @end table
6221
6222 @node Compiling Different Versions of Ada
6223 @subsection Compiling Different Versions of Ada
6224
6225 @noindent
6226 The switches described in this section allow you to explicitly specify
6227 the version of the Ada language that your programs are written in.
6228 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6229 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6230 indicate Ada 83 compatibility mode.
6231
6232 @table @option
6233 @cindex Compatibility with Ada 83
6234
6235 @item -gnat83 (Ada 83 Compatibility Mode)
6236 @cindex @option{-gnat83} (@command{gcc})
6237 @cindex ACVC, Ada 83 tests
6238 @cindex Ada 83 mode
6239
6240 @noindent
6241 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6242 specifies that the program is to be compiled in Ada 83 mode. With
6243 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6244 semantics where this can be done easily.
6245 It is not possible to guarantee this switch does a perfect
6246 job; some subtle tests, such as are
6247 found in earlier ACVC tests (and that have been removed from the ACATS suite
6248 for Ada 95), might not compile correctly.
6249 Nevertheless, this switch may be useful in some circumstances, for example
6250 where, due to contractual reasons, existing code needs to be maintained
6251 using only Ada 83 features.
6252
6253 With few exceptions (most notably the need to use @code{<>} on
6254 @cindex Generic formal parameters
6255 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6256 reserved words, and the use of packages
6257 with optional bodies), it is not necessary to specify the
6258 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6259 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6260 a correct Ada 83 program is usually also a correct program
6261 in these later versions of the language standard.
6262 For further information, please refer to @ref{Compatibility and Porting Guide}.
6263
6264 @item -gnat95 (Ada 95 mode)
6265 @cindex @option{-gnat95} (@command{gcc})
6266 @cindex Ada 95 mode
6267
6268 @noindent
6269 This switch directs the compiler to implement the Ada 95 version of the
6270 language.
6271 Since Ada 95 is almost completely upwards
6272 compatible with Ada 83, Ada 83 programs may generally be compiled using
6273 this switch (see the description of the @option{-gnat83} switch for further
6274 information about Ada 83 mode).
6275 If an Ada 2005 program is compiled in Ada 95 mode,
6276 uses of the new Ada 2005 features will cause error
6277 messages or warnings.
6278
6279 This switch also can be used to cancel the effect of a previous
6280 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6281
6282 @item -gnat05 (Ada 2005 mode)
6283 @cindex @option{-gnat05} (@command{gcc})
6284 @cindex Ada 2005 mode
6285
6286 @noindent
6287 This switch directs the compiler to implement the Ada 2005 version of the
6288 language.
6289 Since Ada 2005 is almost completely upwards
6290 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6291 may generally be compiled using this switch (see the description of the
6292 @option{-gnat83} and @option{-gnat95} switches for further
6293 information).
6294
6295 For information about the approved ``Ada Issues'' that have been incorporated
6296 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6297 Included with GNAT releases is a file @file{features-ada0y} that describes
6298 the set of implemented Ada 2005 features.
6299 @end table
6300
6301
6302 @node Character Set Control
6303 @subsection Character Set Control
6304 @table @option
6305 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6306 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6307
6308 @noindent
6309 Normally GNAT recognizes the Latin-1 character set in source program
6310 identifiers, as described in the Ada Reference Manual.
6311 This switch causes
6312 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6313 single character ^^or word^ indicating the character set, as follows:
6314
6315 @table @code
6316 @item 1
6317 ISO 8859-1 (Latin-1) identifiers
6318
6319 @item 2
6320 ISO 8859-2 (Latin-2) letters allowed in identifiers
6321
6322 @item 3
6323 ISO 8859-3 (Latin-3) letters allowed in identifiers
6324
6325 @item 4
6326 ISO 8859-4 (Latin-4) letters allowed in identifiers
6327
6328 @item 5
6329 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6330
6331 @item 9
6332 ISO 8859-15 (Latin-9) letters allowed in identifiers
6333
6334 @item ^p^PC^
6335 IBM PC letters (code page 437) allowed in identifiers
6336
6337 @item ^8^PC850^
6338 IBM PC letters (code page 850) allowed in identifiers
6339
6340 @item ^f^FULL_UPPER^
6341 Full upper-half codes allowed in identifiers
6342
6343 @item ^n^NO_UPPER^
6344 No upper-half codes allowed in identifiers
6345
6346 @item ^w^WIDE^
6347 Wide-character codes (that is, codes greater than 255)
6348 allowed in identifiers
6349 @end table
6350
6351 @xref{Foreign Language Representation}, for full details on the
6352 implementation of these character sets.
6353
6354 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6355 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6356 Specify the method of encoding for wide characters.
6357 @var{e} is one of the following:
6358
6359 @table @code
6360
6361 @item ^h^HEX^
6362 Hex encoding (brackets coding also recognized)
6363
6364 @item ^u^UPPER^
6365 Upper half encoding (brackets encoding also recognized)
6366
6367 @item ^s^SHIFT_JIS^
6368 Shift/JIS encoding (brackets encoding also recognized)
6369
6370 @item ^e^EUC^
6371 EUC encoding (brackets encoding also recognized)
6372
6373 @item ^8^UTF8^
6374 UTF-8 encoding (brackets encoding also recognized)
6375
6376 @item ^b^BRACKETS^
6377 Brackets encoding only (default value)
6378 @end table
6379 For full details on these encoding
6380 methods see @ref{Wide Character Encodings}.
6381 Note that brackets coding is always accepted, even if one of the other
6382 options is specified, so for example @option{-gnatW8} specifies that both
6383 brackets and @code{UTF-8} encodings will be recognized. The units that are
6384 with'ed directly or indirectly will be scanned using the specified
6385 representation scheme, and so if one of the non-brackets scheme is
6386 used, it must be used consistently throughout the program. However,
6387 since brackets encoding is always recognized, it may be conveniently
6388 used in standard libraries, allowing these libraries to be used with
6389 any of the available coding schemes.
6390 scheme. If no @option{-gnatW?} parameter is present, then the default
6391 representation is Brackets encoding only.
6392
6393 Note that the wide character representation that is specified (explicitly
6394 or by default) for the main program also acts as the default encoding used
6395 for Wide_Text_IO files if not specifically overridden by a WCEM form
6396 parameter.
6397
6398 @end table
6399 @node File Naming Control
6400 @subsection File Naming Control
6401
6402 @table @option
6403 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6404 @cindex @option{-gnatk} (@command{gcc})
6405 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6406 1-999, indicates the maximum allowable length of a file name (not
6407 including the @file{.ads} or @file{.adb} extension). The default is not
6408 to enable file name krunching.
6409
6410 For the source file naming rules, @xref{File Naming Rules}.
6411 @end table
6412
6413 @node Subprogram Inlining Control
6414 @subsection Subprogram Inlining Control
6415
6416 @table @option
6417 @c !sort!
6418 @item -gnatn
6419 @cindex @option{-gnatn} (@command{gcc})
6420 @ifclear vms
6421 The @code{n} here is intended to suggest the first syllable of the
6422 word ``inline''.
6423 @end ifclear
6424 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6425 inlining to actually occur, optimization must be enabled. To enable
6426 inlining of subprograms specified by pragma @code{Inline},
6427 you must also specify this switch.
6428 In the absence of this switch, GNAT does not attempt
6429 inlining and does not need to access the bodies of
6430 subprograms for which @code{pragma Inline} is specified if they are not
6431 in the current unit.
6432
6433 If you specify this switch the compiler will access these bodies,
6434 creating an extra source dependency for the resulting object file, and
6435 where possible, the call will be inlined.
6436 For further details on when inlining is possible
6437 see @ref{Inlining of Subprograms}.
6438
6439 @item -gnatN
6440 @cindex @option{-gnatN} (@command{gcc})
6441 The front end inlining activated by this switch is generally more extensive,
6442 and quite often more effective than the standard @option{-gnatn} inlining mode.
6443 It will also generate additional dependencies.
6444 Note that
6445 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6446 to specify both options.
6447 @end table
6448
6449 @node Auxiliary Output Control
6450 @subsection Auxiliary Output Control
6451
6452 @table @option
6453 @item -gnatt
6454 @cindex @option{-gnatt} (@command{gcc})
6455 @cindex Writing internal trees
6456 @cindex Internal trees, writing to file
6457 Causes GNAT to write the internal tree for a unit to a file (with the
6458 extension @file{.adt}.
6459 This not normally required, but is used by separate analysis tools.
6460 Typically
6461 these tools do the necessary compilations automatically, so you should
6462 not have to specify this switch in normal operation.
6463
6464 @item -gnatu
6465 @cindex @option{-gnatu} (@command{gcc})
6466 Print a list of units required by this compilation on @file{stdout}.
6467 The listing includes all units on which the unit being compiled depends
6468 either directly or indirectly.
6469
6470 @ifclear vms
6471 @item -pass-exit-codes
6472 @cindex @option{-pass-exit-codes} (@command{gcc})
6473 If this switch is not used, the exit code returned by @command{gcc} when
6474 compiling multiple files indicates whether all source files have
6475 been successfully used to generate object files or not.
6476
6477 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6478 exit status and allows an integrated development environment to better
6479 react to a compilation failure. Those exit status are:
6480
6481 @table @asis
6482 @item 5
6483 There was an error in at least one source file.
6484 @item 3
6485 At least one source file did not generate an object file.
6486 @item 2
6487 The compiler died unexpectedly (internal error for example).
6488 @item 0
6489 An object file has been generated for every source file.
6490 @end table
6491 @end ifclear
6492 @end table
6493
6494 @node Debugging Control
6495 @subsection Debugging Control
6496
6497 @table @option
6498 @c !sort!
6499 @cindex Debugging options
6500 @ifclear vms
6501 @item -gnatd@var{x}
6502 @cindex @option{-gnatd} (@command{gcc})
6503 Activate internal debugging switches. @var{x} is a letter or digit, or
6504 string of letters or digits, which specifies the type of debugging
6505 outputs desired. Normally these are used only for internal development
6506 or system debugging purposes. You can find full documentation for these
6507 switches in the body of the @code{Debug} unit in the compiler source
6508 file @file{debug.adb}.
6509 @end ifclear
6510
6511 @item -gnatG
6512 @cindex @option{-gnatG} (@command{gcc})
6513 This switch causes the compiler to generate auxiliary output containing
6514 a pseudo-source listing of the generated expanded code. Like most Ada
6515 compilers, GNAT works by first transforming the high level Ada code into
6516 lower level constructs. For example, tasking operations are transformed
6517 into calls to the tasking run-time routines. A unique capability of GNAT
6518 is to list this expanded code in a form very close to normal Ada source.
6519 This is very useful in understanding the implications of various Ada
6520 usage on the efficiency of the generated code. There are many cases in
6521 Ada (e.g. the use of controlled types), where simple Ada statements can
6522 generate a lot of run-time code. By using @option{-gnatG} you can identify
6523 these cases, and consider whether it may be desirable to modify the coding
6524 approach to improve efficiency.
6525
6526 The format of the output is very similar to standard Ada source, and is
6527 easily understood by an Ada programmer. The following special syntactic
6528 additions correspond to low level features used in the generated code that
6529 do not have any exact analogies in pure Ada source form. The following
6530 is a partial list of these special constructions. See the specification
6531 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6532
6533 If the switch @option{-gnatL} is used in conjunction with
6534 @cindex @option{-gnatL} (@command{gcc})
6535 @option{-gnatG}, then the original source lines are interspersed
6536 in the expanded source (as comment lines with the original line number).
6537
6538 @table @code
6539 @item new @var{xxx} [storage_pool = @var{yyy}]
6540 Shows the storage pool being used for an allocator.
6541
6542 @item at end @var{procedure-name};
6543 Shows the finalization (cleanup) procedure for a scope.
6544
6545 @item (if @var{expr} then @var{expr} else @var{expr})
6546 Conditional expression equivalent to the @code{x?y:z} construction in C.
6547
6548 @item @var{target}^^^(@var{source})
6549 A conversion with floating-point truncation instead of rounding.
6550
6551 @item @var{target}?(@var{source})
6552 A conversion that bypasses normal Ada semantic checking. In particular
6553 enumeration types and fixed-point types are treated simply as integers.
6554
6555 @item @var{target}?^^^(@var{source})
6556 Combines the above two cases.
6557
6558 @item @var{x} #/ @var{y}
6559 @itemx @var{x} #mod @var{y}
6560 @itemx @var{x} #* @var{y}
6561 @itemx @var{x} #rem @var{y}
6562 A division or multiplication of fixed-point values which are treated as
6563 integers without any kind of scaling.
6564
6565 @item free @var{expr} [storage_pool = @var{xxx}]
6566 Shows the storage pool associated with a @code{free} statement.
6567
6568 @item [subtype or type declaration]
6569 Used to list an equivalent declaration for an internally generated
6570 type that is referenced elsewhere in the listing.
6571
6572 @item freeze @var{type-name} [@var{actions}]
6573 Shows the point at which @var{type-name} is frozen, with possible
6574 associated actions to be performed at the freeze point.
6575
6576 @item reference @var{itype}
6577 Reference (and hence definition) to internal type @var{itype}.
6578
6579 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6580 Intrinsic function call.
6581
6582 @item @var{label-name} : label
6583 Declaration of label @var{labelname}.
6584
6585 @item #$ @var{subprogram-name}
6586 An implicit call to a run-time support routine
6587 (to meet the requirement of H.3.1(9) in a
6588 convenient manner).
6589
6590 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6591 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6592 @var{expr}, but handled more efficiently).
6593
6594 @item [constraint_error]
6595 Raise the @code{Constraint_Error} exception.
6596
6597 @item @var{expression}'reference
6598 A pointer to the result of evaluating @var{expression}.
6599
6600 @item @var{target-type}!(@var{source-expression})
6601 An unchecked conversion of @var{source-expression} to @var{target-type}.
6602
6603 @item [@var{numerator}/@var{denominator}]
6604 Used to represent internal real literals (that) have no exact
6605 representation in base 2-16 (for example, the result of compile time
6606 evaluation of the expression 1.0/27.0).
6607 @end table
6608
6609 @item -gnatD
6610 @cindex @option{-gnatD} (@command{gcc})
6611 When used in conjunction with @option{-gnatG}, this switch causes
6612 the expanded source, as described above for
6613 @option{-gnatG} to be written to files with names
6614 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6615 instead of to the standard output file. For
6616 example, if the source file name is @file{hello.adb}, then a file
6617 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6618 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6619 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6620 you to do source level debugging using the generated code which is
6621 sometimes useful for complex code, for example to find out exactly
6622 which part of a complex construction raised an exception. This switch
6623 also suppress generation of cross-reference information (see
6624 @option{-gnatx}) since otherwise the cross-reference information
6625 would refer to the @file{^.dg^.DG^} file, which would cause
6626 confusion since this is not the original source file.
6627
6628 Note that @option{-gnatD} actually implies @option{-gnatG}
6629 automatically, so it is not necessary to give both options.
6630 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6631
6632 If the switch @option{-gnatL} is used in conjunction with
6633 @cindex @option{-gnatL} (@command{gcc})
6634 @option{-gnatDG}, then the original source lines are interspersed
6635 in the expanded source (as comment lines with the original line number).
6636
6637 @ifclear vms
6638 @item -gnatR[0|1|2|3[s]]
6639 @cindex @option{-gnatR} (@command{gcc})
6640 This switch controls output from the compiler of a listing showing
6641 representation information for declared types and objects. For
6642 @option{-gnatR0}, no information is output (equivalent to omitting
6643 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6644 so @option{-gnatR} with no parameter has the same effect), size and alignment
6645 information is listed for declared array and record types. For
6646 @option{-gnatR2}, size and alignment information is listed for all
6647 expressions for values that are computed at run time for
6648 variant records. These symbolic expressions have a mostly obvious
6649 format with #n being used to represent the value of the n'th
6650 discriminant. See source files @file{repinfo.ads/adb} in the
6651 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6652 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6653 the output is to a file with the name @file{^file.rep^file_REP^} where
6654 file is the name of the corresponding source file.
6655 @end ifclear
6656 @ifset vms
6657 @item /REPRESENTATION_INFO
6658 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6659 This qualifier controls output from the compiler of a listing showing
6660 representation information for declared types and objects. For
6661 @option{/REPRESENTATION_INFO=NONE}, no information is output
6662 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6663 @option{/REPRESENTATION_INFO} without option is equivalent to
6664 @option{/REPRESENTATION_INFO=ARRAYS}.
6665 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6666 information is listed for declared array and record types. For
6667 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6668 is listed for all expression information for values that are computed
6669 at run time for variant records. These symbolic expressions have a mostly
6670 obvious format with #n being used to represent the value of the n'th
6671 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6672 @code{GNAT} sources for full details on the format of
6673 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6674 If _FILE is added at the end of an option
6675 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6676 then the output is to a file with the name @file{file_REP} where
6677 file is the name of the corresponding source file.
6678 @end ifset
6679 Note that it is possible for record components to have zero size. In
6680 this case, the component clause uses an obvious extension of permitted
6681 Ada syntax, for example @code{at 0 range 0 .. -1}.
6682
6683 Representation information requires that code be generated (since it is the
6684 code generator that lays out complex data structures). If an attempt is made
6685 to output representation information when no code is generated, for example
6686 when a subunit is compiled on its own, then no information can be generated
6687 and the compiler outputs a message to this effect.
6688
6689 @item -gnatS
6690 @cindex @option{-gnatS} (@command{gcc})
6691 The use of the switch @option{-gnatS} for an
6692 Ada compilation will cause the compiler to output a
6693 representation of package Standard in a form very
6694 close to standard Ada. It is not quite possible to
6695 do this entirely in standard Ada (since new
6696 numeric base types cannot be created in standard
6697 Ada), but the output is easily
6698 readable to any Ada programmer, and is useful to
6699 determine the characteristics of target dependent
6700 types in package Standard.
6701
6702 @item -gnatx
6703 @cindex @option{-gnatx} (@command{gcc})
6704 Normally the compiler generates full cross-referencing information in
6705 the @file{ALI} file. This information is used by a number of tools,
6706 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6707 suppresses this information. This saves some space and may slightly
6708 speed up compilation, but means that these tools cannot be used.
6709 @end table
6710
6711 @node Exception Handling Control
6712 @subsection Exception Handling Control
6713
6714 @noindent
6715 GNAT uses two methods for handling exceptions at run-time. The
6716 @code{setjmp/longjmp} method saves the context when entering
6717 a frame with an exception handler. Then when an exception is
6718 raised, the context can be restored immediately, without the
6719 need for tracing stack frames. This method provides very fast
6720 exception propagation, but introduces significant overhead for
6721 the use of exception handlers, even if no exception is raised.
6722
6723 The other approach is called ``zero cost'' exception handling.
6724 With this method, the compiler builds static tables to describe
6725 the exception ranges. No dynamic code is required when entering
6726 a frame containing an exception handler. When an exception is
6727 raised, the tables are used to control a back trace of the
6728 subprogram invocation stack to locate the required exception
6729 handler. This method has considerably poorer performance for
6730 the propagation of exceptions, but there is no overhead for
6731 exception handlers if no exception is raised. Note that in this
6732 mode and in the context of mixed Ada and C/C++ programming,
6733 to propagate an exception through a C/C++ code, the C/C++ code
6734 must be compiled with the @option{-funwind-tables} GCC's
6735 option.
6736
6737 The following switches may be used to control which of the
6738 two exception handling methods is used.
6739
6740 @table @option
6741 @c !sort!
6742
6743 @item --RTS=sjlj
6744 @cindex @option{--RTS=sjlj} (@command{gnatmake})
6745 This switch causes the setjmp/longjmp run-time (when available) to be used
6746 for exception handling. If the default
6747 mechanism for the target is zero cost exceptions, then
6748 this switch can be used to modify this default, and must be
6749 used for all units in the partition.
6750 This option is rarely used. One case in which it may be
6751 advantageous is if you have an application where exception
6752 raising is common and the overall performance of the
6753 application is improved by favoring exception propagation.
6754
6755 @item --RTS=zcx
6756 @cindex @option{--RTS=zcx} (@command{gnatmake})
6757 @cindex Zero Cost Exceptions
6758 This switch causes the zero cost approach to be used
6759 for exception handling. If this is the default mechanism for the
6760 target (see below), then this switch is unneeded. If the default
6761 mechanism for the target is setjmp/longjmp exceptions, then
6762 this switch can be used to modify this default, and must be
6763 used for all units in the partition.
6764 This option can only be used if the zero cost approach
6765 is available for the target in use, otherwise it will generate an error.
6766 @end table
6767
6768 @noindent
6769 The same option @option{--RTS} must be used both for @command{gcc}
6770 and @command{gnatbind}. Passing this option to @command{gnatmake}
6771 (@pxref{Switches for gnatmake}) will ensure the required consistency
6772 through the compilation and binding steps.
6773
6774 @node Units to Sources Mapping Files
6775 @subsection Units to Sources Mapping Files
6776
6777 @table @option
6778
6779 @item -gnatem^^=^@var{path}
6780 @cindex @option{-gnatem} (@command{gcc})
6781 A mapping file is a way to communicate to the compiler two mappings:
6782 from unit names to file names (without any directory information) and from
6783 file names to path names (with full directory information). These mappings
6784 are used by the compiler to short-circuit the path search.
6785
6786 The use of mapping files is not required for correct operation of the
6787 compiler, but mapping files can improve efficiency, particularly when
6788 sources are read over a slow network connection. In normal operation,
6789 you need not be concerned with the format or use of mapping files,
6790 and the @option{-gnatem} switch is not a switch that you would use
6791 explicitly. it is intended only for use by automatic tools such as
6792 @command{gnatmake} running under the project file facility. The
6793 description here of the format of mapping files is provided
6794 for completeness and for possible use by other tools.
6795
6796 A mapping file is a sequence of sets of three lines. In each set,
6797 the first line is the unit name, in lower case, with ``@code{%s}''
6798 appended for
6799 specifications and ``@code{%b}'' appended for bodies; the second line is the
6800 file name; and the third line is the path name.
6801
6802 Example:
6803 @smallexample
6804    main%b
6805    main.2.ada
6806    /gnat/project1/sources/main.2.ada
6807 @end smallexample
6808
6809 When the switch @option{-gnatem} is specified, the compiler will create
6810 in memory the two mappings from the specified file. If there is any problem
6811 (non existent file, truncated file or duplicate entries), no mapping
6812 will be created.
6813
6814 Several @option{-gnatem} switches may be specified; however, only the last
6815 one on the command line will be taken into account.
6816
6817 When using a project file, @command{gnatmake} create a temporary mapping file
6818 and communicates it to the compiler using this switch.
6819
6820 @end table
6821
6822 @node Integrated Preprocessing
6823 @subsection Integrated Preprocessing
6824
6825 @noindent
6826 GNAT sources may be preprocessed immediately before compilation; the actual
6827 text of the source is not the text of the source file, but is derived from it
6828 through a process called preprocessing. Integrated preprocessing is specified
6829 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6830 indicates, through a text file, the preprocessing data to be used.
6831 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6832
6833 @noindent
6834 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6835 used when Integrated Preprocessing is used. The reason is that preprocessing
6836 with another Preprocessing Data file without changing the sources will
6837 not trigger recompilation without this switch.
6838
6839 @noindent
6840 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6841 always trigger recompilation for sources that are preprocessed,
6842 because @command{gnatmake} cannot compute the checksum of the source after
6843 preprocessing.
6844
6845 @noindent
6846 The actual preprocessing function is described in details in section
6847 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6848 preprocessing is triggered and parameterized.
6849
6850 @table @code
6851
6852 @item -gnatep=@var{file}
6853 @cindex @option{-gnatep} (@command{gcc})
6854 This switch indicates to the compiler the file name (without directory
6855 information) of the preprocessor data file to use. The preprocessor data file
6856 should be found in the source directories.
6857
6858 @noindent
6859 A preprocessing data file is a text file with significant lines indicating
6860 how should be preprocessed either a specific source or all sources not
6861 mentioned in other lines. A significant line is a non empty, non comment line.
6862 Comments are similar to Ada comments.
6863
6864 @noindent
6865 Each significant line starts with either a literal string or the character '*'.
6866 A literal string is the file name (without directory information) of the source
6867 to preprocess. A character '*' indicates the preprocessing for all the sources
6868 that are not specified explicitly on other lines (order of the lines is not
6869 significant). It is an error to have two lines with the same file name or two
6870 lines starting with the character '*'.
6871
6872 @noindent
6873 After the file name or the character '*', another optional literal string
6874 indicating the file name of the definition file to be used for preprocessing
6875 (@pxref{Form of Definitions File}). The definition files are found by the
6876 compiler in one of the source directories. In some cases, when compiling
6877 a source in a directory other than the current directory, if the definition
6878 file is in the current directory, it may be necessary to add the current
6879 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6880 the compiler would not find the definition file.
6881
6882 @noindent
6883 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6884 be found. Those ^switches^switches^ are:
6885
6886 @table @code
6887
6888 @item -b
6889 Causes both preprocessor lines and the lines deleted by
6890 preprocessing to be replaced by blank lines, preserving the line number.
6891 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6892 it cancels the effect of @option{-c}.
6893
6894 @item -c
6895 Causes both preprocessor lines and the lines deleted
6896 by preprocessing to be retained as comments marked
6897 with the special string ``@code{--! }''.
6898
6899 @item -Dsymbol=value
6900 Define or redefine a symbol, associated with value. A symbol is an Ada
6901 identifier, or an Ada reserved word, with the exception of @code{if},
6902 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6903 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6904 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6905 same name defined in a definition file.
6906
6907 @item -s
6908 Causes a sorted list of symbol names and values to be
6909 listed on the standard output file.
6910
6911 @item -u
6912 Causes undefined symbols to be treated as having the value @code{FALSE}
6913 in the context
6914 of a preprocessor test. In the absence of this option, an undefined symbol in
6915 a @code{#if} or @code{#elsif} test will be treated as an error.
6916
6917 @end table
6918
6919 @noindent
6920 Examples of valid lines in a preprocessor data file:
6921
6922 @smallexample
6923   "toto.adb"  "prep.def" -u
6924   --  preprocess "toto.adb", using definition file "prep.def",
6925   --  undefined symbol are False.
6926
6927   * -c -DVERSION=V101
6928   --  preprocess all other sources without a definition file;
6929   --  suppressed lined are commented; symbol VERSION has the value V101.
6930
6931   "titi.adb" "prep2.def" -s
6932   --  preprocess "titi.adb", using definition file "prep2.def";
6933   --  list all symbols with their values.
6934 @end smallexample
6935
6936 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6937 @cindex @option{-gnateD} (@command{gcc})
6938 Define or redefine a preprocessing symbol, associated with value. If no value
6939 is given on the command line, then the value of the symbol is @code{True}.
6940 A symbol is an identifier, following normal Ada (case-insensitive)
6941 rules for its syntax, and value is any sequence (including an empty sequence)
6942 of characters from the set (letters, digits, period, underline).
6943 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6944 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6945
6946 @noindent
6947 A symbol declared with this ^switch^switch^ on the command line replaces a
6948 symbol with the same name either in a definition file or specified with a
6949 ^switch^switch^ -D in the preprocessor data file.
6950
6951 @noindent
6952 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6953
6954 @end table
6955
6956 @node Code Generation Control
6957 @subsection Code Generation Control
6958
6959 @noindent
6960
6961 The GCC technology provides a wide range of target dependent
6962 @option{-m} switches for controlling
6963 details of code generation with respect to different versions of
6964 architectures. This includes variations in instruction sets (e.g.
6965 different members of the power pc family), and different requirements
6966 for optimal arrangement of instructions (e.g. different members of
6967 the x86 family). The list of available @option{-m} switches may be
6968 found in the GCC documentation.
6969
6970 Use of these @option{-m} switches may in some cases result in improved
6971 code performance.
6972
6973 The GNAT Pro technology is tested and qualified without any
6974 @option{-m} switches,
6975 so generally the most reliable approach is to avoid the use of these
6976 switches. However, we generally expect most of these switches to work
6977 successfully with GNAT Pro, and many customers have reported successful
6978 use of these options.
6979
6980 Our general advice is to avoid the use of @option{-m} switches unless
6981 special needs lead to requirements in this area. In particular,
6982 there is no point in using @option{-m} switches to improve performance
6983 unless you actually see a performance improvement.
6984
6985 @ifset vms
6986 @node Return Codes
6987 @subsection Return Codes
6988 @cindex Return Codes
6989 @cindex @option{/RETURN_CODES=VMS}
6990
6991 @noindent
6992 On VMS, GNAT compiled programs return POSIX-style codes by default,
6993 e.g. @option{/RETURN_CODES=POSIX}.
6994
6995 To enable VMS style return codes, use GNAT BIND and LINK with the option
6996 @option{/RETURN_CODES=VMS}. For example:
6997
6998 @smallexample
6999 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7000 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7001 @end smallexample
7002
7003 @noindent
7004 Programs built with /RETURN_CODES=VMS are suitable to be called in
7005 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7006 are suitable for spawning with appropriate GNAT RTL routines.
7007
7008 @end ifset
7009
7010 @node Search Paths and the Run-Time Library (RTL)
7011 @section Search Paths and the Run-Time Library (RTL)
7012
7013 @noindent
7014 With the GNAT source-based library system, the compiler must be able to
7015 find source files for units that are needed by the unit being compiled.
7016 Search paths are used to guide this process.
7017
7018 The compiler compiles one source file whose name must be given
7019 explicitly on the command line. In other words, no searching is done
7020 for this file. To find all other source files that are needed (the most
7021 common being the specs of units), the compiler examines the following
7022 directories, in the following order:
7023
7024 @enumerate
7025 @item
7026 The directory containing the source file of the main unit being compiled
7027 (the file name on the command line).
7028
7029 @item
7030 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7031 @command{gcc} command line, in the order given.
7032
7033 @item
7034 @findex ADA_PRJ_INCLUDE_FILE
7035 Each of the directories listed in the text file whose name is given
7036 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7037
7038 @noindent
7039 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7040 driver when project files are used. It should not normally be set
7041 by other means.
7042
7043 @item
7044 @findex ADA_INCLUDE_PATH
7045 Each of the directories listed in the value of the
7046 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7047 @ifclear vms
7048 Construct this value
7049 exactly as the @code{PATH} environment variable: a list of directory
7050 names separated by colons (semicolons when working with the NT version).
7051 @end ifclear
7052 @ifset vms
7053 Normally, define this value as a logical name containing a comma separated
7054 list of directory names.
7055
7056 This variable can also be defined by means of an environment string
7057 (an argument to the HP C exec* set of functions).
7058
7059 Logical Name:
7060 @smallexample
7061 DEFINE ANOTHER_PATH FOO:[BAG]
7062 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7063 @end smallexample
7064
7065 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7066 first, followed by the standard Ada
7067 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7068 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7069 (Text_IO, Sequential_IO, etc)
7070 instead of the standard Ada packages. Thus, in order to get the standard Ada
7071 packages by default, ADA_INCLUDE_PATH must be redefined.
7072 @end ifset
7073
7074 @item
7075 The content of the @file{ada_source_path} file which is part of the GNAT
7076 installation tree and is used to store standard libraries such as the
7077 GNAT Run Time Library (RTL) source files.
7078 @ifclear vms
7079 @ref{Installing a library}
7080 @end ifclear
7081 @end enumerate
7082
7083 @noindent
7084 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7085 inhibits the use of the directory
7086 containing the source file named in the command line. You can still
7087 have this directory on your search path, but in this case it must be
7088 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7089
7090 Specifying the switch @option{-nostdinc}
7091 inhibits the search of the default location for the GNAT Run Time
7092 Library (RTL) source files.
7093
7094 The compiler outputs its object files and ALI files in the current
7095 working directory.
7096 @ifclear vms
7097 Caution: The object file can be redirected with the @option{-o} switch;
7098 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7099 so the @file{ALI} file will not go to the right place. Therefore, you should
7100 avoid using the @option{-o} switch.
7101 @end ifclear
7102
7103 @findex System.IO
7104 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7105 children make up the GNAT RTL, together with the simple @code{System.IO}
7106 package used in the @code{"Hello World"} example. The sources for these units
7107 are needed by the compiler and are kept together in one directory. Not
7108 all of the bodies are needed, but all of the sources are kept together
7109 anyway. In a normal installation, you need not specify these directory
7110 names when compiling or binding. Either the environment variables or
7111 the built-in defaults cause these files to be found.
7112
7113 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7114 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7115 consisting of child units of @code{GNAT}. This is a collection of generally
7116 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
7117 further details.
7118
7119 Besides simplifying access to the RTL, a major use of search paths is
7120 in compiling sources from multiple directories. This can make
7121 development environments much more flexible.
7122
7123 @node Order of Compilation Issues
7124 @section Order of Compilation Issues
7125
7126 @noindent
7127 If, in our earlier example, there was a spec for the @code{hello}
7128 procedure, it would be contained in the file @file{hello.ads}; yet this
7129 file would not have to be explicitly compiled. This is the result of the
7130 model we chose to implement library management. Some of the consequences
7131 of this model are as follows:
7132
7133 @itemize @bullet
7134 @item
7135 There is no point in compiling specs (except for package
7136 specs with no bodies) because these are compiled as needed by clients. If
7137 you attempt a useless compilation, you will receive an error message.
7138 It is also useless to compile subunits because they are compiled as needed
7139 by the parent.
7140
7141 @item
7142 There are no order of compilation requirements: performing a
7143 compilation never obsoletes anything. The only way you can obsolete
7144 something and require recompilations is to modify one of the
7145 source files on which it depends.
7146
7147 @item
7148 There is no library as such, apart from the ALI files
7149 (@pxref{The Ada Library Information Files}, for information on the format
7150 of these files). For now we find it convenient to create separate ALI files,
7151 but eventually the information therein may be incorporated into the object
7152 file directly.
7153
7154 @item
7155 When you compile a unit, the source files for the specs of all units
7156 that it @code{with}'s, all its subunits, and the bodies of any generics it
7157 instantiates must be available (reachable by the search-paths mechanism
7158 described above), or you will receive a fatal error message.
7159 @end itemize
7160
7161 @node Examples
7162 @section Examples
7163
7164 @noindent
7165 The following are some typical Ada compilation command line examples:
7166
7167 @table @code
7168 @item $ gcc -c xyz.adb
7169 Compile body in file @file{xyz.adb} with all default options.
7170
7171 @ifclear vms
7172 @item $ gcc -c -O2 -gnata xyz-def.adb
7173 @end ifclear
7174 @ifset vms
7175 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7176 @end ifset
7177
7178 Compile the child unit package in file @file{xyz-def.adb} with extensive
7179 optimizations, and pragma @code{Assert}/@code{Debug} statements
7180 enabled.
7181
7182 @item $ gcc -c -gnatc abc-def.adb
7183 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7184 mode.
7185 @end table
7186
7187 @node Binding Using gnatbind
7188 @chapter Binding Using @code{gnatbind}
7189 @findex gnatbind
7190
7191 @menu
7192 * Running gnatbind::
7193 * Switches for gnatbind::
7194 * Command-Line Access::
7195 * Search Paths for gnatbind::
7196 * Examples of gnatbind Usage::
7197 @end menu
7198
7199 @noindent
7200 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7201 to bind compiled GNAT objects.
7202
7203 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7204 driver (see @ref{The GNAT Driver and Project Files}).
7205
7206 The @code{gnatbind} program performs four separate functions:
7207
7208 @enumerate
7209 @item
7210 Checks that a program is consistent, in accordance with the rules in
7211 Chapter 10 of the Ada Reference Manual. In particular, error
7212 messages are generated if a program uses inconsistent versions of a
7213 given unit.
7214
7215 @item
7216 Checks that an acceptable order of elaboration exists for the program
7217 and issues an error message if it cannot find an order of elaboration
7218 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7219
7220 @item
7221 Generates a main program incorporating the given elaboration order.
7222 This program is a small Ada package (body and spec) that
7223 must be subsequently compiled
7224 using the GNAT compiler. The necessary compilation step is usually
7225 performed automatically by @command{gnatlink}. The two most important
7226 functions of this program
7227 are to call the elaboration routines of units in an appropriate order
7228 and to call the main program.
7229
7230 @item
7231 Determines the set of object files required by the given main program.
7232 This information is output in the forms of comments in the generated program,
7233 to be read by the @command{gnatlink} utility used to link the Ada application.
7234 @end enumerate
7235
7236 @node Running gnatbind
7237 @section Running @code{gnatbind}
7238
7239 @noindent
7240 The form of the @code{gnatbind} command is
7241
7242 @smallexample
7243 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
7244 @end smallexample
7245
7246 @noindent
7247 where @file{@i{mainprog}.adb} is the Ada file containing the main program
7248 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7249 package in two files whose names are
7250 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
7251 For example, if given the
7252 parameter @file{hello.ali}, for a main program contained in file
7253 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7254 and @file{b~hello.adb}.
7255
7256 When doing consistency checking, the binder takes into consideration
7257 any source files it can locate. For example, if the binder determines
7258 that the given main program requires the package @code{Pack}, whose
7259 @file{.ALI}
7260 file is @file{pack.ali} and whose corresponding source spec file is
7261 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7262 (using the same search path conventions as previously described for the
7263 @command{gcc} command). If it can locate this source file, it checks that
7264 the time stamps
7265 or source checksums of the source and its references to in @file{ALI} files
7266 match. In other words, any @file{ALI} files that mentions this spec must have
7267 resulted from compiling this version of the source file (or in the case
7268 where the source checksums match, a version close enough that the
7269 difference does not matter).
7270
7271 @cindex Source files, use by binder
7272 The effect of this consistency checking, which includes source files, is
7273 that the binder ensures that the program is consistent with the latest
7274 version of the source files that can be located at bind time. Editing a
7275 source file without compiling files that depend on the source file cause
7276 error messages to be generated by the binder.
7277
7278 For example, suppose you have a main program @file{hello.adb} and a
7279 package @code{P}, from file @file{p.ads} and you perform the following
7280 steps:
7281
7282 @enumerate
7283 @item
7284 Enter @code{gcc -c hello.adb} to compile the main program.
7285
7286 @item
7287 Enter @code{gcc -c p.ads} to compile package @code{P}.
7288
7289 @item
7290 Edit file @file{p.ads}.
7291
7292 @item
7293 Enter @code{gnatbind hello}.
7294 @end enumerate
7295
7296 @noindent
7297 At this point, the file @file{p.ali} contains an out-of-date time stamp
7298 because the file @file{p.ads} has been edited. The attempt at binding
7299 fails, and the binder generates the following error messages:
7300
7301 @smallexample
7302 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7303 error: "p.ads" has been modified and must be recompiled
7304 @end smallexample
7305
7306 @noindent
7307 Now both files must be recompiled as indicated, and then the bind can
7308 succeed, generating a main program. You need not normally be concerned
7309 with the contents of this file, but for reference purposes a sample
7310 binder output file is given in @ref{Example of Binder Output File}.
7311
7312 In most normal usage, the default mode of @command{gnatbind} which is to
7313 generate the main package in Ada, as described in the previous section.
7314 In particular, this means that any Ada programmer can read and understand
7315 the generated main program. It can also be debugged just like any other
7316 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7317 @command{gnatbind} and @command{gnatlink}.
7318
7319 However for some purposes it may be convenient to generate the main
7320 program in C rather than Ada. This may for example be helpful when you
7321 are generating a mixed language program with the main program in C. The
7322 GNAT compiler itself is an example.
7323 The use of the @option{^-C^/BIND_FILE=C^} switch
7324 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7325 be generated in C (and compiled using the gnu C compiler).
7326
7327 @node Switches for gnatbind
7328 @section Switches for @command{gnatbind}
7329
7330 @noindent
7331 The following switches are available with @code{gnatbind}; details will
7332 be presented in subsequent sections.
7333
7334 @menu
7335 * Consistency-Checking Modes::
7336 * Binder Error Message Control::
7337 * Elaboration Control::
7338 * Output Control::
7339 * Binding with Non-Ada Main Programs::
7340 * Binding Programs with No Main Subprogram::
7341 @end menu
7342
7343 @table @option
7344 @c !sort!
7345
7346 @item -a
7347 @cindex @option{-a} @command{gnatbind}
7348 Indicates that, if supported by the platform, the adainit procedure should
7349 be treated as an initialisation routine by the linker (a constructor). This
7350 is intended to be used by the Project Manager to automatically initialize
7351 shared Stand-Alone Libraries.
7352
7353 @item ^-aO^/OBJECT_SEARCH^
7354 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7355 Specify directory to be searched for ALI files.
7356
7357 @item ^-aI^/SOURCE_SEARCH^
7358 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7359 Specify directory to be searched for source file.
7360
7361 @item ^-A^/BIND_FILE=ADA^
7362 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7363 Generate binder program in Ada (default)
7364
7365 @item ^-b^/REPORT_ERRORS=BRIEF^
7366 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7367 Generate brief messages to @file{stderr} even if verbose mode set.
7368
7369 @item ^-c^/NOOUTPUT^
7370 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7371 Check only, no generation of binder output file.
7372
7373 @item ^-C^/BIND_FILE=C^
7374 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7375 Generate binder program in C
7376
7377 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]
7378 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]} (@command{gnatbind})
7379 This switch can be used to change the default task stack size value
7380 to a specified size @var{nn}, which is expressed in bytes by default, or
7381 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7382 with @var{m}.
7383 In the absence of a [k|m] suffix, this switch is equivalent, in effect,
7384 to completing all task specs with
7385 @smallexample @c ada
7386    pragma Storage_Size (nn);
7387 @end smallexample
7388 When they do not already have such a pragma.
7389
7390 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}[k|m]
7391 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7392 This switch can be used to change the default secondary stack size value
7393 to a specified size @var{nn}, which is expressed in bytes by default, or
7394 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7395 with @var{m}.
7396
7397 The secondary stack is used to deal with functions that return a variable
7398 sized result, for example a function returning an unconstrained
7399 String. There are two ways in which this secondary stack is allocated.
7400
7401 For most targets, the secondary stack is growing on demand and is allocated
7402 as a chain of blocks in the heap. The -D option is not very
7403 relevant. It only give some control over the size of the allocated
7404 blocks (whose size is the minimum of the default secondary stack size value,
7405 and the actual size needed for the current allocation request).
7406
7407 For certain targets, notably VxWorks 653,
7408 the secondary stack is allocated by carving off a fixed ratio chunk of the
7409 primary task stack. The -D option is used to defined the
7410 size of the environment task's secondary stack.
7411
7412 @item ^-e^/ELABORATION_DEPENDENCIES^
7413 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7414 Output complete list of elaboration-order dependencies.
7415
7416 @item ^-E^/STORE_TRACEBACKS^
7417 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7418 Store tracebacks in exception occurrences when the target supports it.
7419 This is the default with the zero cost exception mechanism.
7420 @ignore
7421 @c The following may get moved to an appendix
7422 This option is currently supported on the following targets:
7423 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7424 @end ignore
7425 See also the packages @code{GNAT.Traceback} and
7426 @code{GNAT.Traceback.Symbolic} for more information.
7427 @ifclear vms
7428 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7429 @command{gcc} option.
7430 @end ifclear
7431
7432 @item ^-F^/FORCE_ELABS_FLAGS^
7433 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7434 Force the checks of elaboration flags. @command{gnatbind} does not normally
7435 generate checks of elaboration flags for the main executable, except when
7436 a Stand-Alone Library is used. However, there are cases when this cannot be
7437 detected by gnatbind. An example is importing an interface of a Stand-Alone
7438 Library through a pragma Import and only specifying through a linker switch
7439 this Stand-Alone Library. This switch is used to guarantee that elaboration
7440 flag checks are generated.
7441
7442 @item ^-h^/HELP^
7443 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7444 Output usage (help) information
7445
7446 @item ^-I^/SEARCH^
7447 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7448 Specify directory to be searched for source and ALI files.
7449
7450 @item ^-I-^/NOCURRENT_DIRECTORY^
7451 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7452 Do not look for sources in the current directory where @code{gnatbind} was
7453 invoked, and do not look for ALI files in the directory containing the
7454 ALI file named in the @code{gnatbind} command line.
7455
7456 @item ^-l^/ORDER_OF_ELABORATION^
7457 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7458 Output chosen elaboration order.
7459
7460 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7461 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7462 Bind the units for library building. In this case the adainit and
7463 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7464 are renamed to ^xxxinit^XXXINIT^ and
7465 ^xxxfinal^XXXFINAL^.
7466 Implies ^-n^/NOCOMPILE^.
7467 @ifclear vms
7468 (@xref{GNAT and Libraries}, for more details.)
7469 @end ifclear
7470 @ifset vms
7471 On OpenVMS, these init and final procedures are exported in uppercase
7472 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7473 the init procedure will be "TOTOINIT" and the exported name of the final
7474 procedure will be "TOTOFINAL".
7475 @end ifset
7476
7477 @item ^-Mxyz^/RENAME_MAIN=xyz^
7478 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7479 Rename generated main program from main to xyz. This option is
7480 supported on cross environments only.
7481
7482 @item ^-m^/ERROR_LIMIT=^@var{n}
7483 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7484 Limit number of detected errors to @var{n}, where @var{n} is
7485 in the range 1..999_999. The default value if no switch is
7486 given is 9999. Binding is terminated if the limit is exceeded.
7487 @ifset unw
7488 Furthermore, under Windows, the sources pointed to by the libraries path
7489 set in the registry are not searched for.
7490 @end ifset
7491
7492 @item ^-n^/NOMAIN^
7493 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7494 No main program.
7495
7496 @item -nostdinc
7497 @cindex @option{-nostdinc} (@command{gnatbind})
7498 Do not look for sources in the system default directory.
7499
7500 @item -nostdlib
7501 @cindex @option{-nostdlib} (@command{gnatbind})
7502 Do not look for library files in the system default directory.
7503
7504 @item --RTS=@var{rts-path}
7505 @cindex @option{--RTS} (@code{gnatbind})
7506 Specifies the default location of the runtime library. Same meaning as the
7507 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7508
7509 @item ^-o ^/OUTPUT=^@var{file}
7510 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7511 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7512 Note that if this option is used, then linking must be done manually,
7513 gnatlink cannot be used.
7514
7515 @item ^-O^/OBJECT_LIST^
7516 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7517 Output object list.
7518
7519 @item ^-p^/PESSIMISTIC_ELABORATION^
7520 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7521 Pessimistic (worst-case) elaboration order
7522
7523 @item ^-R^-R^
7524 @cindex @option{^-R^-R^} (@command{gnatbind})
7525 Output closure source list.
7526
7527 @item ^-s^/READ_SOURCES=ALL^
7528 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7529 Require all source files to be present.
7530
7531 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7532 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7533 Specifies the value to be used when detecting uninitialized scalar
7534 objects with pragma Initialize_Scalars.
7535 The @var{xxx} ^string specified with the switch^option^ may be either
7536 @itemize @bullet
7537 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7538 @item ``@option{^lo^LOW^}'' for the lowest possible value
7539 @item ``@option{^hi^HIGH^}'' for the highest possible value
7540 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7541 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7542 @end itemize
7543
7544 In addition, you can specify @option{-Sev} to indicate that the value is
7545 to be set at run time. In this case, the program will look for an environment
7546 @cindex GNAT_INIT_SCALARS
7547 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7548 of @option{in/lo/hi/xx} with the same meanings as above.
7549 If no environment variable is found, or if it does not have a valid value,
7550 then the default is @option{in} (invalid values).
7551
7552 @ifclear vms
7553 @item -static
7554 @cindex @option{-static} (@code{gnatbind})
7555 Link against a static GNAT run time.
7556
7557 @item -shared
7558 @cindex @option{-shared} (@code{gnatbind})
7559 Link against a shared GNAT run time when available.
7560 @end ifclear
7561
7562 @item ^-t^/NOTIME_STAMP_CHECK^
7563 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7564 Tolerate time stamp and other consistency errors
7565
7566 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7567 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7568 Set the time slice value to @var{n} milliseconds. If the system supports
7569 the specification of a specific time slice value, then the indicated value
7570 is used. If the system does not support specific time slice values, but
7571 does support some general notion of round-robin scheduling, then any
7572 nonzero value will activate round-robin scheduling.
7573
7574 A value of zero is treated specially. It turns off time
7575 slicing, and in addition, indicates to the tasking run time that the
7576 semantics should match as closely as possible the Annex D
7577 requirements of the Ada RM, and in particular sets the default
7578 scheduling policy to @code{FIFO_Within_Priorities}.
7579
7580 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
7581 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
7582 Enable dynamic stack usage, with n result stored and displayed at program
7583 termination. Results that can't be stored are displayed on the fly, at task
7584 termination. This option is currently not supported on OpenVMS I64 platforms.
7585
7586 @item ^-v^/REPORT_ERRORS=VERBOSE^
7587 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7588 Verbose mode. Write error messages, header, summary output to
7589 @file{stdout}.
7590
7591 @ifclear vms
7592 @item -w@var{x}
7593 @cindex @option{-w} (@code{gnatbind})
7594 Warning mode (@var{x}=s/e for suppress/treat as error)
7595 @end ifclear
7596
7597 @ifset vms
7598 @item /WARNINGS=NORMAL
7599 @cindex @option{/WARNINGS} (@code{gnatbind})
7600 Normal warnings mode. Warnings are issued but ignored
7601
7602 @item /WARNINGS=SUPPRESS
7603 @cindex @option{/WARNINGS} (@code{gnatbind})
7604 All warning messages are suppressed
7605
7606 @item /WARNINGS=ERROR
7607 @cindex @option{/WARNINGS} (@code{gnatbind})
7608 Warning messages are treated as fatal errors
7609 @end ifset
7610
7611 @item ^-x^/READ_SOURCES=NONE^
7612 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7613 Exclude source files (check object consistency only).
7614
7615 @ifset vms
7616 @item /READ_SOURCES=AVAILABLE
7617 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7618 Default mode, in which sources are checked for consistency only if
7619 they are available.
7620 @end ifset
7621
7622 @item ^-z^/ZERO_MAIN^
7623 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7624 No main subprogram.
7625 @end table
7626
7627 @ifclear vms
7628 @noindent
7629 You may obtain this listing of switches by running @code{gnatbind} with
7630 no arguments.
7631 @end ifclear
7632
7633 @node Consistency-Checking Modes
7634 @subsection Consistency-Checking Modes
7635
7636 @noindent
7637 As described earlier, by default @code{gnatbind} checks
7638 that object files are consistent with one another and are consistent
7639 with any source files it can locate. The following switches control binder
7640 access to sources.
7641
7642 @table @option
7643 @c !sort!
7644 @item ^-s^/READ_SOURCES=ALL^
7645 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7646 Require source files to be present. In this mode, the binder must be
7647 able to locate all source files that are referenced, in order to check
7648 their consistency. In normal mode, if a source file cannot be located it
7649 is simply ignored. If you specify this switch, a missing source
7650 file is an error.
7651
7652 @item ^-x^/READ_SOURCES=NONE^
7653 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7654 Exclude source files. In this mode, the binder only checks that ALI
7655 files are consistent with one another. Source files are not accessed.
7656 The binder runs faster in this mode, and there is still a guarantee that
7657 the resulting program is self-consistent.
7658 If a source file has been edited since it was last compiled, and you
7659 specify this switch, the binder will not detect that the object
7660 file is out of date with respect to the source file. Note that this is the
7661 mode that is automatically used by @command{gnatmake} because in this
7662 case the checking against sources has already been performed by
7663 @command{gnatmake} in the course of compilation (i.e. before binding).
7664
7665 @ifset vms
7666 @item /READ_SOURCES=AVAILABLE
7667 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7668 This is the default mode in which source files are checked if they are
7669 available, and ignored if they are not available.
7670 @end ifset
7671 @end table
7672
7673 @node Binder Error Message Control
7674 @subsection Binder Error Message Control
7675
7676 @noindent
7677 The following switches provide control over the generation of error
7678 messages from the binder:
7679
7680 @table @option
7681 @c !sort!
7682 @item ^-v^/REPORT_ERRORS=VERBOSE^
7683 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7684 Verbose mode. In the normal mode, brief error messages are generated to
7685 @file{stderr}. If this switch is present, a header is written
7686 to @file{stdout} and any error messages are directed to @file{stdout}.
7687 All that is written to @file{stderr} is a brief summary message.
7688
7689 @item ^-b^/REPORT_ERRORS=BRIEF^
7690 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7691 Generate brief error messages to @file{stderr} even if verbose mode is
7692 specified. This is relevant only when used with the
7693 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7694
7695 @ifclear vms
7696 @item -m@var{n}
7697 @cindex @option{-m} (@code{gnatbind})
7698 Limits the number of error messages to @var{n}, a decimal integer in the
7699 range 1-999. The binder terminates immediately if this limit is reached.
7700
7701 @item -M@var{xxx}
7702 @cindex @option{-M} (@code{gnatbind})
7703 Renames the generated main program from @code{main} to @code{xxx}.
7704 This is useful in the case of some cross-building environments, where
7705 the actual main program is separate from the one generated
7706 by @code{gnatbind}.
7707 @end ifclear
7708
7709 @item ^-ws^/WARNINGS=SUPPRESS^
7710 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7711 @cindex Warnings
7712 Suppress all warning messages.
7713
7714 @item ^-we^/WARNINGS=ERROR^
7715 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7716 Treat any warning messages as fatal errors.
7717
7718 @ifset vms
7719 @item /WARNINGS=NORMAL
7720 Standard mode with warnings generated, but warnings do not get treated
7721 as errors.
7722 @end ifset
7723
7724 @item ^-t^/NOTIME_STAMP_CHECK^
7725 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7726 @cindex Time stamp checks, in binder
7727 @cindex Binder consistency checks
7728 @cindex Consistency checks, in binder
7729 The binder performs a number of consistency checks including:
7730
7731 @itemize @bullet
7732 @item
7733 Check that time stamps of a given source unit are consistent
7734 @item
7735 Check that checksums of a given source unit are consistent
7736 @item
7737 Check that consistent versions of @code{GNAT} were used for compilation
7738 @item
7739 Check consistency of configuration pragmas as required
7740 @end itemize
7741
7742 @noindent
7743 Normally failure of such checks, in accordance with the consistency
7744 requirements of the Ada Reference Manual, causes error messages to be
7745 generated which abort the binder and prevent the output of a binder
7746 file and subsequent link to obtain an executable.
7747
7748 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7749 into warnings, so that
7750 binding and linking can continue to completion even in the presence of such
7751 errors. The result may be a failed link (due to missing symbols), or a
7752 non-functional executable which has undefined semantics.
7753 @emph{This means that
7754 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7755 with extreme care.}
7756 @end table
7757
7758 @node Elaboration Control
7759 @subsection Elaboration Control
7760
7761 @noindent
7762 The following switches provide additional control over the elaboration
7763 order. For full details see @ref{Elaboration Order Handling in GNAT}.
7764
7765 @table @option
7766 @item ^-p^/PESSIMISTIC_ELABORATION^
7767 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7768 Normally the binder attempts to choose an elaboration order that is
7769 likely to minimize the likelihood of an elaboration order error resulting
7770 in raising a @code{Program_Error} exception. This switch reverses the
7771 action of the binder, and requests that it deliberately choose an order
7772 that is likely to maximize the likelihood of an elaboration error.
7773 This is useful in ensuring portability and avoiding dependence on
7774 accidental fortuitous elaboration ordering.
7775
7776 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7777 switch if dynamic
7778 elaboration checking is used (@option{-gnatE} switch used for compilation).
7779 This is because in the default static elaboration mode, all necessary
7780 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
7781 These implicit pragmas are still respected by the binder in
7782 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7783 safe elaboration order is assured.
7784 @end table
7785
7786 @node Output Control
7787 @subsection Output Control
7788
7789 @noindent
7790 The following switches allow additional control over the output
7791 generated by the binder.
7792
7793 @table @option
7794 @c !sort!
7795
7796 @item ^-A^/BIND_FILE=ADA^
7797 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7798 Generate binder program in Ada (default). The binder program is named
7799 @file{b~@var{mainprog}.adb} by default. This can be changed with
7800 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7801
7802 @item ^-c^/NOOUTPUT^
7803 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7804 Check only. Do not generate the binder output file. In this mode the
7805 binder performs all error checks but does not generate an output file.
7806
7807 @item ^-C^/BIND_FILE=C^
7808 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7809 Generate binder program in C. The binder program is named
7810 @file{b_@var{mainprog}.c}.
7811 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7812 option.
7813
7814 @item ^-e^/ELABORATION_DEPENDENCIES^
7815 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7816 Output complete list of elaboration-order dependencies, showing the
7817 reason for each dependency. This output can be rather extensive but may
7818 be useful in diagnosing problems with elaboration order. The output is
7819 written to @file{stdout}.
7820
7821 @item ^-h^/HELP^
7822 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7823 Output usage information. The output is written to @file{stdout}.
7824
7825 @item ^-K^/LINKER_OPTION_LIST^
7826 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7827 Output linker options to @file{stdout}. Includes library search paths,
7828 contents of pragmas Ident and Linker_Options, and libraries added
7829 by @code{gnatbind}.
7830
7831 @item ^-l^/ORDER_OF_ELABORATION^
7832 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7833 Output chosen elaboration order. The output is written to @file{stdout}.
7834
7835 @item ^-O^/OBJECT_LIST^
7836 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7837 Output full names of all the object files that must be linked to provide
7838 the Ada component of the program. The output is written to @file{stdout}.
7839 This list includes the files explicitly supplied and referenced by the user
7840 as well as implicitly referenced run-time unit files. The latter are
7841 omitted if the corresponding units reside in shared libraries. The
7842 directory names for the run-time units depend on the system configuration.
7843
7844 @item ^-o ^/OUTPUT=^@var{file}
7845 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7846 Set name of output file to @var{file} instead of the normal
7847 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7848 binder generated body filename. In C mode you would normally give
7849 @var{file} an extension of @file{.c} because it will be a C source program.
7850 Note that if this option is used, then linking must be done manually.
7851 It is not possible to use gnatlink in this case, since it cannot locate
7852 the binder file.
7853
7854 @item ^-r^/RESTRICTION_LIST^
7855 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7856 Generate list of @code{pragma Restrictions} that could be applied to
7857 the current unit. This is useful for code audit purposes, and also may
7858 be used to improve code generation in some cases.
7859
7860 @end table
7861
7862 @node Binding with Non-Ada Main Programs
7863 @subsection Binding with Non-Ada Main Programs
7864
7865 @noindent
7866 In our description so far we have assumed that the main
7867 program is in Ada, and that the task of the binder is to generate a
7868 corresponding function @code{main} that invokes this Ada main
7869 program. GNAT also supports the building of executable programs where
7870 the main program is not in Ada, but some of the called routines are
7871 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7872 The following switch is used in this situation:
7873
7874 @table @option
7875 @item ^-n^/NOMAIN^
7876 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7877 No main program. The main program is not in Ada.
7878 @end table
7879
7880 @noindent
7881 In this case, most of the functions of the binder are still required,
7882 but instead of generating a main program, the binder generates a file
7883 containing the following callable routines:
7884
7885 @table @code
7886 @item adainit
7887 @findex adainit
7888 You must call this routine to initialize the Ada part of the program by
7889 calling the necessary elaboration routines. A call to @code{adainit} is
7890 required before the first call to an Ada subprogram.
7891
7892 Note that it is assumed that the basic execution environment must be setup
7893 to be appropriate for Ada execution at the point where the first Ada
7894 subprogram is called. In particular, if the Ada code will do any
7895 floating-point operations, then the FPU must be setup in an appropriate
7896 manner. For the case of the x86, for example, full precision mode is
7897 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7898 that the FPU is in the right state.
7899
7900 @item adafinal
7901 @findex adafinal
7902 You must call this routine to perform any library-level finalization
7903 required by the Ada subprograms. A call to @code{adafinal} is required
7904 after the last call to an Ada subprogram, and before the program
7905 terminates.
7906 @end table
7907
7908 @noindent
7909 If the @option{^-n^/NOMAIN^} switch
7910 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7911 @cindex Binder, multiple input files
7912 is given, more than one ALI file may appear on
7913 the command line for @code{gnatbind}. The normal @dfn{closure}
7914 calculation is performed for each of the specified units. Calculating
7915 the closure means finding out the set of units involved by tracing
7916 @code{with} references. The reason it is necessary to be able to
7917 specify more than one ALI file is that a given program may invoke two or
7918 more quite separate groups of Ada units.
7919
7920 The binder takes the name of its output file from the last specified ALI
7921 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7922 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7923 The output is an Ada unit in source form that can
7924 be compiled with GNAT unless the -C switch is used in which case the
7925 output is a C source file, which must be compiled using the C compiler.
7926 This compilation occurs automatically as part of the @command{gnatlink}
7927 processing.
7928
7929 Currently the GNAT run time requires a FPU using 80 bits mode
7930 precision. Under targets where this is not the default it is required to
7931 call GNAT.Float_Control.Reset before using floating point numbers (this
7932 include float computation, float input and output) in the Ada code. A
7933 side effect is that this could be the wrong mode for the foreign code
7934 where floating point computation could be broken after this call.
7935
7936 @node Binding Programs with No Main Subprogram
7937 @subsection Binding Programs with No Main Subprogram
7938
7939 @noindent
7940 It is possible to have an Ada program which does not have a main
7941 subprogram. This program will call the elaboration routines of all the
7942 packages, then the finalization routines.
7943
7944 The following switch is used to bind programs organized in this manner:
7945
7946 @table @option
7947 @item ^-z^/ZERO_MAIN^
7948 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7949 Normally the binder checks that the unit name given on the command line
7950 corresponds to a suitable main subprogram. When this switch is used,
7951 a list of ALI files can be given, and the execution of the program
7952 consists of elaboration of these units in an appropriate order.
7953 @end table
7954
7955 @node Command-Line Access
7956 @section Command-Line Access
7957
7958 @noindent
7959 The package @code{Ada.Command_Line} provides access to the command-line
7960 arguments and program name. In order for this interface to operate
7961 correctly, the two variables
7962
7963 @smallexample
7964 @group
7965 int gnat_argc;
7966 char **gnat_argv;
7967 @end group
7968 @end smallexample
7969
7970 @noindent
7971 @findex gnat_argv
7972 @findex gnat_argc
7973 are declared in one of the GNAT library routines. These variables must
7974 be set from the actual @code{argc} and @code{argv} values passed to the
7975 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7976 generates the C main program to automatically set these variables.
7977 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7978 set these variables. If they are not set, the procedures in
7979 @code{Ada.Command_Line} will not be available, and any attempt to use
7980 them will raise @code{Constraint_Error}. If command line access is
7981 required, your main program must set @code{gnat_argc} and
7982 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7983 it.
7984
7985 @node Search Paths for gnatbind
7986 @section Search Paths for @code{gnatbind}
7987
7988 @noindent
7989 The binder takes the name of an ALI file as its argument and needs to
7990 locate source files as well as other ALI files to verify object consistency.
7991
7992 For source files, it follows exactly the same search rules as @command{gcc}
7993 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7994 directories searched are:
7995
7996 @enumerate
7997 @item
7998 The directory containing the ALI file named in the command line, unless
7999 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8000
8001 @item
8002 All directories specified by @option{^-I^/SEARCH^}
8003 switches on the @code{gnatbind}
8004 command line, in the order given.
8005
8006 @item
8007 @findex ADA_PRJ_OBJECTS_FILE
8008 Each of the directories listed in the text file whose name is given
8009 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8010
8011 @noindent
8012 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8013 driver when project files are used. It should not normally be set
8014 by other means.
8015
8016 @item
8017 @findex ADA_OBJECTS_PATH
8018 Each of the directories listed in the value of the
8019 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8020 @ifset unw
8021 Construct this value
8022 exactly as the @code{PATH} environment variable: a list of directory
8023 names separated by colons (semicolons when working with the NT version
8024 of GNAT).
8025 @end ifset
8026 @ifset vms
8027 Normally, define this value as a logical name containing a comma separated
8028 list of directory names.
8029
8030 This variable can also be defined by means of an environment string
8031 (an argument to the HP C exec* set of functions).
8032
8033 Logical Name:
8034 @smallexample
8035 DEFINE ANOTHER_PATH FOO:[BAG]
8036 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8037 @end smallexample
8038
8039 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8040 first, followed by the standard Ada
8041 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8042 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8043 (Text_IO, Sequential_IO, etc)
8044 instead of the standard Ada packages. Thus, in order to get the standard Ada
8045 packages by default, ADA_OBJECTS_PATH must be redefined.
8046 @end ifset
8047
8048 @item
8049 The content of the @file{ada_object_path} file which is part of the GNAT
8050 installation tree and is used to store standard libraries such as the
8051 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8052 specified.
8053 @ifclear vms
8054 @ref{Installing a library}
8055 @end ifclear
8056 @end enumerate
8057
8058 @noindent
8059 In the binder the switch @option{^-I^/SEARCH^}
8060 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8061 is used to specify both source and
8062 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8063 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8064 instead if you want to specify
8065 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8066 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8067 if you want to specify library paths
8068 only. This means that for the binder
8069 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8070 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8071 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8072 The binder generates the bind file (a C language source file) in the
8073 current working directory.
8074
8075 @findex Ada
8076 @findex System
8077 @findex Interfaces
8078 @findex GNAT
8079 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8080 children make up the GNAT Run-Time Library, together with the package
8081 GNAT and its children, which contain a set of useful additional
8082 library functions provided by GNAT. The sources for these units are
8083 needed by the compiler and are kept together in one directory. The ALI
8084 files and object files generated by compiling the RTL are needed by the
8085 binder and the linker and are kept together in one directory, typically
8086 different from the directory containing the sources. In a normal
8087 installation, you need not specify these directory names when compiling
8088 or binding. Either the environment variables or the built-in defaults
8089 cause these files to be found.
8090
8091 Besides simplifying access to the RTL, a major use of search paths is
8092 in compiling sources from multiple directories. This can make
8093 development environments much more flexible.
8094
8095 @node Examples of gnatbind Usage
8096 @section Examples of @code{gnatbind} Usage
8097
8098 @noindent
8099 This section contains a number of examples of using the GNAT binding
8100 utility @code{gnatbind}.
8101
8102 @table @code
8103 @item gnatbind hello
8104 The main program @code{Hello} (source program in @file{hello.adb}) is
8105 bound using the standard switch settings. The generated main program is
8106 @file{b~hello.adb}. This is the normal, default use of the binder.
8107
8108 @ifclear vms
8109 @item gnatbind hello -o mainprog.adb
8110 @end ifclear
8111 @ifset vms
8112 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8113 @end ifset
8114 The main program @code{Hello} (source program in @file{hello.adb}) is
8115 bound using the standard switch settings. The generated main program is
8116 @file{mainprog.adb} with the associated spec in
8117 @file{mainprog.ads}. Note that you must specify the body here not the
8118 spec, in the case where the output is in Ada. Note that if this option
8119 is used, then linking must be done manually, since gnatlink will not
8120 be able to find the generated file.
8121
8122 @ifclear vms
8123 @item gnatbind main -C -o mainprog.c -x
8124 @end ifclear
8125 @ifset vms
8126 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8127 @end ifset
8128 The main program @code{Main} (source program in
8129 @file{main.adb}) is bound, excluding source files from the
8130 consistency checking, generating
8131 the file @file{mainprog.c}.
8132
8133 @ifclear vms
8134 @item gnatbind -x main_program -C -o mainprog.c
8135 This command is exactly the same as the previous example. Switches may
8136 appear anywhere in the command line, and single letter switches may be
8137 combined into a single switch.
8138 @end ifclear
8139
8140 @ifclear vms
8141 @item gnatbind -n math dbase -C -o ada-control.c
8142 @end ifclear
8143 @ifset vms
8144 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8145 @end ifset
8146 The main program is in a language other than Ada, but calls to
8147 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8148 to @code{gnatbind} generates the file @file{ada-control.c} containing
8149 the @code{adainit} and @code{adafinal} routines to be called before and
8150 after accessing the Ada units.
8151 @end table
8152
8153 @c ------------------------------------
8154 @node Linking Using gnatlink
8155 @chapter Linking Using @command{gnatlink}
8156 @c ------------------------------------
8157 @findex gnatlink
8158
8159 @noindent
8160 This chapter discusses @command{gnatlink}, a tool that links
8161 an Ada program and builds an executable file. This utility
8162 invokes the system linker ^(via the @command{gcc} command)^^
8163 with a correct list of object files and library references.
8164 @command{gnatlink} automatically determines the list of files and
8165 references for the Ada part of a program. It uses the binder file
8166 generated by the @command{gnatbind} to determine this list.
8167
8168 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8169 driver (see @ref{The GNAT Driver and Project Files}).
8170
8171 @menu
8172 * Running gnatlink::
8173 * Switches for gnatlink::
8174 @end menu
8175
8176 @node Running gnatlink
8177 @section Running @command{gnatlink}
8178
8179 @noindent
8180 The form of the @command{gnatlink} command is
8181
8182 @smallexample
8183 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
8184            [@var{non-Ada objects}] [@var{linker options}]
8185 @end smallexample
8186
8187 @noindent
8188 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8189 non-Ada objects
8190 or linker options) may be in any order, provided that no non-Ada object may
8191 be mistaken for a main @file{ALI} file.
8192 Any file name @file{F} without the @file{.ali}
8193 extension will be taken as the main @file{ALI} file if a file exists
8194 whose name is the concatenation of @file{F} and @file{.ali}.
8195
8196 @noindent
8197 @file{@var{mainprog}.ali} references the ALI file of the main program.
8198 The @file{.ali} extension of this file can be omitted. From this
8199 reference, @command{gnatlink} locates the corresponding binder file
8200 @file{b~@var{mainprog}.adb} and, using the information in this file along
8201 with the list of non-Ada objects and linker options, constructs a
8202 linker command file to create the executable.
8203
8204 The arguments other than the @command{gnatlink} switches and the main
8205 @file{ALI} file are passed to the linker uninterpreted.
8206 They typically include the names of
8207 object files for units written in other languages than Ada and any library
8208 references required to resolve references in any of these foreign language
8209 units, or in @code{Import} pragmas in any Ada units.
8210
8211 @var{linker options} is an optional list of linker specific
8212 switches.
8213 The default linker called by gnatlink is @var{gcc} which in
8214 turn calls the appropriate system linker.
8215 Standard options for the linker such as @option{-lmy_lib} or
8216 @option{-Ldir} can be added as is.
8217 For options that are not recognized by
8218 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
8219 @option{-Wl,}.
8220 Refer to the GCC documentation for
8221 details. Here is an example showing how to generate a linker map:
8222
8223 @smallexample
8224 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8225 @end smallexample
8226
8227 Using @var{linker options} it is possible to set the program stack and
8228 heap size.
8229 @ifclear vms
8230 See @ref{Setting Stack Size from gnatlink} and
8231 @ref{Setting Heap Size from gnatlink}.
8232 @end ifclear
8233
8234 @command{gnatlink} determines the list of objects required by the Ada
8235 program and prepends them to the list of objects passed to the linker.
8236 @command{gnatlink} also gathers any arguments set by the use of
8237 @code{pragma Linker_Options} and adds them to the list of arguments
8238 presented to the linker.
8239
8240 @ifset vms
8241 @command{gnatlink} accepts the following types of extra files on the command
8242 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
8243 options files (.OPT). These are recognized and handled according to their
8244 extension.
8245 @end ifset
8246
8247 @node Switches for gnatlink
8248 @section Switches for @command{gnatlink}
8249
8250 @noindent
8251 The following switches are available with the @command{gnatlink} utility:
8252
8253 @table @option
8254 @c !sort!
8255
8256 @item ^-A^/BIND_FILE=ADA^
8257 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8258 The binder has generated code in Ada. This is the default.
8259
8260 @item ^-C^/BIND_FILE=C^
8261 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8262 If instead of generating a file in Ada, the binder has generated one in
8263 C, then the linker needs to know about it. Use this switch to signal
8264 to @command{gnatlink} that the binder has generated C code rather than
8265 Ada code.
8266
8267 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8268 @cindex Command line length
8269 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8270 On some targets, the command line length is limited, and @command{gnatlink}
8271 will generate a separate file for the linker if the list of object files
8272 is too long.
8273 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8274 to be generated even if
8275 the limit is not exceeded. This is useful in some cases to deal with
8276 special situations where the command line length is exceeded.
8277
8278 @item ^-g^/DEBUG^
8279 @cindex Debugging information, including
8280 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8281 The option to include debugging information causes the Ada bind file (in
8282 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8283 @option{^-g^/DEBUG^}.
8284 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8285 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8286 Without @option{^-g^/DEBUG^}, the binder removes these files by
8287 default. The same procedure apply if a C bind file was generated using
8288 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8289 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8290
8291 @item ^-n^/NOCOMPILE^
8292 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8293 Do not compile the file generated by the binder. This may be used when
8294 a link is rerun with different options, but there is no need to recompile
8295 the binder file.
8296
8297 @item ^-v^/VERBOSE^
8298 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8299 Causes additional information to be output, including a full list of the
8300 included object files. This switch option is most useful when you want
8301 to see what set of object files are being used in the link step.
8302
8303 @item ^-v -v^/VERBOSE/VERBOSE^
8304 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8305 Very verbose mode. Requests that the compiler operate in verbose mode when
8306 it compiles the binder file, and that the system linker run in verbose mode.
8307
8308 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8309 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8310 @var{exec-name} specifies an alternate name for the generated
8311 executable program. If this switch is omitted, the executable has the same
8312 name as the main unit. For example, @code{gnatlink try.ali} creates
8313 an executable called @file{^try^TRY.EXE^}.
8314
8315 @ifclear vms
8316 @item -b @var{target}
8317 @cindex @option{-b} (@command{gnatlink})
8318 Compile your program to run on @var{target}, which is the name of a
8319 system configuration. You must have a GNAT cross-compiler built if
8320 @var{target} is not the same as your host system.
8321
8322 @item -B@var{dir}
8323 @cindex @option{-B} (@command{gnatlink})
8324 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8325 from @var{dir} instead of the default location. Only use this switch
8326 when multiple versions of the GNAT compiler are available. See the
8327 @command{gcc} manual page for further details. You would normally use the
8328 @option{-b} or @option{-V} switch instead.
8329
8330 @item --GCC=@var{compiler_name}
8331 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8332 Program used for compiling the binder file. The default is
8333 @command{gcc}. You need to use quotes around @var{compiler_name} if
8334 @code{compiler_name} contains spaces or other separator characters.
8335 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8336 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8337 inserted after your command name. Thus in the above example the compiler
8338 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8339 A limitation of this syntax is that the name and path name of the executable
8340 itself must not include any embedded spaces. If several
8341 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8342 is taken into account. However, all the additional switches are also taken
8343 into account. Thus,
8344 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8345 @option{--GCC="bar -x -y -z -t"}.
8346
8347 @item --LINK=@var{name}
8348 @cindex @option{--LINK=} (@command{gnatlink})
8349 @var{name} is the name of the linker to be invoked. This is especially
8350 useful in mixed language programs since languages such as C++ require
8351 their own linker to be used. When this switch is omitted, the default
8352 name for the linker is @command{gcc}. When this switch is used, the
8353 specified linker is called instead of @command{gcc} with exactly the same
8354 parameters that would have been passed to @command{gcc} so if the desired
8355 linker requires different parameters it is necessary to use a wrapper
8356 script that massages the parameters before invoking the real linker. It
8357 may be useful to control the exact invocation by using the verbose
8358 switch.
8359
8360 @end ifclear
8361
8362 @ifset vms
8363 @item /DEBUG=TRACEBACK
8364 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8365 This qualifier causes sufficient information to be included in the
8366 executable file to allow a traceback, but does not include the full
8367 symbol information needed by the debugger.
8368
8369 @item /IDENTIFICATION="<string>"
8370 @code{"<string>"} specifies the string to be stored in the image file
8371 identification field in the image header.
8372 It overrides any pragma @code{Ident} specified string.
8373
8374 @item /NOINHIBIT-EXEC
8375 Generate the executable file even if there are linker warnings.
8376
8377 @item /NOSTART_FILES
8378 Don't link in the object file containing the ``main'' transfer address.
8379 Used when linking with a foreign language main program compiled with an
8380 HP compiler.
8381
8382 @item /STATIC
8383 Prefer linking with object libraries over sharable images, even without
8384 /DEBUG.
8385 @end ifset
8386
8387 @end table
8388
8389 @node The GNAT Make Program gnatmake
8390 @chapter The GNAT Make Program @command{gnatmake}
8391 @findex gnatmake
8392
8393 @menu
8394 * Running gnatmake::
8395 * Switches for gnatmake::
8396 * Mode Switches for gnatmake::
8397 * Notes on the Command Line::
8398 * How gnatmake Works::
8399 * Examples of gnatmake Usage::
8400 @end menu
8401 @noindent
8402 A typical development cycle when working on an Ada program consists of
8403 the following steps:
8404
8405 @enumerate
8406 @item
8407 Edit some sources to fix bugs.
8408
8409 @item
8410 Add enhancements.
8411
8412 @item
8413 Compile all sources affected.
8414
8415 @item
8416 Rebind and relink.
8417
8418 @item
8419 Test.
8420 @end enumerate
8421
8422 @noindent
8423 The third step can be tricky, because not only do the modified files
8424 @cindex Dependency rules
8425 have to be compiled, but any files depending on these files must also be
8426 recompiled. The dependency rules in Ada can be quite complex, especially
8427 in the presence of overloading, @code{use} clauses, generics and inlined
8428 subprograms.
8429
8430 @command{gnatmake} automatically takes care of the third and fourth steps
8431 of this process. It determines which sources need to be compiled,
8432 compiles them, and binds and links the resulting object files.
8433
8434 Unlike some other Ada make programs, the dependencies are always
8435 accurately recomputed from the new sources. The source based approach of
8436 the GNAT compilation model makes this possible. This means that if
8437 changes to the source program cause corresponding changes in
8438 dependencies, they will always be tracked exactly correctly by
8439 @command{gnatmake}.
8440
8441 @node Running gnatmake
8442 @section Running @command{gnatmake}
8443
8444 @noindent
8445 The usual form of the @command{gnatmake} command is
8446
8447 @smallexample
8448 $ gnatmake [@var{switches}] @var{file_name}
8449       [@var{file_names}] [@var{mode_switches}]
8450 @end smallexample
8451
8452 @noindent
8453 The only required argument is one @var{file_name}, which specifies
8454 a compilation unit that is a main program. Several @var{file_names} can be
8455 specified: this will result in several executables being built.
8456 If @code{switches} are present, they can be placed before the first
8457 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8458 If @var{mode_switches} are present, they must always be placed after
8459 the last @var{file_name} and all @code{switches}.
8460
8461 If you are using standard file extensions (.adb and .ads), then the
8462 extension may be omitted from the @var{file_name} arguments. However, if
8463 you are using non-standard extensions, then it is required that the
8464 extension be given. A relative or absolute directory path can be
8465 specified in a @var{file_name}, in which case, the input source file will
8466 be searched for in the specified directory only. Otherwise, the input
8467 source file will first be searched in the directory where
8468 @command{gnatmake} was invoked and if it is not found, it will be search on
8469 the source path of the compiler as described in
8470 @ref{Search Paths and the Run-Time Library (RTL)}.
8471
8472 All @command{gnatmake} output (except when you specify
8473 @option{^-M^/DEPENDENCIES_LIST^}) is to
8474 @file{stderr}. The output produced by the
8475 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8476 @file{stdout}.
8477
8478 @node Switches for gnatmake
8479 @section Switches for @command{gnatmake}
8480
8481 @noindent
8482 You may specify any of the following switches to @command{gnatmake}:
8483
8484 @table @option
8485 @c !sort!
8486 @ifclear vms
8487 @item --GCC=@var{compiler_name}
8488 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8489 Program used for compiling. The default is `@command{gcc}'. You need to use
8490 quotes around @var{compiler_name} if @code{compiler_name} contains
8491 spaces or other separator characters. As an example @option{--GCC="foo -x
8492 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8493 compiler. A limitation of this syntax is that the name and path name of
8494 the executable itself must not include any embedded spaces. Note that
8495 switch @option{-c} is always inserted after your command name. Thus in the
8496 above example the compiler command that will be used by @command{gnatmake}
8497 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
8498 used, only the last @var{compiler_name} is taken into account. However,
8499 all the additional switches are also taken into account. Thus,
8500 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8501 @option{--GCC="bar -x -y -z -t"}.
8502
8503 @item --GNATBIND=@var{binder_name}
8504 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8505 Program used for binding. The default is `@code{gnatbind}'. You need to
8506 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8507 or other separator characters. As an example @option{--GNATBIND="bar -x
8508 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8509 binder. Binder switches that are normally appended by @command{gnatmake}
8510 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8511 A limitation of this syntax is that the name and path name of the executable
8512 itself must not include any embedded spaces.
8513
8514 @item --GNATLINK=@var{linker_name}
8515 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8516 Program used for linking. The default is `@command{gnatlink}'. You need to
8517 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8518 or other separator characters. As an example @option{--GNATLINK="lan -x
8519 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8520 linker. Linker switches that are normally appended by @command{gnatmake} to
8521 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8522 A limitation of this syntax is that the name and path name of the executable
8523 itself must not include any embedded spaces.
8524
8525 @end ifclear
8526
8527 @item ^-a^/ALL_FILES^
8528 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8529 Consider all files in the make process, even the GNAT internal system
8530 files (for example, the predefined Ada library files), as well as any
8531 locked files. Locked files are files whose ALI file is write-protected.
8532 By default,
8533 @command{gnatmake} does not check these files,
8534 because the assumption is that the GNAT internal files are properly up
8535 to date, and also that any write protected ALI files have been properly
8536 installed. Note that if there is an installation problem, such that one
8537 of these files is not up to date, it will be properly caught by the
8538 binder.
8539 You may have to specify this switch if you are working on GNAT
8540 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8541 in conjunction with @option{^-f^/FORCE_COMPILE^}
8542 if you need to recompile an entire application,
8543 including run-time files, using special configuration pragmas,
8544 such as a @code{Normalize_Scalars} pragma.
8545
8546 By default
8547 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8548 internal files with
8549 @ifclear vms
8550 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8551 @end ifclear
8552 @ifset vms
8553 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8554 @end ifset
8555
8556 @item ^-b^/ACTIONS=BIND^
8557 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8558 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8559 compilation and binding, but no link.
8560 Can be combined with @option{^-l^/ACTIONS=LINK^}
8561 to do binding and linking. When not combined with
8562 @option{^-c^/ACTIONS=COMPILE^}
8563 all the units in the closure of the main program must have been previously
8564 compiled and must be up to date. The root unit specified by @var{file_name}
8565 may be given without extension, with the source extension or, if no GNAT
8566 Project File is specified, with the ALI file extension.
8567
8568 @item ^-c^/ACTIONS=COMPILE^
8569 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8570 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8571 is also specified. Do not perform linking, except if both
8572 @option{^-b^/ACTIONS=BIND^} and
8573  @option{^-l^/ACTIONS=LINK^} are also specified.
8574 If the root unit specified by @var{file_name} is not a main unit, this is the
8575 default. Otherwise @command{gnatmake} will attempt binding and linking
8576 unless all objects are up to date and the executable is more recent than
8577 the objects.
8578
8579 @item ^-C^/MAPPING^
8580 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8581 Use a temporary mapping file. A mapping file is a way to communicate to the
8582 compiler two mappings: from unit names to file names (without any directory
8583 information) and from file names to path names (with full directory
8584 information). These mappings are used by the compiler to short-circuit the path
8585 search. When @command{gnatmake} is invoked with this switch, it will create
8586 a temporary mapping file, initially populated by the project manager,
8587 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8588 Each invocation of the compiler will add the newly accessed sources to the
8589 mapping file. This will improve the source search during the next invocation
8590 of the compiler.
8591
8592 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8593 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8594 Use a specific mapping file. The file, specified as a path name (absolute or
8595 relative) by this switch, should already exist, otherwise the switch is
8596 ineffective. The specified mapping file will be communicated to the compiler.
8597 This switch is not compatible with a project file
8598 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8599 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8600
8601 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8602 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8603 Put all object files and ALI file in directory @var{dir}.
8604 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8605 and ALI files go in the current working directory.
8606
8607 This switch cannot be used when using a project file.
8608
8609 @ifclear vms
8610 @item -eL
8611 @cindex @option{-eL} (@command{gnatmake})
8612 Follow all symbolic links when processing project files.
8613 @end ifclear
8614
8615 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
8616 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
8617 Output the commands for the compiler, the binder and the linker
8618 on ^standard output^SYS$OUTPUT^,
8619 instead of ^standard error^SYS$ERROR^.
8620
8621 @item ^-f^/FORCE_COMPILE^
8622 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
8623 Force recompilations. Recompile all sources, even though some object
8624 files may be up to date, but don't recompile predefined or GNAT internal
8625 files or locked files (files with a write-protected ALI file),
8626 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8627
8628 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8629 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
8630 When using project files, if some errors or warnings are detected during
8631 parsing and verbose mode is not in effect (no use of switch
8632 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8633 file, rather than its simple file name.
8634
8635 @item ^-g^/DEBUG^
8636 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
8637 Enable debugging. This switch is simply passed to the compiler and to the
8638 linker.
8639
8640 @item ^-i^/IN_PLACE^
8641 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
8642 In normal mode, @command{gnatmake} compiles all object files and ALI files
8643 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8644 then instead object files and ALI files that already exist are overwritten
8645 in place. This means that once a large project is organized into separate
8646 directories in the desired manner, then @command{gnatmake} will automatically
8647 maintain and update this organization. If no ALI files are found on the
8648 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8649 the new object and ALI files are created in the
8650 directory containing the source being compiled. If another organization
8651 is desired, where objects and sources are kept in different directories,
8652 a useful technique is to create dummy ALI files in the desired directories.
8653 When detecting such a dummy file, @command{gnatmake} will be forced to
8654 recompile the corresponding source file, and it will be put the resulting
8655 object and ALI files in the directory where it found the dummy file.
8656
8657 @item ^-j^/PROCESSES=^@var{n}
8658 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
8659 @cindex Parallel make
8660 Use @var{n} processes to carry out the (re)compilations. On a
8661 multiprocessor machine compilations will occur in parallel. In the
8662 event of compilation errors, messages from various compilations might
8663 get interspersed (but @command{gnatmake} will give you the full ordered
8664 list of failing compiles at the end). If this is problematic, rerun
8665 the make process with n set to 1 to get a clean list of messages.
8666
8667 @item ^-k^/CONTINUE_ON_ERROR^
8668 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
8669 Keep going. Continue as much as possible after a compilation error. To
8670 ease the programmer's task in case of compilation errors, the list of
8671 sources for which the compile fails is given when @command{gnatmake}
8672 terminates.
8673
8674 If @command{gnatmake} is invoked with several @file{file_names} and with this
8675 switch, if there are compilation errors when building an executable,
8676 @command{gnatmake} will not attempt to build the following executables.
8677
8678 @item ^-l^/ACTIONS=LINK^
8679 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
8680 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8681 and linking. Linking will not be performed if combined with
8682 @option{^-c^/ACTIONS=COMPILE^}
8683 but not with @option{^-b^/ACTIONS=BIND^}.
8684 When not combined with @option{^-b^/ACTIONS=BIND^}
8685 all the units in the closure of the main program must have been previously
8686 compiled and must be up to date, and the main program needs to have been bound.
8687 The root unit specified by @var{file_name}
8688 may be given without extension, with the source extension or, if no GNAT
8689 Project File is specified, with the ALI file extension.
8690
8691 @item ^-m^/MINIMAL_RECOMPILATION^
8692 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
8693 Specify that the minimum necessary amount of recompilations
8694 be performed. In this mode @command{gnatmake} ignores time
8695 stamp differences when the only
8696 modifications to a source file consist in adding/removing comments,
8697 empty lines, spaces or tabs. This means that if you have changed the
8698 comments in a source file or have simply reformatted it, using this
8699 switch will tell gnatmake not to recompile files that depend on it
8700 (provided other sources on which these files depend have undergone no
8701 semantic modifications). Note that the debugging information may be
8702 out of date with respect to the sources if the @option{-m} switch causes
8703 a compilation to be switched, so the use of this switch represents a
8704 trade-off between compilation time and accurate debugging information.
8705
8706 @item ^-M^/DEPENDENCIES_LIST^
8707 @cindex Dependencies, producing list
8708 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
8709 Check if all objects are up to date. If they are, output the object
8710 dependences to @file{stdout} in a form that can be directly exploited in
8711 a @file{Makefile}. By default, each source file is prefixed with its
8712 (relative or absolute) directory name. This name is whatever you
8713 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8714 and @option{^-I^/SEARCH^} switches. If you use
8715 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8716 @option{^-q^/QUIET^}
8717 (see below), only the source file names,
8718 without relative paths, are output. If you just specify the
8719 @option{^-M^/DEPENDENCIES_LIST^}
8720 switch, dependencies of the GNAT internal system files are omitted. This
8721 is typically what you want. If you also specify
8722 the @option{^-a^/ALL_FILES^} switch,
8723 dependencies of the GNAT internal files are also listed. Note that
8724 dependencies of the objects in external Ada libraries (see switch
8725 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8726 are never reported.
8727
8728 @item ^-n^/DO_OBJECT_CHECK^
8729 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
8730 Don't compile, bind, or link. Checks if all objects are up to date.
8731 If they are not, the full name of the first file that needs to be
8732 recompiled is printed.
8733 Repeated use of this option, followed by compiling the indicated source
8734 file, will eventually result in recompiling all required units.
8735
8736 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8737 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
8738 Output executable name. The name of the final executable program will be
8739 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8740 name for the executable will be the name of the input file in appropriate form
8741 for an executable file on the host system.
8742
8743 This switch cannot be used when invoking @command{gnatmake} with several
8744 @file{file_names}.
8745
8746 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
8747 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
8748 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
8749 automatically missing object directories, library directories and exec
8750 directories.
8751
8752 @item ^-P^/PROJECT_FILE=^@var{project}
8753 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
8754 Use project file @var{project}. Only one such switch can be used.
8755 @xref{gnatmake and Project Files}.
8756
8757 @item ^-q^/QUIET^
8758 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
8759 Quiet. When this flag is not set, the commands carried out by
8760 @command{gnatmake} are displayed.
8761
8762 @item ^-s^/SWITCH_CHECK/^
8763 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
8764 Recompile if compiler switches have changed since last compilation.
8765 All compiler switches but -I and -o are taken into account in the
8766 following way:
8767 orders between different ``first letter'' switches are ignored, but
8768 orders between same switches are taken into account. For example,
8769 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8770 is equivalent to @option{-O -g}.
8771
8772 This switch is recommended when Integrated Preprocessing is used.
8773
8774 @item ^-u^/UNIQUE^
8775 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
8776 Unique. Recompile at most the main files. It implies -c. Combined with
8777 -f, it is equivalent to calling the compiler directly. Note that using
8778 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8779 (@pxref{Project Files and Main Subprograms}).
8780
8781 @item ^-U^/ALL_PROJECTS^
8782 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
8783 When used without a project file or with one or several mains on the command
8784 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8785 on the command line, all sources of all project files are checked and compiled
8786 if not up to date, and libraries are rebuilt, if necessary.
8787
8788 @item ^-v^/REASONS^
8789 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
8790 Verbose. Display the reason for all recompilations @command{gnatmake}
8791 decides are necessary, with the highest verbosity level.
8792
8793 @item ^-vl^/LOW_VERBOSITY^
8794 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
8795 Verbosity level Low. Display fewer lines than in verbosity Medium.
8796
8797 @item ^-vm^/MEDIUM_VERBOSITY^
8798 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
8799 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
8800
8801 @item ^-vh^/HIGH_VERBOSITY^
8802 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
8803 Verbosity level High. Equivalent to ^-v^/REASONS^.
8804
8805 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8806 Indicate the verbosity of the parsing of GNAT project files.
8807 @xref{Switches Related to Project Files}.
8808
8809 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8810 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
8811 Indicate that sources that are not part of any Project File may be compiled.
8812 Normally, when using Project Files, only sources that are part of a Project
8813 File may be compile. When this switch is used, a source outside of all Project
8814 Files may be compiled. The ALI file and the object file will be put in the
8815 object directory of the main Project. The compilation switches used will only
8816 be those specified on the command line.
8817
8818 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8819 Indicate that external variable @var{name} has the value @var{value}.
8820 The Project Manager will use this value for occurrences of
8821 @code{external(name)} when parsing the project file.
8822 @xref{Switches Related to Project Files}.
8823
8824 @item ^-z^/NOMAIN^
8825 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
8826 No main subprogram. Bind and link the program even if the unit name
8827 given on the command line is a package name. The resulting executable
8828 will execute the elaboration routines of the package and its closure,
8829 then the finalization routines.
8830
8831 @end table
8832
8833 @table @asis
8834 @item @command{gcc} @asis{switches}
8835 @ifclear vms
8836 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
8837 is passed to @command{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8838 @end ifclear
8839 @ifset vms
8840 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8841 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8842 automatically treated as a compiler switch, and passed on to all
8843 compilations that are carried out.
8844 @end ifset
8845 @end table
8846
8847 @noindent
8848 Source and library search path switches:
8849
8850 @table @option
8851 @c !sort!
8852 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8853 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
8854 When looking for source files also look in directory @var{dir}.
8855 The order in which source files search is undertaken is
8856 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8857
8858 @item ^-aL^/SKIP_MISSING=^@var{dir}
8859 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
8860 Consider @var{dir} as being an externally provided Ada library.
8861 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
8862 files have been located in directory @var{dir}. This allows you to have
8863 missing bodies for the units in @var{dir} and to ignore out of date bodies
8864 for the same units. You still need to specify
8865 the location of the specs for these units by using the switches
8866 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8867 or @option{^-I^/SEARCH=^@var{dir}}.
8868 Note: this switch is provided for compatibility with previous versions
8869 of @command{gnatmake}. The easier method of causing standard libraries
8870 to be excluded from consideration is to write-protect the corresponding
8871 ALI files.
8872
8873 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8874 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
8875 When searching for library and object files, look in directory
8876 @var{dir}. The order in which library files are searched is described in
8877 @ref{Search Paths for gnatbind}.
8878
8879 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8880 @cindex Search paths, for @command{gnatmake}
8881 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
8882 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8883 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8884
8885 @item ^-I^/SEARCH=^@var{dir}
8886 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
8887 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8888 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8889
8890 @item ^-I-^/NOCURRENT_DIRECTORY^
8891 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
8892 @cindex Source files, suppressing search
8893 Do not look for source files in the directory containing the source
8894 file named in the command line.
8895 Do not look for ALI or object files in the directory
8896 where @command{gnatmake} was invoked.
8897
8898 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8899 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
8900 @cindex Linker libraries
8901 Add directory @var{dir} to the list of directories in which the linker
8902 will search for libraries. This is equivalent to
8903 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8904 @ifclear vms
8905 Furthermore, under Windows, the sources pointed to by the libraries path
8906 set in the registry are not searched for.
8907 @end ifclear
8908
8909 @item -nostdinc
8910 @cindex @option{-nostdinc} (@command{gnatmake})
8911 Do not look for source files in the system default directory.
8912
8913 @item -nostdlib
8914 @cindex @option{-nostdlib} (@command{gnatmake})
8915 Do not look for library files in the system default directory.
8916
8917 @item --RTS=@var{rts-path}
8918 @cindex @option{--RTS} (@command{gnatmake})
8919 Specifies the default location of the runtime library. GNAT looks for the
8920 runtime
8921 in the following directories, and stops as soon as a valid runtime is found
8922 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8923 @file{ada_object_path} present):
8924
8925 @itemize @bullet
8926 @item <current directory>/$rts_path
8927
8928 @item <default-search-dir>/$rts_path
8929
8930 @item <default-search-dir>/rts-$rts_path
8931 @end itemize
8932
8933 @noindent
8934 The selected path is handled like a normal RTS path.
8935
8936 @end table
8937
8938 @node Mode Switches for gnatmake
8939 @section Mode Switches for @command{gnatmake}
8940
8941 @noindent
8942 The mode switches (referred to as @code{mode_switches}) allow the
8943 inclusion of switches that are to be passed to the compiler itself, the
8944 binder or the linker. The effect of a mode switch is to cause all
8945 subsequent switches up to the end of the switch list, or up to the next
8946 mode switch, to be interpreted as switches to be passed on to the
8947 designated component of GNAT.
8948
8949 @table @option
8950 @c !sort!
8951 @item -cargs @var{switches}
8952 @cindex @option{-cargs} (@command{gnatmake})
8953 Compiler switches. Here @var{switches} is a list of switches
8954 that are valid switches for @command{gcc}. They will be passed on to
8955 all compile steps performed by @command{gnatmake}.
8956
8957 @item -bargs @var{switches}
8958 @cindex @option{-bargs} (@command{gnatmake})
8959 Binder switches. Here @var{switches} is a list of switches
8960 that are valid switches for @code{gnatbind}. They will be passed on to
8961 all bind steps performed by @command{gnatmake}.
8962
8963 @item -largs @var{switches}
8964 @cindex @option{-largs} (@command{gnatmake})
8965 Linker switches. Here @var{switches} is a list of switches
8966 that are valid switches for @command{gnatlink}. They will be passed on to
8967 all link steps performed by @command{gnatmake}.
8968
8969 @item -margs @var{switches}
8970 @cindex @option{-margs} (@command{gnatmake})
8971 Make switches. The switches are directly interpreted by @command{gnatmake},
8972 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8973 or @option{-largs}.
8974 @end table
8975
8976 @node Notes on the Command Line
8977 @section Notes on the Command Line
8978
8979 @noindent
8980 This section contains some additional useful notes on the operation
8981 of the @command{gnatmake} command.
8982
8983 @itemize @bullet
8984 @item
8985 @cindex Recompilation, by @command{gnatmake}
8986 If @command{gnatmake} finds no ALI files, it recompiles the main program
8987 and all other units required by the main program.
8988 This means that @command{gnatmake}
8989 can be used for the initial compile, as well as during subsequent steps of
8990 the development cycle.
8991
8992 @item
8993 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8994 is a subunit or body of a generic unit, @command{gnatmake} recompiles
8995 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8996 warning.
8997
8998 @item
8999 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9000 is used to specify both source and
9001 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9002 instead if you just want to specify
9003 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9004 if you want to specify library paths
9005 only.
9006
9007 @item
9008 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9009 This may conveniently be used to exclude standard libraries from
9010 consideration and in particular it means that the use of the
9011 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9012 unless @option{^-a^/ALL_FILES^} is also specified.
9013
9014 @item
9015 @command{gnatmake} has been designed to make the use of Ada libraries
9016 particularly convenient. Assume you have an Ada library organized
9017 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9018 of your Ada compilation units,
9019 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9020 specs of these units, but no bodies. Then to compile a unit
9021 stored in @code{main.adb}, which uses this Ada library you would just type
9022
9023 @smallexample
9024 @ifclear vms
9025 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9026 @end ifclear
9027 @ifset vms
9028 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9029            /SKIP_MISSING=@i{[OBJ_DIR]} main
9030 @end ifset
9031 @end smallexample
9032
9033 @item
9034 Using @command{gnatmake} along with the
9035 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9036 switch provides a mechanism for avoiding unnecessary rcompilations. Using
9037 this switch,
9038 you can update the comments/format of your
9039 source files without having to recompile everything. Note, however, that
9040 adding or deleting lines in a source files may render its debugging
9041 info obsolete. If the file in question is a spec, the impact is rather
9042 limited, as that debugging info will only be useful during the
9043 elaboration phase of your program. For bodies the impact can be more
9044 significant. In all events, your debugger will warn you if a source file
9045 is more recent than the corresponding object, and alert you to the fact
9046 that the debugging information may be out of date.
9047 @end itemize
9048
9049 @node How gnatmake Works
9050 @section How @command{gnatmake} Works
9051
9052 @noindent
9053 Generally @command{gnatmake} automatically performs all necessary
9054 recompilations and you don't need to worry about how it works. However,
9055 it may be useful to have some basic understanding of the @command{gnatmake}
9056 approach and in particular to understand how it uses the results of
9057 previous compilations without incorrectly depending on them.
9058
9059 First a definition: an object file is considered @dfn{up to date} if the
9060 corresponding ALI file exists and if all the source files listed in the
9061 dependency section of this ALI file have time stamps matching those in
9062 the ALI file. This means that neither the source file itself nor any
9063 files that it depends on have been modified, and hence there is no need
9064 to recompile this file.
9065
9066 @command{gnatmake} works by first checking if the specified main unit is up
9067 to date. If so, no compilations are required for the main unit. If not,
9068 @command{gnatmake} compiles the main program to build a new ALI file that
9069 reflects the latest sources. Then the ALI file of the main unit is
9070 examined to find all the source files on which the main program depends,
9071 and @command{gnatmake} recursively applies the above procedure on all these
9072 files.
9073
9074 This process ensures that @command{gnatmake} only trusts the dependencies
9075 in an existing ALI file if they are known to be correct. Otherwise it
9076 always recompiles to determine a new, guaranteed accurate set of
9077 dependencies. As a result the program is compiled ``upside down'' from what may
9078 be more familiar as the required order of compilation in some other Ada
9079 systems. In particular, clients are compiled before the units on which
9080 they depend. The ability of GNAT to compile in any order is critical in
9081 allowing an order of compilation to be chosen that guarantees that
9082 @command{gnatmake} will recompute a correct set of new dependencies if
9083 necessary.
9084
9085 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9086 imported by several of the executables, it will be recompiled at most once.
9087
9088 Note: when using non-standard naming conventions
9089 (@pxref{Using Other File Names}), changing through a configuration pragmas
9090 file the version of a source and invoking @command{gnatmake} to recompile may
9091 have no effect, if the previous version of the source is still accessible
9092 by @command{gnatmake}. It may be necessary to use the switch
9093 ^-f^/FORCE_COMPILE^.
9094
9095 @node Examples of gnatmake Usage
9096 @section Examples of @command{gnatmake} Usage
9097
9098 @table @code
9099 @item gnatmake hello.adb
9100 Compile all files necessary to bind and link the main program
9101 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9102 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9103
9104 @item gnatmake main1 main2 main3
9105 Compile all files necessary to bind and link the main programs
9106 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9107 (containing unit @code{Main2}) and @file{main3.adb}
9108 (containing unit @code{Main3}) and bind and link the resulting object files
9109 to generate three executable files @file{^main1^MAIN1.EXE^},
9110 @file{^main2^MAIN2.EXE^}
9111 and @file{^main3^MAIN3.EXE^}.
9112
9113 @ifclear vms
9114 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9115 @end ifclear
9116
9117 @ifset vms
9118 @item gnatmake Main_Unit /QUIET
9119    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9120    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9121 @end ifset
9122 Compile all files necessary to bind and link the main program unit
9123 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9124 be done with optimization level 2 and the order of elaboration will be
9125 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9126 displaying commands it is executing.
9127 @end table
9128
9129 @c *************************
9130 @node Improving Performance
9131 @chapter Improving Performance
9132 @cindex Improving performance
9133
9134 @noindent
9135 This chapter presents several topics related to program performance.
9136 It first describes some of the tradeoffs that need to be considered
9137 and some of the techniques for making your program run faster.
9138 It then documents the @command{gnatelim} tool and unused subprogram/data
9139 elimination feature, which can reduce the size of program executables.
9140
9141 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9142 driver (see @ref{The GNAT Driver and Project Files}).
9143
9144 @ifnottex
9145 @menu
9146 * Performance Considerations::
9147 * Reducing Size of Ada Executables with gnatelim::
9148 * Reducing Size of Executables with unused subprogram/data elimination::
9149 @end menu
9150 @end ifnottex
9151
9152 @c *****************************
9153 @node Performance Considerations
9154 @section Performance Considerations
9155
9156 @noindent
9157 The GNAT system provides a number of options that allow a trade-off
9158 between
9159
9160 @itemize @bullet
9161 @item
9162 performance of the generated code
9163
9164 @item
9165 speed of compilation
9166
9167 @item
9168 minimization of dependences and recompilation
9169
9170 @item
9171 the degree of run-time checking.
9172 @end itemize
9173
9174 @noindent
9175 The defaults (if no options are selected) aim at improving the speed
9176 of compilation and minimizing dependences, at the expense of performance
9177 of the generated code:
9178
9179 @itemize @bullet
9180 @item
9181 no optimization
9182
9183 @item
9184 no inlining of subprogram calls
9185
9186 @item
9187 all run-time checks enabled except overflow and elaboration checks
9188 @end itemize
9189
9190 @noindent
9191 These options are suitable for most program development purposes. This
9192 chapter describes how you can modify these choices, and also provides
9193 some guidelines on debugging optimized code.
9194
9195 @menu
9196 * Controlling Run-Time Checks::
9197 * Use of Restrictions::
9198 * Optimization Levels::
9199 * Debugging Optimized Code::
9200 * Inlining of Subprograms::
9201 * Other Optimization Switches::
9202 * Optimization and Strict Aliasing::
9203
9204 @ifset vms
9205 * Coverage Analysis::
9206 @end ifset
9207 @end menu
9208
9209 @node Controlling Run-Time Checks
9210 @subsection Controlling Run-Time Checks
9211
9212 @noindent
9213 By default, GNAT generates all run-time checks, except arithmetic overflow
9214 checking for integer operations and checks for access before elaboration on
9215 subprogram calls. The latter are not required in default mode, because all
9216 necessary checking is done at compile time.
9217 @cindex @option{-gnatp} (@command{gcc})
9218 @cindex @option{-gnato} (@command{gcc})
9219 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9220 be modified. @xref{Run-Time Checks}.
9221
9222 Our experience is that the default is suitable for most development
9223 purposes.
9224
9225 We treat integer overflow specially because these
9226 are quite expensive and in our experience are not as important as other
9227 run-time checks in the development process. Note that division by zero
9228 is not considered an overflow check, and divide by zero checks are
9229 generated where required by default.
9230
9231 Elaboration checks are off by default, and also not needed by default, since
9232 GNAT uses a static elaboration analysis approach that avoids the need for
9233 run-time checking. This manual contains a full chapter discussing the issue
9234 of elaboration checks, and if the default is not satisfactory for your use,
9235 you should read this chapter.
9236
9237 For validity checks, the minimal checks required by the Ada Reference
9238 Manual (for case statements and assignments to array elements) are on
9239 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9240 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9241 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9242 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9243 are also suppressed entirely if @option{-gnatp} is used.
9244
9245 @cindex Overflow checks
9246 @cindex Checks, overflow
9247 @findex Suppress
9248 @findex Unsuppress
9249 @cindex pragma Suppress
9250 @cindex pragma Unsuppress
9251 Note that the setting of the switches controls the default setting of
9252 the checks. They may be modified using either @code{pragma Suppress} (to
9253 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9254 checks) in the program source.
9255
9256 @node Use of Restrictions
9257 @subsection Use of Restrictions
9258
9259 @noindent
9260 The use of pragma Restrictions allows you to control which features are
9261 permitted in your program. Apart from the obvious point that if you avoid
9262 relatively expensive features like finalization (enforceable by the use
9263 of pragma Restrictions (No_Finalization), the use of this pragma does not
9264 affect the generated code in most cases.
9265
9266 One notable exception to this rule is that the possibility of task abort
9267 results in some distributed overhead, particularly if finalization or
9268 exception handlers are used. The reason is that certain sections of code
9269 have to be marked as non-abortable.
9270
9271 If you use neither the @code{abort} statement, nor asynchronous transfer
9272 of control (@code{select .. then abort}), then this distributed overhead
9273 is removed, which may have a general positive effect in improving
9274 overall performance.  Especially code involving frequent use of tasking
9275 constructs and controlled types will show much improved performance.
9276 The relevant restrictions pragmas are
9277
9278 @smallexample @c ada
9279    pragma Restrictions (No_Abort_Statements);
9280    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9281 @end smallexample
9282
9283 @noindent
9284 It is recommended that these restriction pragmas be used if possible. Note
9285 that this also means that you can write code without worrying about the
9286 possibility of an immediate abort at any point.
9287
9288 @node Optimization Levels
9289 @subsection Optimization Levels
9290 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9291
9292 @noindent
9293 The default is optimization off. This results in the fastest compile
9294 times, but GNAT makes absolutely no attempt to optimize, and the
9295 generated programs are considerably larger and slower than when
9296 optimization is enabled. You can use the
9297 @ifclear vms
9298 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9299 @option{-O2}, @option{-O3}, and @option{-Os})
9300 @end ifclear
9301 @ifset vms
9302 @code{OPTIMIZE} qualifier
9303 @end ifset
9304 to @command{gcc} to control the optimization level:
9305
9306 @table @option
9307 @item ^-O0^/OPTIMIZE=NONE^
9308 No optimization (the default);
9309 generates unoptimized code but has
9310 the fastest compilation time.
9311
9312 Note that many other compilers do fairly extensive optimization
9313 even if "no optimization" is specified. When using gcc, it is
9314 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9315 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9316 really does mean no optimization at all. This difference between
9317 gcc and other compilers should be kept in mind when doing
9318 performance comparisons.
9319
9320 @item ^-O1^/OPTIMIZE=SOME^
9321 Moderate optimization;
9322 optimizes reasonably well but does not
9323 degrade compilation time significantly.
9324
9325 @item ^-O2^/OPTIMIZE=ALL^
9326 @ifset vms
9327 @itemx /OPTIMIZE=DEVELOPMENT
9328 @end ifset
9329 Full optimization;
9330 generates highly optimized code and has
9331 the slowest compilation time.
9332
9333 @item ^-O3^/OPTIMIZE=INLINING^
9334 Full optimization as in @option{-O2},
9335 and also attempts automatic inlining of small
9336 subprograms within a unit (@pxref{Inlining of Subprograms}).
9337
9338 @item ^-Os^/OPTIMIZE=SPACE^
9339 Optimize space usage of resulting program.
9340 @end table
9341
9342 @noindent
9343 Higher optimization levels perform more global transformations on the
9344 program and apply more expensive analysis algorithms in order to generate
9345 faster and more compact code. The price in compilation time, and the
9346 resulting improvement in execution time,
9347 both depend on the particular application and the hardware environment.
9348 You should experiment to find the best level for your application.
9349
9350 The @option{^-Os^/OPTIMIZE=SPACE^} switch is independent of the time
9351 optimizations, so you can specify both @option{^-Os^/OPTIMIZE=SPACE^}
9352 and a time optimization on the same compile command.
9353
9354 Since the precise set of optimizations done at each level will vary from
9355 release to release (and sometime from target to target), it is best to think
9356 of the optimization settings in general terms.
9357 The @cite{Using GNU GCC} manual contains details about
9358 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9359 individually enable or disable specific optimizations.
9360
9361 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9362 been tested extensively at all optimization levels. There are some bugs
9363 which appear only with optimization turned on, but there have also been
9364 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9365 level of optimization does not improve the reliability of the code
9366 generator, which in practice is highly reliable at all optimization
9367 levels.
9368
9369 Note regarding the use of @option{-O3}: The use of this optimization level
9370 is generally discouraged with GNAT, since it often results in larger
9371 executables which run more slowly. See further discussion of this point
9372 in @ref{Inlining of Subprograms}.
9373
9374 @node Debugging Optimized Code
9375 @subsection Debugging Optimized Code
9376 @cindex Debugging optimized code
9377 @cindex Optimization and debugging
9378
9379 @noindent
9380 Although it is possible to do a reasonable amount of debugging at
9381 @ifclear vms
9382 nonzero optimization levels,
9383 the higher the level the more likely that
9384 @end ifclear
9385 @ifset vms
9386 @option{/OPTIMIZE} settings other than @code{NONE},
9387 such settings will make it more likely that
9388 @end ifset
9389 source-level constructs will have been eliminated by optimization.
9390 For example, if a loop is strength-reduced, the loop
9391 control variable may be completely eliminated and thus cannot be
9392 displayed in the debugger.
9393 This can only happen at @option{-O2} or @option{-O3}.
9394 Explicit temporary variables that you code might be eliminated at
9395 ^level^setting^ @option{-O1} or higher.
9396
9397 The use of the @option{^-g^/DEBUG^} switch,
9398 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9399 which is needed for source-level debugging,
9400 affects the size of the program executable on disk,
9401 and indeed the debugging information can be quite large.
9402 However, it has no effect on the generated code (and thus does not
9403 degrade performance)
9404
9405 Since the compiler generates debugging tables for a compilation unit before
9406 it performs optimizations, the optimizing transformations may invalidate some
9407 of the debugging data.  You therefore need to anticipate certain
9408 anomalous situations that may arise while debugging optimized code.
9409 These are the most common cases:
9410
9411 @enumerate
9412 @item
9413 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
9414 commands show
9415 the PC bouncing back and forth in the code.  This may result from any of
9416 the following optimizations:
9417
9418 @itemize @bullet
9419 @item
9420 @i{Common subexpression elimination:} using a single instance of code for a
9421 quantity that the source computes several times.  As a result you
9422 may not be able to stop on what looks like a statement.
9423
9424 @item
9425 @i{Invariant code motion:} moving an expression that does not change within a
9426 loop, to the beginning of the loop.
9427
9428 @item
9429 @i{Instruction scheduling:} moving instructions so as to
9430 overlap loads and stores (typically) with other code, or in
9431 general to move computations of values closer to their uses. Often
9432 this causes you to pass an assignment statement without the assignment
9433 happening and then later bounce back to the statement when the
9434 value is actually needed.  Placing a breakpoint on a line of code
9435 and then stepping over it may, therefore, not always cause all the
9436 expected side-effects.
9437 @end itemize
9438
9439 @item
9440 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9441 two identical pieces of code are merged and the program counter suddenly
9442 jumps to a statement that is not supposed to be executed, simply because
9443 it (and the code following) translates to the same thing as the code
9444 that @emph{was} supposed to be executed.  This effect is typically seen in
9445 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9446 a @code{break} in a C @code{^switch^switch^} statement.
9447
9448 @item
9449 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9450 There are various reasons for this effect:
9451
9452 @itemize @bullet
9453 @item
9454 In a subprogram prologue, a parameter may not yet have been moved to its
9455 ``home''.
9456
9457 @item
9458 A variable may be dead, and its register re-used.  This is
9459 probably the most common cause.
9460
9461 @item
9462 As mentioned above, the assignment of a value to a variable may
9463 have been moved.
9464
9465 @item
9466 A variable may be eliminated entirely by value propagation or
9467 other means.  In this case, GCC may incorrectly generate debugging
9468 information for the variable
9469 @end itemize
9470
9471 @noindent
9472 In general, when an unexpected value appears for a local variable or parameter
9473 you should first ascertain if that value was actually computed by
9474 your program, as opposed to being incorrectly reported by the debugger.
9475 Record fields or
9476 array elements in an object designated by an access value
9477 are generally less of a problem, once you have ascertained that the access
9478 value is sensible.
9479 Typically, this means checking variables in the preceding code and in the
9480 calling subprogram to verify that the value observed is explainable from other
9481 values (one must apply the procedure recursively to those
9482 other values); or re-running the code and stopping a little earlier
9483 (perhaps before the call) and stepping to better see how the variable obtained
9484 the value in question; or continuing to step @emph{from} the point of the
9485 strange value to see if code motion had simply moved the variable's
9486 assignments later.
9487 @end enumerate
9488
9489 @noindent
9490 In light of such anomalies, a recommended technique is to use @option{-O0}
9491 early in the software development cycle, when extensive debugging capabilities
9492 are most needed, and then move to @option{-O1} and later @option{-O2} as
9493 the debugger becomes less critical.
9494 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9495 a release management issue.
9496 @ifclear vms
9497 Note that if you use @option{-g} you can then use the @command{strip} program
9498 on the resulting executable,
9499 which removes both debugging information and global symbols.
9500 @end ifclear
9501
9502 @node Inlining of Subprograms
9503 @subsection Inlining of Subprograms
9504
9505 @noindent
9506 A call to a subprogram in the current unit is inlined if all the
9507 following conditions are met:
9508
9509 @itemize @bullet
9510 @item
9511 The optimization level is at least @option{-O1}.
9512
9513 @item
9514 The called subprogram is suitable for inlining: It must be small enough
9515 and not contain nested subprograms or anything else that @command{gcc}
9516 cannot support in inlined subprograms.
9517
9518 @item
9519 The call occurs after the definition of the body of the subprogram.
9520
9521 @item
9522 @cindex pragma Inline
9523 @findex Inline
9524 Either @code{pragma Inline} applies to the subprogram or it is
9525 small and automatic inlining (optimization level @option{-O3}) is
9526 specified.
9527 @end itemize
9528
9529 @noindent
9530 Calls to subprograms in @code{with}'ed units are normally not inlined.
9531 To achieve actual inlining (that is, replacement of the call by the code
9532 in the body of the subprogram), the following conditions must all be true.
9533
9534 @itemize @bullet
9535 @item
9536 The optimization level is at least @option{-O1}.
9537
9538 @item
9539 The called subprogram is suitable for inlining: It must be small enough
9540 and not contain nested subprograms or anything else @command{gcc} cannot
9541 support in inlined subprograms.
9542
9543 @item
9544 The call appears in a body (not in a package spec).
9545
9546 @item
9547 There is a @code{pragma Inline} for the subprogram.
9548
9549 @item
9550 @cindex @option{-gnatn} (@command{gcc})
9551 The @option{^-gnatn^/INLINE^} switch
9552 is used in the @command{gcc} command line
9553 @end itemize
9554
9555 Even if all these conditions are met, it may not be possible for
9556 the compiler to inline the call, due to the length of the body,
9557 or features in the body that make it impossible for the compiler
9558 to do the inlining.
9559
9560 Note that specifying the @option{-gnatn} switch causes additional
9561 compilation dependencies. Consider the following:
9562
9563 @smallexample @c ada
9564 @cartouche
9565 package R is
9566    procedure Q;
9567    pragma Inline (Q);
9568 end R;
9569 package body R is
9570    ...
9571 end R;
9572
9573 with R;
9574 procedure Main is
9575 begin
9576    ...
9577    R.Q;
9578 end Main;
9579 @end cartouche
9580 @end smallexample
9581
9582 @noindent
9583 With the default behavior (no @option{-gnatn} switch specified), the
9584 compilation of the @code{Main} procedure depends only on its own source,
9585 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9586 means that editing the body of @code{R} does not require recompiling
9587 @code{Main}.
9588
9589 On the other hand, the call @code{R.Q} is not inlined under these
9590 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9591 is compiled, the call will be inlined if the body of @code{Q} is small
9592 enough, but now @code{Main} depends on the body of @code{R} in
9593 @file{r.adb} as well as on the spec. This means that if this body is edited,
9594 the main program must be recompiled. Note that this extra dependency
9595 occurs whether or not the call is in fact inlined by @command{gcc}.
9596
9597 The use of front end inlining with @option{-gnatN} generates similar
9598 additional dependencies.
9599
9600 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
9601 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9602 can be used to prevent
9603 all inlining. This switch overrides all other conditions and ensures
9604 that no inlining occurs. The extra dependences resulting from
9605 @option{-gnatn} will still be active, even if
9606 this switch is used to suppress the resulting inlining actions.
9607
9608 Note regarding the use of @option{-O3}: There is no difference in inlining
9609 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9610 pragma @code{Inline} assuming the use of @option{-gnatn}
9611 or @option{-gnatN} (the switches that activate inlining). If you have used
9612 pragma @code{Inline} in appropriate cases, then it is usually much better
9613 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9614 in this case only has the effect of inlining subprograms you did not
9615 think should be inlined. We often find that the use of @option{-O3} slows
9616 down code by performing excessive inlining, leading to increased instruction
9617 cache pressure from the increased code size. So the bottom line here is
9618 that you should not automatically assume that @option{-O3} is better than
9619 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9620 it actually improves performance.
9621
9622 @node Other Optimization Switches
9623 @subsection Other Optimization Switches
9624 @cindex Optimization Switches
9625
9626 Since @code{GNAT} uses the @code{gcc} back end, all the specialized
9627 @code{gcc} optimization switches are potentially usable. These switches
9628 have not been extensively tested with GNAT but can generally be expected
9629 to work. Examples of switches in this category are
9630 @option{-funroll-loops} and
9631 the various target-specific @option{-m} options (in particular, it has been
9632 observed that @option{-march=pentium4} can significantly improve performance
9633 on appropriate machines). For full details of these switches, see the
9634 @code{gcc} manual.
9635
9636 @node Optimization and Strict Aliasing
9637 @subsection Optimization and Strict Aliasing
9638 @cindex Aliasing
9639 @cindex Strict Aliasing
9640 @cindex No_Strict_Aliasing
9641
9642 @noindent
9643 The strong typing capabilities of Ada allow an optimizer to generate
9644 efficient code in situations where other languages would be forced to
9645 make worst case assumptions preventing such optimizations. Consider
9646 the following example:
9647
9648 @smallexample @c ada
9649 @cartouche
9650 procedure R is
9651    type Int1 is new Integer;
9652    type Int2 is new Integer;
9653    type Int1A is access Int1;
9654    type Int2A is access Int2;
9655    Int1V : Int1A;
9656    Int2V : Int2A;
9657    ...
9658
9659 begin
9660    ...
9661    for J in Data'Range loop
9662       if Data (J) = Int1V.all then
9663          Int2V.all := Int2V.all + 1;
9664       end if;
9665    end loop;
9666    ...
9667 end R;
9668 @end cartouche
9669 @end smallexample
9670
9671 @noindent
9672 In this example, since the variable @code{Int1V} can only access objects
9673 of type @code{Int1}, and @code{Int2V} can only access objects of type
9674 @code{Int2}, there is no possibility that the assignment to
9675 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9676 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9677 for all iterations of the loop and avoid the extra memory reference
9678 required to dereference it each time through the loop.
9679
9680 This kind of optimization, called strict aliasing analysis, is
9681 triggered by specifying an optimization level of @option{-O2} or
9682 higher and allows @code{GNAT} to generate more efficient code
9683 when access values are involved.
9684
9685 However, although this optimization is always correct in terms of
9686 the formal semantics of the Ada Reference Manual, difficulties can
9687 arise if features like @code{Unchecked_Conversion} are used to break
9688 the typing system. Consider the following complete program example:
9689
9690 @smallexample @c ada
9691 @cartouche
9692 package p1 is
9693    type int1 is new integer;
9694    type int2 is new integer;
9695    type a1 is access int1;
9696    type a2 is access int2;
9697 end p1;
9698
9699 with p1; use p1;
9700 package p2 is
9701    function to_a2 (Input : a1) return a2;
9702 end p2;
9703
9704 with Unchecked_Conversion;
9705 package body p2 is
9706    function to_a2 (Input : a1) return a2 is
9707       function to_a2u is
9708         new Unchecked_Conversion (a1, a2);
9709    begin
9710       return to_a2u (Input);
9711    end to_a2;
9712 end p2;
9713
9714 with p2; use p2;
9715 with p1; use p1;
9716 with Text_IO; use Text_IO;
9717 procedure m is
9718    v1 : a1 := new int1;
9719    v2 : a2 := to_a2 (v1);
9720 begin
9721    v1.all := 1;
9722    v2.all := 0;
9723    put_line (int1'image (v1.all));
9724 end;
9725 @end cartouche
9726 @end smallexample
9727
9728 @noindent
9729 This program prints out 0 in @code{-O0} or @code{-O1}
9730 mode, but it prints out 1 in @code{-O2} mode. That's
9731 because in strict aliasing mode, the compiler can and
9732 does assume that the assignment to @code{v2.all} could not
9733 affect the value of @code{v1.all}, since different types
9734 are involved.
9735
9736 This behavior is not a case of non-conformance with the standard, since
9737 the Ada RM specifies that an unchecked conversion where the resulting
9738 bit pattern is not a correct value of the target type can result in an
9739 abnormal value and attempting to reference an abnormal value makes the
9740 execution of a program erroneous.  That's the case here since the result
9741 does not point to an object of type @code{int2}.  This means that the
9742 effect is entirely unpredictable.
9743
9744 However, although that explanation may satisfy a language
9745 lawyer, in practice an applications programmer expects an
9746 unchecked conversion involving pointers to create true
9747 aliases and the behavior of printing 1 seems plain wrong.
9748 In this case, the strict aliasing optimization is unwelcome.
9749
9750 Indeed the compiler recognizes this possibility, and the
9751 unchecked conversion generates a warning:
9752
9753 @smallexample
9754 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9755 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9756 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9757 @end smallexample
9758
9759 @noindent
9760 Unfortunately the problem is recognized when compiling the body of
9761 package @code{p2}, but the actual "bad" code is generated while
9762 compiling the body of @code{m} and this latter compilation does not see
9763 the suspicious @code{Unchecked_Conversion}.
9764
9765 As implied by the warning message, there are approaches you can use to
9766 avoid the unwanted strict aliasing optimization in a case like this.
9767
9768 One possibility is to simply avoid the use of @code{-O2}, but
9769 that is a bit drastic, since it throws away a number of useful
9770 optimizations that do not involve strict aliasing assumptions.
9771
9772 A less drastic approach is to compile the program using the
9773 option @code{-fno-strict-aliasing}. Actually it is only the
9774 unit containing the dereferencing of the suspicious pointer
9775 that needs to be compiled. So in this case, if we compile
9776 unit @code{m} with this switch, then we get the expected
9777 value of zero printed. Analyzing which units might need
9778 the switch can be painful, so a more reasonable approach
9779 is to compile the entire program with options @code{-O2}
9780 and @code{-fno-strict-aliasing}. If the performance is
9781 satisfactory with this combination of options, then the
9782 advantage is that the entire issue of possible "wrong"
9783 optimization due to strict aliasing is avoided.
9784
9785 To avoid the use of compiler switches, the configuration
9786 pragma @code{No_Strict_Aliasing} with no parameters may be
9787 used to specify that for all access types, the strict
9788 aliasing optimization should be suppressed.
9789
9790 However, these approaches are still overkill, in that they causes
9791 all manipulations of all access values to be deoptimized. A more
9792 refined approach is to concentrate attention on the specific
9793 access type identified as problematic.
9794
9795 First, if a careful analysis of uses of the pointer shows
9796 that there are no possible problematic references, then
9797 the warning can be suppressed by bracketing the
9798 instantiation of @code{Unchecked_Conversion} to turn
9799 the warning off:
9800
9801 @smallexample @c ada
9802    pragma Warnings (Off);
9803    function to_a2u is
9804      new Unchecked_Conversion (a1, a2);
9805    pragma Warnings (On);
9806 @end smallexample
9807
9808 @noindent
9809 Of course that approach is not appropriate for this particular
9810 example, since indeed there is a problematic reference. In this
9811 case we can take one of two other approaches.
9812
9813 The first possibility is to move the instantiation of unchecked
9814 conversion to the unit in which the type is declared. In
9815 this example, we would move the instantiation of
9816 @code{Unchecked_Conversion} from the body of package
9817 @code{p2} to the spec of package @code{p1}. Now the
9818 warning disappears. That's because any use of the
9819 access type knows there is a suspicious unchecked
9820 conversion, and the strict aliasing optimization
9821 is automatically suppressed for the type.
9822
9823 If it is not practical to move the unchecked conversion to the same unit
9824 in which the destination access type is declared (perhaps because the
9825 source type is not visible in that unit), you may use pragma
9826 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9827 same declarative sequence as the declaration of the access type:
9828
9829 @smallexample @c ada
9830    type a2 is access int2;
9831    pragma No_Strict_Aliasing (a2);
9832 @end smallexample
9833
9834 @noindent
9835 Here again, the compiler now knows that the strict aliasing optimization
9836 should be suppressed for any reference to type @code{a2} and the
9837 expected behavior is obtained.
9838
9839 Finally, note that although the compiler can generate warnings for
9840 simple cases of unchecked conversions, there are tricker and more
9841 indirect ways of creating type incorrect aliases which the compiler
9842 cannot detect. Examples are the use of address overlays and unchecked
9843 conversions involving composite types containing access types as
9844 components. In such cases, no warnings are generated, but there can
9845 still be aliasing problems. One safe coding practice is to forbid the
9846 use of address clauses for type overlaying, and to allow unchecked
9847 conversion only for primitive types. This is not really a significant
9848 restriction since any possible desired effect can be achieved by
9849 unchecked conversion of access values.
9850
9851 @ifset vms
9852 @node Coverage Analysis
9853 @subsection Coverage Analysis
9854
9855 @noindent
9856 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
9857 the user to determine the distribution of execution time across a program,
9858 @pxref{Profiling} for details of usage.
9859 @end ifset
9860
9861 @node Reducing Size of Ada Executables with gnatelim
9862 @section Reducing Size of Ada Executables with @code{gnatelim}
9863 @findex gnatelim
9864
9865 @noindent
9866 This section describes @command{gnatelim}, a tool which detects unused
9867 subprograms and helps the compiler to create a smaller executable for your
9868 program.
9869
9870 @menu
9871 * About gnatelim::
9872 * Running gnatelim::
9873 * Correcting the List of Eliminate Pragmas::
9874 * Making Your Executables Smaller::
9875 * Summary of the gnatelim Usage Cycle::
9876 @end menu
9877
9878 @node About gnatelim
9879 @subsection About @code{gnatelim}
9880
9881 @noindent
9882 When a program shares a set of Ada
9883 packages with other programs, it may happen that this program uses
9884 only a fraction of the subprograms defined in these packages. The code
9885 created for these unused subprograms increases the size of the executable.
9886
9887 @code{gnatelim} tracks unused subprograms in an Ada program and
9888 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9889 subprograms that are declared but never called. By placing the list of
9890 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9891 recompiling your program, you may decrease the size of its executable,
9892 because the compiler will not generate the code for 'eliminated' subprograms.
9893 See GNAT Reference Manual for more information about this pragma.
9894
9895 @code{gnatelim} needs as its input data the name of the main subprogram
9896 and a bind file for a main subprogram.
9897
9898 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9899 the main subprogram. @code{gnatelim} can work with both Ada and C
9900 bind files; when both are present, it uses the Ada bind file.
9901 The following commands will build the program and create the bind file:
9902
9903 @smallexample
9904 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9905 $ gnatbind main_prog
9906 @end smallexample
9907
9908 Note that @code{gnatelim} needs neither object nor ALI files.
9909
9910 @node Running gnatelim
9911 @subsection Running @code{gnatelim}
9912
9913 @noindent
9914 @code{gnatelim} has the following command-line interface:
9915
9916 @smallexample
9917 $ gnatelim [options] name
9918 @end smallexample
9919
9920 @noindent
9921 @code{name} should be a name of a source file that contains the main subprogram
9922 of a program (partition).
9923
9924 @code{gnatelim} has the following switches:
9925
9926 @table @option
9927 @c !sort!
9928 @item ^-q^/QUIET^
9929 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9930 Quiet mode: by default @code{gnatelim} outputs to the standard error
9931 stream the number of program units left to be processed. This option turns
9932 this trace off.
9933
9934 @item ^-v^/VERBOSE^
9935 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9936 Verbose mode: @code{gnatelim} version information is printed as Ada
9937 comments to the standard output stream. Also, in addition to the number of
9938 program units left @code{gnatelim} will output the name of the current unit
9939 being processed.
9940
9941 @item ^-a^/ALL^
9942 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9943 Also look for subprograms from the GNAT run time that can be eliminated. Note
9944 that when @file{gnat.adc} is produced using this switch, the entire program
9945 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
9946
9947 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9948 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9949 When looking for source files also look in directory @var{dir}. Specifying
9950 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9951 sources in the current directory.
9952
9953 @item ^-b^/BIND_FILE=^@var{bind_file}
9954 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9955 Specifies @var{bind_file} as the bind file to process. If not set, the name
9956 of the bind file is computed from the full expanded Ada name
9957 of a main subprogram.
9958
9959 @item ^-C^/CONFIG_FILE=^@var{config_file}
9960 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9961 Specifies a file @var{config_file} that contains configuration pragmas. The
9962 file must be specified with full path.
9963
9964 @item ^--GCC^/COMPILER^=@var{compiler_name}
9965 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9966 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
9967 available on the path.
9968
9969 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9970 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9971 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
9972 available on the path.
9973 @end table
9974
9975 @noindent
9976 @code{gnatelim} sends its output to the standard output stream, and all the
9977 tracing and debug information is sent to the standard error stream.
9978 In order to produce a proper GNAT configuration file
9979 @file{gnat.adc}, redirection must be used:
9980
9981 @smallexample
9982 @ifset vms
9983 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9984 @end ifset
9985 @ifclear vms
9986 $ gnatelim main_prog.adb > gnat.adc
9987 @end ifclear
9988 @end smallexample
9989
9990 @ifclear vms
9991 @noindent
9992 or
9993
9994 @smallexample
9995 $ gnatelim main_prog.adb >> gnat.adc
9996 @end smallexample
9997
9998 @noindent
9999 in order to append the @code{gnatelim} output to the existing contents of
10000 @file{gnat.adc}.
10001 @end ifclear
10002
10003 @node Correcting the List of Eliminate Pragmas
10004 @subsection Correcting the List of Eliminate Pragmas
10005
10006 @noindent
10007 In some rare cases @code{gnatelim} may try to eliminate
10008 subprograms that are actually called in the program. In this case, the
10009 compiler will generate an error message of the form:
10010
10011 @smallexample
10012 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10013 @end smallexample
10014
10015 @noindent
10016 You will need to manually remove the wrong @code{Eliminate} pragmas from
10017 the @file{gnat.adc} file. You should recompile your program
10018 from scratch after that, because you need a consistent @file{gnat.adc} file
10019 during the entire compilation.
10020
10021 @node Making Your Executables Smaller
10022 @subsection Making Your Executables Smaller
10023
10024 @noindent
10025 In order to get a smaller executable for your program you now have to
10026 recompile the program completely with the new @file{gnat.adc} file
10027 created by @code{gnatelim} in your current directory:
10028
10029 @smallexample
10030 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10031 @end smallexample
10032
10033 @noindent
10034 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10035 recompile everything
10036 with the set of pragmas @code{Eliminate} that you have obtained with
10037 @command{gnatelim}).
10038
10039 Be aware that the set of @code{Eliminate} pragmas is specific to each
10040 program. It is not recommended to merge sets of @code{Eliminate}
10041 pragmas created for different programs in one @file{gnat.adc} file.
10042
10043 @node Summary of the gnatelim Usage Cycle
10044 @subsection Summary of the gnatelim Usage Cycle
10045
10046 @noindent
10047 Here is a quick summary of the steps to be taken in order to reduce
10048 the size of your executables with @code{gnatelim}. You may use
10049 other GNAT options to control the optimization level,
10050 to produce the debugging information, to set search path, etc.
10051
10052 @enumerate
10053 @item
10054 Produce a bind file
10055
10056 @smallexample
10057 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10058 $ gnatbind main_prog
10059 @end smallexample
10060
10061 @item
10062 Generate a list of @code{Eliminate} pragmas
10063 @smallexample
10064 @ifset vms
10065 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10066 @end ifset
10067 @ifclear vms
10068 $ gnatelim main_prog >[>] gnat.adc
10069 @end ifclear
10070 @end smallexample
10071
10072 @item
10073 Recompile the application
10074
10075 @smallexample
10076 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10077 @end smallexample
10078
10079 @end enumerate
10080
10081 @node Reducing Size of Executables with unused subprogram/data elimination
10082 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10083 @findex unused subprogram/data elimination
10084
10085 @noindent
10086 This section describes how you can eliminate unused subprograms and data from
10087 your executable just by setting options at compilation time.
10088
10089 @menu
10090 * About unused subprogram/data elimination::
10091 * Compilation options::
10092 * Example of unused subprogram/data elimination::
10093 @end menu
10094
10095 @node About unused subprogram/data elimination
10096 @subsection About unused subprogram/data elimination
10097
10098 @noindent
10099 By default, an executable contains all code and data of its composing objects
10100 (directly linked or coming from statically linked libraries), even data or code
10101 never used by this executable.
10102
10103 This feature will allow you to eliminate such unused code from your
10104 executable, making it smaller (in disk and in memory).
10105
10106 This functionality is available on all platforms using elf binary format and
10107 having GNU binutils version 2.16.1.
10108
10109 @node Compilation options
10110 @subsection Compilation options
10111
10112 @noindent
10113 The operation of eliminating the unused code and data from the final executable
10114 is directly performed by the linker.
10115
10116 In order to do this, it has to work with objects compiled with the
10117 following options:
10118 @option{-ffunction-sections} @option{-fdata-sections}.
10119 @cindex @option{-ffunction-sections} (@command{gcc})
10120 @cindex @option{-fdata-sections} (@command{gcc})
10121 These options are usable with C and Ada files.
10122 They will place respectively each
10123 function or data in a separate section in the resulting object file.
10124
10125 Once the objects and static libraries are created with these options, the
10126 linker can perform the dead code elimination. You can do this by setting
10127 the @option{-Wl,--gc-sections} option to gcc command or in the
10128 @option{-largs} section of gnatmake. This will perform a garbage collection of
10129 code and data never referenced.
10130
10131 If the linker performs a partial link (@option{-r} ld linker option), then you
10132 will need to provide one or several entry point using the
10133 @option{-e} / @option{--entry} ld option.
10134
10135 Note that objects compiled without the @option{-ffunction-sections} and
10136 @option{-fdata-sections} options can still be linked with the executable.
10137 However, no dead code elimination will be performed on those objects (they will
10138 be linked as is).
10139
10140 The GNAT static library is now compiled with -ffunction-sections and
10141 -fdata-sections on some platforms. This allows you to eliminate the unused code
10142 and data of the GNAT library from your executable.
10143
10144 @node Example of unused subprogram/data elimination
10145 @subsection Example of unused subprogram/data elimination
10146
10147 @noindent
10148 Here is a simple example:
10149
10150 @smallexample @c ada
10151 with Aux;
10152
10153 procedure Test is
10154 begin
10155    Aux.Used (10);
10156 end Test;
10157
10158 package Aux is
10159    Used_Data   : Integer;
10160    Unused_Data : Integer;
10161
10162    procedure Used   (Data : Integer);
10163    procedure Unused (Data : Integer);
10164 end Aux;
10165
10166 package body Aux is
10167    procedure Used (Data : Integer) is
10168    begin
10169       Used_Data := Data;
10170    end Used;
10171
10172    procedure Unused (Data : Integer) is
10173    begin
10174       Unused_Data := Data;
10175    end Unused;
10176 end Aux;
10177 @end smallexample
10178
10179 @noindent
10180 @code{Unused} and @code{Unused_Data} are never referenced in this code
10181 excerpt, and hence they may be safely removed from the final executable.
10182
10183 @smallexample
10184 $ gnatmake test
10185
10186 $ nm test | grep used
10187 020015f0 T aux__unused
10188 02005d88 B aux__unused_data
10189 020015cc T aux__used
10190 02005d84 B aux__used_data
10191
10192 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10193      -largs -Wl,--gc-sections
10194
10195 $ nm test | grep used
10196 02005350 T aux__used
10197 0201ffe0 B aux__used_data
10198 @end smallexample
10199
10200 @noindent
10201 It can be observed that the procedure @code{Unused} and the object
10202 @code{Unused_Data} are removed by the linker when using the
10203 appropriate options.
10204
10205 @c ********************************
10206 @node Renaming Files Using gnatchop
10207 @chapter Renaming Files Using @code{gnatchop}
10208 @findex gnatchop
10209
10210 @noindent
10211 This chapter discusses how to handle files with multiple units by using
10212 the @code{gnatchop} utility. This utility is also useful in renaming
10213 files to meet the standard GNAT default file naming conventions.
10214
10215 @menu
10216 * Handling Files with Multiple Units::
10217 * Operating gnatchop in Compilation Mode::
10218 * Command Line for gnatchop::
10219 * Switches for gnatchop::
10220 * Examples of gnatchop Usage::
10221 @end menu
10222
10223 @node Handling Files with Multiple Units
10224 @section Handling Files with Multiple Units
10225
10226 @noindent
10227 The basic compilation model of GNAT requires that a file submitted to the
10228 compiler have only one unit and there be a strict correspondence
10229 between the file name and the unit name.
10230
10231 The @code{gnatchop} utility allows both of these rules to be relaxed,
10232 allowing GNAT to process files which contain multiple compilation units
10233 and files with arbitrary file names. @code{gnatchop}
10234 reads the specified file and generates one or more output files,
10235 containing one unit per file. The unit and the file name correspond,
10236 as required by GNAT.
10237
10238 If you want to permanently restructure a set of ``foreign'' files so that
10239 they match the GNAT rules, and do the remaining development using the
10240 GNAT structure, you can simply use @command{gnatchop} once, generate the
10241 new set of files and work with them from that point on.
10242
10243 Alternatively, if you want to keep your files in the ``foreign'' format,
10244 perhaps to maintain compatibility with some other Ada compilation
10245 system, you can set up a procedure where you use @command{gnatchop} each
10246 time you compile, regarding the source files that it writes as temporary
10247 files that you throw away.
10248
10249 @node Operating gnatchop in Compilation Mode
10250 @section Operating gnatchop in Compilation Mode
10251
10252 @noindent
10253 The basic function of @code{gnatchop} is to take a file with multiple units
10254 and split it into separate files. The boundary between files is reasonably
10255 clear, except for the issue of comments and pragmas. In default mode, the
10256 rule is that any pragmas between units belong to the previous unit, except
10257 that configuration pragmas always belong to the following unit. Any comments
10258 belong to the following unit. These rules
10259 almost always result in the right choice of
10260 the split point without needing to mark it explicitly and most users will
10261 find this default to be what they want. In this default mode it is incorrect to
10262 submit a file containing only configuration pragmas, or one that ends in
10263 configuration pragmas, to @code{gnatchop}.
10264
10265 However, using a special option to activate ``compilation mode'',
10266 @code{gnatchop}
10267 can perform another function, which is to provide exactly the semantics
10268 required by the RM for handling of configuration pragmas in a compilation.
10269 In the absence of configuration pragmas (at the main file level), this
10270 option has no effect, but it causes such configuration pragmas to be handled
10271 in a quite different manner.
10272
10273 First, in compilation mode, if @code{gnatchop} is given a file that consists of
10274 only configuration pragmas, then this file is appended to the
10275 @file{gnat.adc} file in the current directory. This behavior provides
10276 the required behavior described in the RM for the actions to be taken
10277 on submitting such a file to the compiler, namely that these pragmas
10278 should apply to all subsequent compilations in the same compilation
10279 environment. Using GNAT, the current directory, possibly containing a
10280 @file{gnat.adc} file is the representation
10281 of a compilation environment. For more information on the
10282 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
10283
10284 Second, in compilation mode, if @code{gnatchop}
10285 is given a file that starts with
10286 configuration pragmas, and contains one or more units, then these
10287 configuration pragmas are prepended to each of the chopped files. This
10288 behavior provides the required behavior described in the RM for the
10289 actions to be taken on compiling such a file, namely that the pragmas
10290 apply to all units in the compilation, but not to subsequently compiled
10291 units.
10292
10293 Finally, if configuration pragmas appear between units, they are appended
10294 to the previous unit. This results in the previous unit being illegal,
10295 since the compiler does not accept configuration pragmas that follow
10296 a unit. This provides the required RM behavior that forbids configuration
10297 pragmas other than those preceding the first compilation unit of a
10298 compilation.
10299
10300 For most purposes, @code{gnatchop} will be used in default mode. The
10301 compilation mode described above is used only if you need exactly
10302 accurate behavior with respect to compilations, and you have files
10303 that contain multiple units and configuration pragmas. In this
10304 circumstance the use of @code{gnatchop} with the compilation mode
10305 switch provides the required behavior, and is for example the mode
10306 in which GNAT processes the ACVC tests.
10307
10308 @node Command Line for gnatchop
10309 @section Command Line for @code{gnatchop}
10310
10311 @noindent
10312 The @code{gnatchop} command has the form:
10313
10314 @smallexample
10315 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
10316       [@var{directory}]
10317 @end smallexample
10318
10319 @noindent
10320 The only required argument is the file name of the file to be chopped.
10321 There are no restrictions on the form of this file name. The file itself
10322 contains one or more Ada units, in normal GNAT format, concatenated
10323 together. As shown, more than one file may be presented to be chopped.
10324
10325 When run in default mode, @code{gnatchop} generates one output file in
10326 the current directory for each unit in each of the files.
10327
10328 @var{directory}, if specified, gives the name of the directory to which
10329 the output files will be written. If it is not specified, all files are
10330 written to the current directory.
10331
10332 For example, given a
10333 file called @file{hellofiles} containing
10334
10335 @smallexample @c ada
10336 @group
10337 @cartouche
10338 procedure hello;
10339
10340 with Text_IO; use Text_IO;
10341 procedure hello is
10342 begin
10343    Put_Line ("Hello");
10344 end hello;
10345 @end cartouche
10346 @end group
10347 @end smallexample
10348
10349 @noindent
10350 the command
10351
10352 @smallexample
10353 $ gnatchop ^hellofiles^HELLOFILES.^
10354 @end smallexample
10355
10356 @noindent
10357 generates two files in the current directory, one called
10358 @file{hello.ads} containing the single line that is the procedure spec,
10359 and the other called @file{hello.adb} containing the remaining text. The
10360 original file is not affected. The generated files can be compiled in
10361 the normal manner.
10362
10363 @noindent
10364 When gnatchop is invoked on a file that is empty or that contains only empty
10365 lines and/or comments, gnatchop will not fail, but will not produce any
10366 new sources.
10367
10368 For example, given a
10369 file called @file{toto.txt} containing
10370
10371 @smallexample @c ada
10372 @group
10373 @cartouche
10374 --  Just a comment
10375 @end cartouche
10376 @end group
10377 @end smallexample
10378
10379 @noindent
10380 the command
10381
10382 @smallexample
10383 $ gnatchop ^toto.txt^TOT.TXT^
10384 @end smallexample
10385
10386 @noindent
10387 will not produce any new file and will result in the following warnings:
10388
10389 @smallexample
10390 toto.txt:1:01: warning: empty file, contains no compilation units
10391 no compilation units found
10392 no source files written
10393 @end smallexample
10394
10395 @node Switches for gnatchop
10396 @section Switches for @code{gnatchop}
10397
10398 @noindent
10399 @command{gnatchop} recognizes the following switches:
10400
10401 @table @option
10402 @c !sort!
10403
10404 @item ^-c^/COMPILATION^
10405 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
10406 Causes @code{gnatchop} to operate in compilation mode, in which
10407 configuration pragmas are handled according to strict RM rules. See
10408 previous section for a full description of this mode.
10409
10410 @ifclear vms
10411 @item -gnatxxx
10412 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
10413 used to parse the given file. Not all @code{xxx} options make sense,
10414 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
10415 process a source file that uses Latin-2 coding for identifiers.
10416 @end ifclear
10417
10418 @item ^-h^/HELP^
10419 Causes @code{gnatchop} to generate a brief help summary to the standard
10420 output file showing usage information.
10421
10422 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
10423 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
10424 Limit generated file names to the specified number @code{mm}
10425 of characters.
10426 This is useful if the
10427 resulting set of files is required to be interoperable with systems
10428 which limit the length of file names.
10429 @ifset vms
10430 If no value is given, or
10431 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
10432 a default of 39, suitable for OpenVMS Alpha
10433 Systems, is assumed
10434 @end ifset
10435 @ifclear vms
10436 No space is allowed between the @option{-k} and the numeric value. The numeric
10437 value may be omitted in which case a default of @option{-k8},
10438 suitable for use
10439 with DOS-like file systems, is used. If no @option{-k} switch
10440 is present then
10441 there is no limit on the length of file names.
10442 @end ifclear
10443
10444 @item ^-p^/PRESERVE^
10445 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
10446 Causes the file ^modification^creation^ time stamp of the input file to be
10447 preserved and used for the time stamp of the output file(s). This may be
10448 useful for preserving coherency of time stamps in an environment where
10449 @code{gnatchop} is used as part of a standard build process.
10450
10451 @item ^-q^/QUIET^
10452 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
10453 Causes output of informational messages indicating the set of generated
10454 files to be suppressed. Warnings and error messages are unaffected.
10455
10456 @item ^-r^/REFERENCE^
10457 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
10458 @findex Source_Reference
10459 Generate @code{Source_Reference} pragmas. Use this switch if the output
10460 files are regarded as temporary and development is to be done in terms
10461 of the original unchopped file. This switch causes
10462 @code{Source_Reference} pragmas to be inserted into each of the
10463 generated files to refers back to the original file name and line number.
10464 The result is that all error messages refer back to the original
10465 unchopped file.
10466 In addition, the debugging information placed into the object file (when
10467 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
10468 specified)
10469 also refers back to this original file so that tools like profilers and
10470 debuggers will give information in terms of the original unchopped file.
10471
10472 If the original file to be chopped itself contains
10473 a @code{Source_Reference}
10474 pragma referencing a third file, then gnatchop respects
10475 this pragma, and the generated @code{Source_Reference} pragmas
10476 in the chopped file refer to the original file, with appropriate
10477 line numbers. This is particularly useful when @code{gnatchop}
10478 is used in conjunction with @code{gnatprep} to compile files that
10479 contain preprocessing statements and multiple units.
10480
10481 @item ^-v^/VERBOSE^
10482 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
10483 Causes @code{gnatchop} to operate in verbose mode. The version
10484 number and copyright notice are output, as well as exact copies of
10485 the gnat1 commands spawned to obtain the chop control information.
10486
10487 @item ^-w^/OVERWRITE^
10488 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
10489 Overwrite existing file names. Normally @code{gnatchop} regards it as a
10490 fatal error if there is already a file with the same name as a
10491 file it would otherwise output, in other words if the files to be
10492 chopped contain duplicated units. This switch bypasses this
10493 check, and causes all but the last instance of such duplicated
10494 units to be skipped.
10495
10496 @ifclear vms
10497 @item --GCC=xxxx
10498 @cindex @option{--GCC=} (@code{gnatchop})
10499 Specify the path of the GNAT parser to be used. When this switch is used,
10500 no attempt is made to add the prefix to the GNAT parser executable.
10501 @end ifclear
10502 @end table
10503
10504 @node Examples of gnatchop Usage
10505 @section Examples of @code{gnatchop} Usage
10506
10507 @table @code
10508 @ifset vms
10509 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10510 @end ifset
10511 @ifclear vms
10512 @item gnatchop -w hello_s.ada prerelease/files
10513 @end ifclear
10514
10515 Chops the source file @file{hello_s.ada}. The output files will be
10516 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10517 overwriting any
10518 files with matching names in that directory (no files in the current
10519 directory are modified).
10520
10521 @item gnatchop ^archive^ARCHIVE.^
10522 Chops the source file @file{^archive^ARCHIVE.^}
10523 into the current directory. One
10524 useful application of @code{gnatchop} is in sending sets of sources
10525 around, for example in email messages. The required sources are simply
10526 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
10527 command), and then
10528 @command{gnatchop} is used at the other end to reconstitute the original
10529 file names.
10530
10531 @item gnatchop file1 file2 file3 direc
10532 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10533 the resulting files in the directory @file{direc}. Note that if any units
10534 occur more than once anywhere within this set of files, an error message
10535 is generated, and no files are written. To override this check, use the
10536 @option{^-w^/OVERWRITE^} switch,
10537 in which case the last occurrence in the last file will
10538 be the one that is output, and earlier duplicate occurrences for a given
10539 unit will be skipped.
10540 @end table
10541
10542 @node Configuration Pragmas
10543 @chapter Configuration Pragmas
10544 @cindex Configuration pragmas
10545 @cindex Pragmas, configuration
10546
10547 @noindent
10548 Configuration pragmas include those pragmas described as
10549 such in the Ada Reference Manual, as well as
10550 implementation-dependent pragmas that are configuration pragmas. See the
10551 individual descriptions of pragmas in the @cite{GNAT Reference Manual} for
10552 details on these additional GNAT-specific configuration pragmas. Most
10553 notably, the pragma @code{Source_File_Name}, which allows
10554 specifying non-default names for source files, is a configuration
10555 pragma. The following is a complete list of configuration pragmas
10556 recognized by GNAT:
10557
10558 @smallexample
10559    Ada_83
10560    Ada_95
10561    Ada_05
10562    C_Pass_By_Copy
10563    Component_Alignment
10564    Detect_Blocking
10565    Discard_Names
10566    Elaboration_Checks
10567    Eliminate
10568    Extend_System
10569    External_Name_Casing
10570    Float_Representation
10571    Initialize_Scalars
10572    Interrupt_State
10573    License
10574    Locking_Policy
10575    Long_Float
10576    Normalize_Scalars
10577    Persistent_BSS
10578    Polling
10579    Profile
10580    Profile_Warnings
10581    Propagate_Exceptions
10582    Queuing_Policy
10583    Ravenscar
10584    Restricted_Run_Time
10585    Restrictions
10586    Restrictions_Warnings
10587    Reviewable
10588    Source_File_Name
10589    Style_Checks
10590    Suppress
10591    Task_Dispatching_Policy
10592    Universal_Data
10593    Unsuppress
10594    Use_VADS_Size
10595    Warnings
10596    Validity_Checks
10597 @end smallexample
10598
10599 @menu
10600 * Handling of Configuration Pragmas::
10601 * The Configuration Pragmas Files::
10602 @end menu
10603
10604 @node Handling of Configuration Pragmas
10605 @section Handling of Configuration Pragmas
10606
10607 Configuration pragmas may either appear at the start of a compilation
10608 unit, in which case they apply only to that unit, or they may apply to
10609 all compilations performed in a given compilation environment.
10610
10611 GNAT also provides the @code{gnatchop} utility to provide an automatic
10612 way to handle configuration pragmas following the semantics for
10613 compilations (that is, files with multiple units), described in the RM.
10614 See @ref{Operating gnatchop in Compilation Mode} for details.
10615 However, for most purposes, it will be more convenient to edit the
10616 @file{gnat.adc} file that contains configuration pragmas directly,
10617 as described in the following section.
10618
10619 @node The Configuration Pragmas Files
10620 @section The Configuration Pragmas Files
10621 @cindex @file{gnat.adc}
10622
10623 @noindent
10624 In GNAT a compilation environment is defined by the current
10625 directory at the time that a compile command is given. This current
10626 directory is searched for a file whose name is @file{gnat.adc}. If
10627 this file is present, it is expected to contain one or more
10628 configuration pragmas that will be applied to the current compilation.
10629 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10630 considered.
10631
10632 Configuration pragmas may be entered into the @file{gnat.adc} file
10633 either by running @code{gnatchop} on a source file that consists only of
10634 configuration pragmas, or more conveniently  by
10635 direct editing of the @file{gnat.adc} file, which is a standard format
10636 source file.
10637
10638 In addition to @file{gnat.adc}, additional files containing configuration
10639 pragmas may be applied to the current compilation using the switch
10640 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10641 contains only configuration pragmas. These configuration pragmas are
10642 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10643 is present and switch @option{-gnatA} is not used).
10644
10645 It is allowed to specify several switches @option{-gnatec}, all of which
10646 will be taken into account.
10647
10648 If you are using project file, a separate mechanism is provided using
10649 project attributes, see @ref{Specifying Configuration Pragmas} for more
10650 details.
10651
10652 @ifset vms
10653 Of special interest to GNAT OpenVMS Alpha is the following
10654 configuration pragma:
10655
10656 @smallexample @c ada
10657 @cartouche
10658 pragma Extend_System (Aux_DEC);
10659 @end cartouche
10660 @end smallexample
10661
10662 @noindent
10663 In the presence of this pragma, GNAT adds to the definition of the
10664 predefined package SYSTEM all the additional types and subprograms that are
10665 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
10666 @end ifset
10667
10668 @node Handling Arbitrary File Naming Conventions Using gnatname
10669 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10670 @cindex Arbitrary File Naming Conventions
10671
10672 @menu
10673 * Arbitrary File Naming Conventions::
10674 * Running gnatname::
10675 * Switches for gnatname::
10676 * Examples of gnatname Usage::
10677 @end menu
10678
10679 @node Arbitrary File Naming Conventions
10680 @section Arbitrary File Naming Conventions
10681
10682 @noindent
10683 The GNAT compiler must be able to know the source file name of a compilation
10684 unit.  When using the standard GNAT default file naming conventions
10685 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10686 does not need additional information.
10687
10688 @noindent
10689 When the source file names do not follow the standard GNAT default file naming
10690 conventions, the GNAT compiler must be given additional information through
10691 a configuration pragmas file (@pxref{Configuration Pragmas})
10692 or a project file.
10693 When the non standard file naming conventions are well-defined,
10694 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10695 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
10696 if the file naming conventions are irregular or arbitrary, a number
10697 of pragma @code{Source_File_Name} for individual compilation units
10698 must be defined.
10699 To help maintain the correspondence between compilation unit names and
10700 source file names within the compiler,
10701 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10702 set of files.
10703
10704 @node Running gnatname
10705 @section Running @code{gnatname}
10706
10707 @noindent
10708 The usual form of the @code{gnatname} command is
10709
10710 @smallexample
10711 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10712 @end smallexample
10713
10714 @noindent
10715 All of the arguments are optional. If invoked without any argument,
10716 @code{gnatname} will display its usage.
10717
10718 @noindent
10719 When used with at least one naming pattern, @code{gnatname} will attempt to
10720 find all the compilation units in files that follow at least one of the
10721 naming patterns. To find these compilation units,
10722 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10723 regular files.
10724
10725 @noindent
10726 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10727 Each Naming Pattern is enclosed between double quotes.
10728 A Naming Pattern is a regular expression similar to the wildcard patterns
10729 used in file names by the Unix shells or the DOS prompt.
10730
10731 @noindent
10732 Examples of Naming Patterns are
10733
10734 @smallexample
10735    "*.[12].ada"
10736    "*.ad[sb]*"
10737    "body_*"    "spec_*"
10738 @end smallexample
10739
10740 @noindent
10741 For a more complete description of the syntax of Naming Patterns,
10742 see the second kind of regular expressions described in @file{g-regexp.ads}
10743 (the ``Glob'' regular expressions).
10744
10745 @noindent
10746 When invoked with no switches, @code{gnatname} will create a configuration
10747 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10748 @code{Source_File_Name} for each file that contains a valid Ada unit.
10749
10750 @node Switches for gnatname
10751 @section Switches for @code{gnatname}
10752
10753 @noindent
10754 Switches for @code{gnatname} must precede any specified Naming Pattern.
10755
10756 @noindent
10757 You may specify any of the following switches to @code{gnatname}:
10758
10759 @table @option
10760 @c !sort!
10761
10762 @item ^-c^/CONFIG_FILE=^@file{file}
10763 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10764 Create a configuration pragmas file @file{file} (instead of the default
10765 @file{gnat.adc}).
10766 @ifclear vms
10767 There may be zero, one or more space between @option{-c} and
10768 @file{file}.
10769 @end ifclear
10770 @file{file} may include directory information. @file{file} must be
10771 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10772 When a switch @option{^-c^/CONFIG_FILE^} is
10773 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10774
10775 @item ^-d^/SOURCE_DIRS=^@file{dir}
10776 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10777 Look for source files in directory @file{dir}. There may be zero, one or more
10778 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10779 When a switch @option{^-d^/SOURCE_DIRS^}
10780 is specified, the current working directory will not be searched for source
10781 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10782 or @option{^-D^/DIR_FILES^} switch.
10783 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10784 If @file{dir} is a relative path, it is relative to the directory of
10785 the configuration pragmas file specified with switch
10786 @option{^-c^/CONFIG_FILE^},
10787 or to the directory of the project file specified with switch
10788 @option{^-P^/PROJECT_FILE^} or,
10789 if neither switch @option{^-c^/CONFIG_FILE^}
10790 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10791 current working directory. The directory
10792 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10793
10794 @item ^-D^/DIRS_FILE=^@file{file}
10795 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10796 Look for source files in all directories listed in text file @file{file}.
10797 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10798 and @file{file}.
10799 @file{file} must be an existing, readable text file.
10800 Each non empty line in @file{file} must be a directory.
10801 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10802 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10803 @file{file}.
10804
10805 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10806 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10807 Foreign patterns. Using this switch, it is possible to add sources of languages
10808 other than Ada to the list of sources of a project file.
10809 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10810 For example,
10811 @smallexample
10812 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10813 @end smallexample
10814 @noindent
10815 will look for Ada units in all files with the @file{.ada} extension,
10816 and will add to the list of file for project @file{prj.gpr} the C files
10817 with extension ".^c^C^".
10818
10819 @item ^-h^/HELP^
10820 @cindex @option{^-h^/HELP^} (@code{gnatname})
10821 Output usage (help) information. The output is written to @file{stdout}.
10822
10823 @item ^-P^/PROJECT_FILE=^@file{proj}
10824 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10825 Create or update project file @file{proj}. There may be zero, one or more space
10826 between @option{-P} and @file{proj}. @file{proj} may include directory
10827 information. @file{proj} must be writable.
10828 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10829 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10830 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10831
10832 @item ^-v^/VERBOSE^
10833 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10834 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10835 This includes name of the file written, the name of the directories to search
10836 and, for each file in those directories whose name matches at least one of
10837 the Naming Patterns, an indication of whether the file contains a unit,
10838 and if so the name of the unit.
10839
10840 @item ^-v -v^/VERBOSE /VERBOSE^
10841 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10842 Very Verbose mode. In addition to the output produced in verbose mode,
10843 for each file in the searched directories whose name matches none of
10844 the Naming Patterns, an indication is given that there is no match.
10845
10846 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10847 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10848 Excluded patterns. Using this switch, it is possible to exclude some files
10849 that would match the name patterns. For example,
10850 @smallexample
10851 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10852 @end smallexample
10853 @noindent
10854 will look for Ada units in all files with the @file{.ada} extension,
10855 except those whose names end with @file{_nt.ada}.
10856
10857 @end table
10858
10859 @node Examples of gnatname Usage
10860 @section Examples of @code{gnatname} Usage
10861
10862 @ifset vms
10863 @smallexample
10864 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10865 @end smallexample
10866 @end ifset
10867
10868 @ifclear vms
10869 @smallexample
10870 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10871 @end smallexample
10872 @end ifclear
10873
10874 @noindent
10875 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10876 and be writable. In addition, the directory
10877 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10878 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10879
10880 @ifclear vms
10881 Note the optional spaces after @option{-c} and @option{-d}.
10882 @end ifclear
10883
10884 @smallexample
10885 @ifclear vms
10886 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10887   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10888 @end ifclear
10889 @ifset vms
10890 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
10891   /EXCLUDED_PATTERN=*_nt_body.ada
10892   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10893   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10894 @end ifset
10895 @end smallexample
10896
10897 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10898 even in conjunction with one or several switches
10899 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10900 are used in this example.
10901
10902 @c *****************************************
10903 @c * G N A T  P r o j e c t  M a n a g e r *
10904 @c *****************************************
10905 @node GNAT Project Manager
10906 @chapter GNAT Project Manager
10907
10908 @menu
10909 * Introduction::
10910 * Examples of Project Files::
10911 * Project File Syntax::
10912 * Objects and Sources in Project Files::
10913 * Importing Projects::
10914 * Project Extension::
10915 * Project Hierarchy Extension::
10916 * External References in Project Files::
10917 * Packages in Project Files::
10918 * Variables from Imported Projects::
10919 * Naming Schemes::
10920 * Library Projects::
10921 * Stand-alone Library Projects::
10922 * Switches Related to Project Files::
10923 * Tools Supporting Project Files::
10924 * An Extended Example::
10925 * Project File Complete Syntax::
10926 @end menu
10927
10928 @c ****************
10929 @c * Introduction *
10930 @c ****************
10931
10932 @node Introduction
10933 @section Introduction
10934
10935 @noindent
10936 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10937 you to manage complex builds involving a number of source files, directories,
10938 and compilation options for different system configurations. In particular,
10939 project files allow you to specify:
10940 @itemize @bullet
10941 @item
10942 The directory or set of directories containing the source files, and/or the
10943 names of the specific source files themselves
10944 @item
10945 The directory in which the compiler's output
10946 (@file{ALI} files, object files, tree files) is to be placed
10947 @item
10948 The directory in which the executable programs is to be placed
10949 @item
10950 ^Switch^Switch^ settings for any of the project-enabled tools
10951 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10952 @code{gnatfind}); you can apply these settings either globally or to individual
10953 compilation units.
10954 @item
10955 The source files containing the main subprogram(s) to be built
10956 @item
10957 The source programming language(s) (currently Ada and/or C)
10958 @item
10959 Source file naming conventions; you can specify these either globally or for
10960 individual compilation units
10961 @end itemize
10962
10963 @menu
10964 * Project Files::
10965 @end menu
10966
10967 @node Project Files
10968 @subsection Project Files
10969
10970 @noindent
10971 Project files are written in a syntax close to that of Ada, using  familiar
10972 notions such as packages, context clauses, declarations, default values,
10973 assignments, and inheritance. Finally, project files can be built
10974 hierarchically from other project files, simplifying complex system
10975 integration and project reuse.
10976
10977 A @dfn{project} is a specific set of values for various compilation properties.
10978 The settings for a given project are described by means of
10979 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10980 Property values in project files are either strings or lists of strings.
10981 Properties that are not explicitly set receive default values.  A project
10982 file may interrogate the values of @dfn{external variables} (user-defined
10983 command-line switches or environment variables), and it may specify property
10984 settings conditionally, based on the value of such variables.
10985
10986 In simple cases, a project's source files depend only on other source files
10987 in the same project, or on the predefined libraries.  (@emph{Dependence} is
10988 used in
10989 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10990 the Project Manager also allows more sophisticated arrangements,
10991 where the source files in one project depend on source files in other
10992 projects:
10993 @itemize @bullet
10994 @item
10995 One project can @emph{import} other projects containing needed source files.
10996 @item
10997 You can organize GNAT projects in a hierarchy: a @emph{child} project
10998 can extend a @emph{parent} project, inheriting the parent's source files and
10999 optionally overriding any of them with alternative versions
11000 @end itemize
11001
11002 @noindent
11003 More generally, the Project Manager lets you structure large development
11004 efforts into hierarchical subsystems, where build decisions are delegated
11005 to the subsystem level, and thus different compilation environments
11006 (^switch^switch^ settings) used for different subsystems.
11007
11008 The Project Manager is invoked through the
11009 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11010 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11011 @ifclear vms
11012 There may be zero, one or more spaces between @option{-P} and
11013 @option{@emph{projectfile}}.
11014 @end ifclear
11015 If you want to define (on the command line) an external variable that is
11016 queried by the project file, you must use the
11017 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11018 The Project Manager parses and interprets the project file, and drives the
11019 invoked tool based on the project settings.
11020
11021 The Project Manager supports a wide range of development strategies,
11022 for systems of all sizes.  Here are some typical practices that are
11023 easily handled:
11024 @itemize @bullet
11025 @item
11026 Using a common set of source files, but generating object files in different
11027 directories via different ^switch^switch^ settings
11028 @item
11029 Using a mostly-shared set of source files, but with different versions of
11030 some unit or units
11031 @end itemize
11032
11033 @noindent
11034 The destination of an executable can be controlled inside a project file
11035 using the @option{^-o^-o^}
11036 ^switch^switch^.
11037 In the absence of such a ^switch^switch^ either inside
11038 the project file or on the command line, any executable files generated by
11039 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11040 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11041 in the object directory of the project.
11042
11043 You can use project files to achieve some of the effects of a source
11044 versioning system (for example, defining separate projects for
11045 the different sets of sources that comprise different releases) but the
11046 Project Manager is independent of any source configuration management tools
11047 that might be used by the developers.
11048
11049 The next section introduces the main features of GNAT's project facility
11050 through a sequence of examples; subsequent sections will present the syntax
11051 and semantics in more detail. A more formal description of the project
11052 facility appears in the GNAT Reference Manual.
11053
11054 @c *****************************
11055 @c * Examples of Project Files *
11056 @c *****************************
11057
11058 @node Examples of Project Files
11059 @section Examples of Project Files
11060 @noindent
11061 This section illustrates some of the typical uses of project files and
11062 explains their basic structure and behavior.
11063
11064 @menu
11065 * Common Sources with Different ^Switches^Switches^ and Directories::
11066 * Using External Variables::
11067 * Importing Other Projects::
11068 * Extending a Project::
11069 @end menu
11070
11071 @node Common Sources with Different ^Switches^Switches^ and Directories
11072 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11073
11074 @menu
11075 * Source Files::
11076 * Specifying the Object Directory::
11077 * Specifying the Exec Directory::
11078 * Project File Packages::
11079 * Specifying ^Switch^Switch^ Settings::
11080 * Main Subprograms::
11081 * Executable File Names::
11082 * Source File Naming Conventions::
11083 * Source Language(s)::
11084 @end menu
11085
11086 @noindent
11087 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11088 @file{proc.adb} are in the @file{/common} directory.  The file
11089 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11090 package @code{Pack}.  We want to compile these source files under two sets
11091 of ^switches^switches^:
11092 @itemize @bullet
11093 @item
11094 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11095 and the @option{^-gnata^-gnata^},
11096 @option{^-gnato^-gnato^},
11097 and @option{^-gnatE^-gnatE^} switches to the
11098 compiler; the compiler's output is to appear in @file{/common/debug}
11099 @item
11100 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11101 to the compiler; the compiler's output is to appear in @file{/common/release}
11102 @end itemize
11103
11104 @noindent
11105 The GNAT project files shown below, respectively @file{debug.gpr} and
11106 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11107
11108 Schematically:
11109 @smallexample
11110 @group
11111 ^/common^[COMMON]^
11112   debug.gpr
11113   release.gpr
11114   pack.ads
11115   pack.adb
11116   proc.adb
11117 @end group
11118 @group
11119 ^/common/debug^[COMMON.DEBUG]^
11120   proc.ali, proc.o
11121   pack.ali, pack.o
11122 @end group
11123 @group
11124 ^/common/release^[COMMON.RELEASE]^
11125   proc.ali, proc.o
11126   pack.ali, pack.o
11127 @end group
11128 @end smallexample
11129 Here are the corresponding project files:
11130
11131 @smallexample @c projectfile
11132 @group
11133 project Debug is
11134   for Object_Dir use "debug";
11135   for Main use ("proc");
11136
11137   package Builder is
11138     for ^Default_Switches^Default_Switches^ ("Ada")
11139         use ("^-g^-g^");
11140     for Executable ("proc.adb") use "proc1";
11141   end Builder;
11142 @end group
11143
11144 @group
11145   package Compiler is
11146     for ^Default_Switches^Default_Switches^ ("Ada")
11147        use ("-fstack-check",
11148             "^-gnata^-gnata^",
11149             "^-gnato^-gnato^",
11150             "^-gnatE^-gnatE^");
11151   end Compiler;
11152 end Debug;
11153 @end group
11154 @end smallexample
11155
11156 @smallexample @c projectfile
11157 @group
11158 project Release is
11159   for Object_Dir use "release";
11160   for Exec_Dir use ".";
11161   for Main use ("proc");
11162
11163   package Compiler is
11164     for ^Default_Switches^Default_Switches^ ("Ada")
11165         use ("^-O2^-O2^");
11166   end Compiler;
11167 end Release;
11168 @end group
11169 @end smallexample
11170
11171 @noindent
11172 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11173 insensitive), and analogously the project defined by @file{release.gpr} is
11174 @code{"Release"}.  For consistency the file should have the same name as the
11175 project, and the project file's extension should be @code{"gpr"}. These
11176 conventions are not required, but a warning is issued if they are not followed.
11177
11178 If the current directory is @file{^/temp^[TEMP]^}, then the command
11179 @smallexample
11180 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11181 @end smallexample
11182
11183 @noindent
11184 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11185 as well as the @code{^proc1^PROC1.EXE^} executable,
11186 using the ^switch^switch^ settings defined in the project file.
11187
11188 Likewise, the command
11189 @smallexample
11190 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11191 @end smallexample
11192
11193 @noindent
11194 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11195 and the @code{^proc^PROC.EXE^}
11196 executable in @file{^/common^[COMMON]^},
11197 using the ^switch^switch^ settings from the project file.
11198
11199 @node Source Files
11200 @unnumberedsubsubsec Source Files
11201
11202 @noindent
11203 If a project file does not explicitly specify a set of source directories or
11204 a set of source files, then by default the project's source files are the
11205 Ada source files in the project file directory.  Thus @file{pack.ads},
11206 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11207
11208 @node Specifying the Object Directory
11209 @unnumberedsubsubsec Specifying the Object Directory
11210
11211 @noindent
11212 Several project properties are modeled by Ada-style @emph{attributes};
11213 a property is defined by supplying the equivalent of an Ada attribute
11214 definition clause in the project file.
11215 A project's object directory is another such a property; the corresponding
11216 attribute is @code{Object_Dir}, and its value is also a string expression,
11217 specified either as absolute or relative. In the later case,
11218 it is relative to the project file directory. Thus the compiler's
11219 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
11220 (for the @code{Debug} project)
11221 and to @file{^/common/release^[COMMON.RELEASE]^}
11222 (for the @code{Release} project).
11223 If @code{Object_Dir} is not specified, then the default is the project file
11224 directory itself.
11225
11226 @node Specifying the Exec Directory
11227 @unnumberedsubsubsec Specifying the Exec Directory
11228
11229 @noindent
11230 A project's exec directory is another property; the corresponding
11231 attribute is @code{Exec_Dir}, and its value is also a string expression,
11232 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
11233 then the default is the object directory (which may also be the project file
11234 directory if attribute @code{Object_Dir} is not specified). Thus the executable
11235 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
11236 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
11237 and in @file{^/common^[COMMON]^} for the @code{Release} project.
11238
11239 @node Project File Packages
11240 @unnumberedsubsubsec Project File Packages
11241
11242 @noindent
11243 A GNAT tool that is integrated with the Project Manager is modeled by a
11244 corresponding package in the project file. In the example above,
11245 The @code{Debug} project defines the packages @code{Builder}
11246 (for @command{gnatmake}) and @code{Compiler};
11247 the @code{Release} project defines only the @code{Compiler} package.
11248
11249 The Ada-like package syntax is not to be taken literally.  Although packages in
11250 project files bear a surface resemblance to packages in Ada source code, the
11251 notation is simply a way to convey a grouping of properties for a named
11252 entity.  Indeed, the package names permitted in project files are restricted
11253 to a predefined set, corresponding to the project-aware tools, and the contents
11254 of packages are limited to a small set of constructs.
11255 The packages in the example above contain attribute definitions.
11256
11257 @node Specifying ^Switch^Switch^ Settings
11258 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
11259
11260 @noindent
11261 ^Switch^Switch^ settings for a project-aware tool can be specified through
11262 attributes in the package that corresponds to the tool.
11263 The example above illustrates one of the relevant attributes,
11264 @code{^Default_Switches^Default_Switches^}, which is defined in packages
11265 in both project files.
11266 Unlike simple attributes like @code{Source_Dirs},
11267 @code{^Default_Switches^Default_Switches^} is
11268 known as an @emph{associative array}.  When you define this attribute, you must
11269 supply an ``index'' (a literal string), and the effect of the attribute
11270 definition is to set the value of the array at the specified index.
11271 For the @code{^Default_Switches^Default_Switches^} attribute,
11272 the index is a programming language (in our case, Ada),
11273 and the value specified (after @code{use}) must be a list
11274 of string expressions.
11275
11276 The attributes permitted in project files are restricted to a predefined set.
11277 Some may appear at project level, others in packages.
11278 For any attribute that is an associative array, the index must always be a
11279 literal string, but the restrictions on this string (e.g., a file name or a
11280 language name) depend on the individual attribute.
11281 Also depending on the attribute, its specified value will need to be either a
11282 string or a string list.
11283
11284 In the @code{Debug} project, we set the switches for two tools,
11285 @command{gnatmake} and the compiler, and thus we include the two corresponding
11286 packages; each package defines the @code{^Default_Switches^Default_Switches^}
11287 attribute with index @code{"Ada"}.
11288 Note that the package corresponding to
11289 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
11290 similar, but only includes the @code{Compiler} package.
11291
11292 In project @code{Debug} above, the ^switches^switches^ starting with
11293 @option{-gnat} that are specified in package @code{Compiler}
11294 could have been placed in package @code{Builder}, since @command{gnatmake}
11295 transmits all such ^switches^switches^ to the compiler.
11296
11297 @node Main Subprograms
11298 @unnumberedsubsubsec Main Subprograms
11299
11300 @noindent
11301 One of the specifiable properties of a project is a list of files that contain
11302 main subprograms.  This property is captured in the @code{Main} attribute,
11303 whose value is a list of strings.  If a project defines the @code{Main}
11304 attribute, it is not necessary to identify the main subprogram(s) when
11305 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
11306
11307 @node Executable File Names
11308 @unnumberedsubsubsec Executable File Names
11309
11310 @noindent
11311 By default, the executable file name corresponding to a main source is
11312 deduced from the main source file name. Through the attributes
11313 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
11314 it is possible to change this default.
11315 In project @code{Debug} above, the executable file name
11316 for main source @file{^proc.adb^PROC.ADB^} is
11317 @file{^proc1^PROC1.EXE^}.
11318 Attribute @code{Executable_Suffix}, when specified, may change the suffix
11319 of the executable files, when no attribute @code{Executable} applies:
11320 its value replace the platform-specific executable suffix.
11321 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
11322 specify a non default executable file name when several mains are built at once
11323 in a single @command{gnatmake} command.
11324
11325 @node Source File Naming Conventions
11326 @unnumberedsubsubsec Source File Naming Conventions
11327
11328 @noindent
11329 Since the project files above do not specify any source file naming
11330 conventions, the GNAT defaults are used.  The mechanism for defining source
11331 file naming conventions -- a package named @code{Naming} --
11332 is described below (@pxref{Naming Schemes}).
11333
11334 @node Source Language(s)
11335 @unnumberedsubsubsec Source Language(s)
11336
11337 @noindent
11338 Since the project files do not specify a @code{Languages} attribute, by
11339 default the GNAT tools assume that the language of the project file is Ada.
11340 More generally, a project can comprise source files
11341 in Ada, C, and/or other languages.
11342
11343 @node Using External Variables
11344 @subsection Using External Variables
11345
11346 @noindent
11347 Instead of supplying different project files for debug and release, we can
11348 define a single project file that queries an external variable (set either
11349 on the command line or via an ^environment variable^logical name^) in order to
11350 conditionally define the appropriate settings.  Again, assume that the
11351 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
11352 located in directory @file{^/common^[COMMON]^}.  The following project file,
11353 @file{build.gpr}, queries the external variable named @code{STYLE} and
11354 defines an object directory and ^switch^switch^ settings based on whether
11355 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
11356 the default is @code{"deb"}.
11357
11358 @smallexample @c projectfile
11359 @group
11360 project Build is
11361   for Main use ("proc");
11362
11363   type Style_Type is ("deb", "rel");
11364   Style : Style_Type := external ("STYLE", "deb");
11365
11366   case Style is
11367     when "deb" =>
11368       for Object_Dir use "debug";
11369
11370     when "rel" =>
11371       for Object_Dir use "release";
11372       for Exec_Dir use ".";
11373   end case;
11374 @end group
11375
11376 @group
11377   package Builder is
11378
11379     case Style is
11380       when "deb" =>
11381         for ^Default_Switches^Default_Switches^ ("Ada")
11382             use ("^-g^-g^");
11383         for Executable ("proc") use "proc1";
11384       when others =>
11385         null;
11386     end case;
11387
11388   end Builder;
11389 @end group
11390
11391 @group
11392   package Compiler is
11393
11394     case Style is
11395       when "deb" =>
11396         for ^Default_Switches^Default_Switches^ ("Ada")
11397             use ("^-gnata^-gnata^",
11398                  "^-gnato^-gnato^",
11399                  "^-gnatE^-gnatE^");
11400
11401       when "rel" =>
11402         for ^Default_Switches^Default_Switches^ ("Ada")
11403             use ("^-O2^-O2^");
11404     end case;
11405
11406   end Compiler;
11407
11408 end Build;
11409 @end group
11410 @end smallexample
11411
11412 @noindent
11413 @code{Style_Type} is an example of a @emph{string type}, which is the project
11414 file analog of an Ada enumeration type but whose components are string literals
11415 rather than identifiers.  @code{Style} is declared as a variable of this type.
11416
11417 The form @code{external("STYLE", "deb")} is known as an
11418 @emph{external reference}; its first argument is the name of an
11419 @emph{external variable}, and the second argument is a default value to be
11420 used if the external variable doesn't exist.  You can define an external
11421 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
11422 or you can use ^an environment variable^a logical name^
11423 as an external variable.
11424
11425 Each @code{case} construct is expanded by the Project Manager based on the
11426 value of @code{Style}. Thus the command
11427 @ifclear vms
11428 @smallexample
11429 gnatmake -P/common/build.gpr -XSTYLE=deb
11430 @end smallexample
11431 @end ifclear
11432
11433 @ifset vms
11434 @smallexample
11435 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
11436 @end smallexample
11437 @end ifset
11438
11439 @noindent
11440 is equivalent to the @command{gnatmake} invocation using the project file
11441 @file{debug.gpr} in the earlier example.  So is the command
11442 @smallexample
11443 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
11444 @end smallexample
11445
11446 @noindent
11447 since @code{"deb"} is the default for @code{STYLE}.
11448
11449 Analogously,
11450
11451 @ifclear vms
11452 @smallexample
11453 gnatmake -P/common/build.gpr -XSTYLE=rel
11454 @end smallexample
11455 @end ifclear
11456
11457 @ifset vms
11458 @smallexample
11459 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
11460 @end smallexample
11461 @end ifset
11462
11463 @noindent
11464 is equivalent to the @command{gnatmake} invocation using the project file
11465 @file{release.gpr} in the earlier example.
11466
11467 @node Importing Other Projects
11468 @subsection Importing Other Projects
11469 @cindex @code{ADA_PROJECT_PATH}
11470
11471 @noindent
11472 A compilation unit in a source file in one project may depend on compilation
11473 units in source files in other projects.  To compile this unit under
11474 control of a project file, the
11475 dependent project must @emph{import} the projects containing the needed source
11476 files.
11477 This effect is obtained using syntax similar to an Ada @code{with} clause,
11478 but where @code{with}ed entities are strings that denote project files.
11479
11480 As an example, suppose that the two projects @code{GUI_Proj} and
11481 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
11482 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
11483 and @file{^/comm^[COMM]^}, respectively.
11484 Suppose that the source files for @code{GUI_Proj} are
11485 @file{gui.ads} and @file{gui.adb}, and that the source files for
11486 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
11487 files is located in its respective project file directory.  Schematically:
11488
11489 @smallexample
11490 @group
11491 ^/gui^[GUI]^
11492   gui_proj.gpr
11493   gui.ads
11494   gui.adb
11495 @end group
11496
11497 @group
11498 ^/comm^[COMM]^
11499   comm_proj.gpr
11500   comm.ads
11501   comm.adb
11502 @end group
11503 @end smallexample
11504
11505 @noindent
11506 We want to develop an application in directory @file{^/app^[APP]^} that
11507 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
11508 the corresponding project files (e.g. the ^switch^switch^ settings
11509 and object directory).
11510 Skeletal code for a main procedure might be something like the following:
11511
11512 @smallexample @c ada
11513 @group
11514 with GUI, Comm;
11515 procedure App_Main is
11516    ...
11517 begin
11518    ...
11519 end App_Main;
11520 @end group
11521 @end smallexample
11522
11523 @noindent
11524 Here is a project file, @file{app_proj.gpr}, that achieves the desired
11525 effect:
11526
11527 @smallexample @c projectfile
11528 @group
11529 with "/gui/gui_proj", "/comm/comm_proj";
11530 project App_Proj is
11531    for Main use ("app_main");
11532 end App_Proj;
11533 @end group
11534 @end smallexample
11535
11536 @noindent
11537 Building an executable is achieved through the command:
11538 @smallexample
11539 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
11540 @end smallexample
11541 @noindent
11542 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
11543 in the directory where @file{app_proj.gpr} resides.
11544
11545 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
11546 (as illustrated above) the @code{with} clause can omit the extension.
11547
11548 Our example specified an absolute path for each imported project file.
11549 Alternatively, the directory name of an imported object can be omitted
11550 if either
11551 @itemize @bullet
11552 @item
11553 The imported project file is in the same directory as the importing project
11554 file, or
11555 @item
11556 You have defined ^an environment variable^a logical name^
11557 that includes the directory containing
11558 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
11559 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
11560 directory names separated by colons (semicolons on Windows).
11561 @end itemize
11562
11563 @noindent
11564 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
11565 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
11566 as follows:
11567
11568 @smallexample @c projectfile
11569 @group
11570 with "gui_proj", "comm_proj";
11571 project App_Proj is
11572    for Main use ("app_main");
11573 end App_Proj;
11574 @end group
11575 @end smallexample
11576
11577 @noindent
11578 Importing other projects can create ambiguities.
11579 For example, the same unit might be present in different imported projects, or
11580 it might be present in both the importing project and in an imported project.
11581 Both of these conditions are errors.  Note that in the current version of
11582 the Project Manager, it is illegal to have an ambiguous unit even if the
11583 unit is never referenced by the importing project.  This restriction may be
11584 relaxed in a future release.
11585
11586 @node Extending a Project
11587 @subsection Extending a Project
11588
11589 @noindent
11590 In large software systems it is common to have multiple
11591 implementations of a common interface; in Ada terms, multiple versions of a
11592 package body for the same specification.  For example, one implementation
11593 might be safe for use in tasking programs, while another might only be used
11594 in sequential applications.  This can be modeled in GNAT using the concept
11595 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
11596 another project (the ``parent'') then by default all source files of the
11597 parent project are inherited by the child, but the child project can
11598 override any of the parent's source files with new versions, and can also
11599 add new files.  This facility is the project analog of a type extension in
11600 Object-Oriented Programming.  Project hierarchies are permitted (a child
11601 project may be the parent of yet another project), and a project that
11602 inherits one project can also import other projects.
11603
11604 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11605 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11606 @file{pack.adb}, and @file{proc.adb}:
11607
11608 @smallexample
11609 @group
11610 ^/seq^[SEQ]^
11611   pack.ads
11612   pack.adb
11613   proc.adb
11614   seq_proj.gpr
11615 @end group
11616 @end smallexample
11617
11618 @noindent
11619 Note that the project file can simply be empty (that is, no attribute or
11620 package is defined):
11621
11622 @smallexample @c projectfile
11623 @group
11624 project Seq_Proj is
11625 end Seq_Proj;
11626 @end group
11627 @end smallexample
11628
11629 @noindent
11630 implying that its source files are all the Ada source files in the project
11631 directory.
11632
11633 Suppose we want to supply an alternate version of @file{pack.adb}, in
11634 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11635 @file{pack.ads} and @file{proc.adb}.  We can define a project
11636 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11637
11638 @smallexample
11639 @group
11640 ^/tasking^[TASKING]^
11641   pack.adb
11642   tasking_proj.gpr
11643 @end group
11644
11645 @group
11646 project Tasking_Proj extends "/seq/seq_proj" is
11647 end Tasking_Proj;
11648 @end group
11649 @end smallexample
11650
11651 @noindent
11652 The version of @file{pack.adb} used in a build depends on which project file
11653 is specified.
11654
11655 Note that we could have obtained the desired behavior using project import
11656 rather than project inheritance; a @code{base} project would contain the
11657 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11658 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11659 would import @code{base} and add a different version of @file{pack.adb}.  The
11660 choice depends on whether other sources in the original project need to be
11661 overridden.  If they do, then project extension is necessary, otherwise,
11662 importing is sufficient.
11663
11664 @noindent
11665 In a project file that extends another project file, it is possible to
11666 indicate that an inherited source is not part of the sources of the extending
11667 project. This is necessary sometimes when a package spec has been overloaded
11668 and no longer requires a body: in this case, it is necessary to indicate that
11669 the inherited body is not part of the sources of the project, otherwise there
11670 will be a compilation error when compiling the spec.
11671
11672 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11673 Its value is a string list: a list of file names.
11674
11675 @smallexample @c @projectfile
11676 project B extends "a" is
11677    for Source_Files use ("pkg.ads");
11678    --  New spec of Pkg does not need a completion
11679    for Locally_Removed_Files use ("pkg.adb");
11680 end B;
11681 @end smallexample
11682
11683 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11684 is still needed: if it is possible to build using @command{gnatmake} when such
11685 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11686 it is possible to remove the source completely from a system that includes
11687 project P.
11688
11689 @c ***********************
11690 @c * Project File Syntax *
11691 @c ***********************
11692
11693 @node Project File Syntax
11694 @section Project File Syntax
11695
11696 @menu
11697 * Basic Syntax::
11698 * Packages::
11699 * Expressions::
11700 * String Types::
11701 * Variables::
11702 * Attributes::
11703 * Associative Array Attributes::
11704 * case Constructions::
11705 @end menu
11706
11707 @noindent
11708 This section describes the structure of project files.
11709
11710 A project may be an @emph{independent project}, entirely defined by a single
11711 project file. Any Ada source file in an independent project depends only
11712 on the predefined library and other Ada source files in the same project.
11713
11714 @noindent
11715 A project may also @dfn{depend on} other projects, in either or both of
11716 the following ways:
11717 @itemize @bullet
11718 @item It may import any number of projects
11719 @item It may extend at most one other project
11720 @end itemize
11721
11722 @noindent
11723 The dependence relation is a directed acyclic graph (the subgraph reflecting
11724 the ``extends'' relation is a tree).
11725
11726 A project's @dfn{immediate sources} are the source files directly defined by
11727 that project, either implicitly by residing in the project file's directory,
11728 or explicitly through any of the source-related attributes described below.
11729 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11730 of @var{proj} together with the immediate sources (unless overridden) of any
11731 project on which @var{proj} depends (either directly or indirectly).
11732
11733 @node Basic Syntax
11734 @subsection Basic Syntax
11735
11736 @noindent
11737 As seen in the earlier examples, project files have an Ada-like syntax.
11738 The minimal project file is:
11739 @smallexample @c projectfile
11740 @group
11741 project Empty is
11742
11743 end Empty;
11744 @end group
11745 @end smallexample
11746
11747 @noindent
11748 The identifier @code{Empty} is the name of the project.
11749 This project name must be present after the reserved
11750 word @code{end} at the end of the project file, followed by a semi-colon.
11751
11752 Any name in a project file, such as the project name or a variable name,
11753 has the same syntax as an Ada identifier.
11754
11755 The reserved words of project files are the Ada reserved words plus
11756 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11757 reserved words currently used in project file syntax are:
11758
11759 @itemize @bullet
11760 @item
11761 @code{case}
11762 @item
11763 @code{end}
11764 @item
11765 @code{for}
11766 @item
11767 @code{is}
11768 @item
11769 @code{others}
11770 @item
11771 @code{package}
11772 @item
11773 @code{renames}
11774 @item
11775 @code{type}
11776 @item
11777 @code{use}
11778 @item
11779 @code{when}
11780 @item
11781 @code{with}
11782 @end itemize
11783
11784 @noindent
11785 Comments in project files have the same syntax as in Ada, two consecutives
11786 hyphens through the end of the line.
11787
11788 @node Packages
11789 @subsection Packages
11790
11791 @noindent
11792 A project file may contain @emph{packages}. The name of a package must be one
11793 of the identifiers from the following list. A package
11794 with a given name may only appear once in a project file. Package names are
11795 case insensitive. The following package names are legal:
11796
11797 @itemize @bullet
11798 @item
11799 @code{Naming}
11800 @item
11801 @code{Builder}
11802 @item
11803 @code{Compiler}
11804 @item
11805 @code{Binder}
11806 @item
11807 @code{Linker}
11808 @item
11809 @code{Finder}
11810 @item
11811 @code{Cross_Reference}
11812 @item
11813 @code{Eliminate}
11814 @item
11815 @code{Pretty_Printer}
11816 @item
11817 @code{Metrics}
11818 @item
11819 @code{gnatls}
11820 @item
11821 @code{gnatstub}
11822 @item
11823 @code{IDE}
11824 @item
11825 @code{Language_Processing}
11826 @end itemize
11827
11828 @noindent
11829 In its simplest form, a package may be empty:
11830
11831 @smallexample @c projectfile
11832 @group
11833 project Simple is
11834   package Builder is
11835   end Builder;
11836 end Simple;
11837 @end group
11838 @end smallexample
11839
11840 @noindent
11841 A package may contain @emph{attribute declarations},
11842 @emph{variable declarations} and @emph{case constructions}, as will be
11843 described below.
11844
11845 When there is ambiguity between a project name and a package name,
11846 the name always designates the project. To avoid possible confusion, it is
11847 always a good idea to avoid naming a project with one of the
11848 names allowed for packages or any name that starts with @code{gnat}.
11849
11850 @node Expressions
11851 @subsection Expressions
11852
11853 @noindent
11854 An @emph{expression} is either a @emph{string expression} or a
11855 @emph{string list expression}.
11856
11857 A @emph{string expression} is either a @emph{simple string expression} or a
11858 @emph{compound string expression}.
11859
11860 A @emph{simple string expression} is one of the following:
11861 @itemize @bullet
11862 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11863 @item A string-valued variable reference (@pxref{Variables})
11864 @item A string-valued attribute reference (@pxref{Attributes})
11865 @item An external reference (@pxref{External References in Project Files})
11866 @end itemize
11867
11868 @noindent
11869 A @emph{compound string expression} is a concatenation of string expressions,
11870 using the operator @code{"&"}
11871 @smallexample
11872        Path & "/" & File_Name & ".ads"
11873 @end smallexample
11874
11875 @noindent
11876 A @emph{string list expression} is either a
11877 @emph{simple string list expression} or a
11878 @emph{compound string list expression}.
11879
11880 A @emph{simple string list expression} is one of the following:
11881 @itemize @bullet
11882 @item A parenthesized list of zero or more string expressions,
11883 separated by commas
11884 @smallexample
11885    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11886    Empty_List := ();
11887 @end smallexample
11888 @item A string list-valued variable reference
11889 @item A string list-valued attribute reference
11890 @end itemize
11891
11892 @noindent
11893 A @emph{compound string list expression} is the concatenation (using
11894 @code{"&"}) of a simple string list expression and an expression.  Note that
11895 each term in a compound string list expression, except the first, may be
11896 either a string expression or a string list expression.
11897
11898 @smallexample @c projectfile
11899 @group
11900    File_Name_List := () & File_Name; --  One string in this list
11901    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11902    --  Two strings
11903    Big_List := File_Name_List & Extended_File_Name_List;
11904    --  Concatenation of two string lists: three strings
11905    Illegal_List := "gnat.adc" & Extended_File_Name_List;
11906    --  Illegal: must start with a string list
11907 @end group
11908 @end smallexample
11909
11910 @node String Types
11911 @subsection String Types
11912
11913 @noindent
11914 A @emph{string type declaration} introduces a discrete set of string literals.
11915 If a string variable is declared to have this type, its value
11916 is restricted to the given set of literals.
11917
11918 Here is an example of a string type declaration:
11919
11920 @smallexample @c projectfile
11921    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11922 @end smallexample
11923
11924 @noindent
11925 Variables of a string type are called @emph{typed variables}; all other
11926 variables are called @emph{untyped variables}. Typed variables are
11927 particularly useful in @code{case} constructions, to support conditional
11928 attribute declarations.
11929 (@pxref{case Constructions}).
11930
11931 The string literals in the list are case sensitive and must all be different.
11932 They may include any graphic characters allowed in Ada, including spaces.
11933
11934 A string type may only be declared at the project level, not inside a package.
11935
11936 A string type may be referenced by its name if it has been declared in the same
11937 project file, or by an expanded name whose prefix is the name of the project
11938 in which it is declared.
11939
11940 @node Variables
11941 @subsection Variables
11942
11943 @noindent
11944 A variable may be declared at the project file level, or within a package.
11945 Here are some examples of variable declarations:
11946
11947 @smallexample @c projectfile
11948 @group
11949    This_OS : OS := external ("OS"); --  a typed variable declaration
11950    That_OS := "GNU/Linux";          --  an untyped variable declaration
11951 @end group
11952 @end smallexample
11953
11954 @noindent
11955 The syntax of a @emph{typed variable declaration} is identical to the Ada
11956 syntax for an object declaration. By contrast, the syntax of an untyped
11957 variable declaration is identical to an Ada assignment statement. In fact,
11958 variable declarations in project files have some of the characteristics of
11959 an assignment, in that successive declarations for the same variable are
11960 allowed. Untyped variable declarations do establish the expected kind of the
11961 variable (string or string list), and successive declarations for it must
11962 respect the initial kind.
11963
11964 @noindent
11965 A string variable declaration (typed or untyped) declares a variable
11966 whose value is a string. This variable may be used as a string expression.
11967 @smallexample @c projectfile
11968    File_Name       := "readme.txt";
11969    Saved_File_Name := File_Name & ".saved";
11970 @end smallexample
11971
11972 @noindent
11973 A string list variable declaration declares a variable whose value is a list
11974 of strings. The list may contain any number (zero or more) of strings.
11975
11976 @smallexample @c projectfile
11977    Empty_List := ();
11978    List_With_One_Element := ("^-gnaty^-gnaty^");
11979    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11980    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11981                  "pack2.ada", "util_.ada", "util.ada");
11982 @end smallexample
11983
11984 @noindent
11985 The same typed variable may not be declared more than once at project level,
11986 and it may not be declared more than once in any package; it is in effect
11987 a constant.
11988
11989 The same untyped variable may be declared several times. Declarations are
11990 elaborated in the order in which they appear, so  the new value replaces
11991 the old one, and any subsequent reference to the variable uses the new value.
11992 However, as noted above, if a variable has been declared as a string, all
11993 subsequent
11994 declarations must give it a string value. Similarly, if a variable has
11995 been declared as a string list, all subsequent declarations
11996 must give it a string list value.
11997
11998 A @emph{variable reference} may take several forms:
11999
12000 @itemize @bullet
12001 @item The simple variable name, for a variable in the current package (if any)
12002 or in the current project
12003 @item An expanded name, whose prefix is a context name.
12004 @end itemize
12005
12006 @noindent
12007 A @emph{context} may be one of the following:
12008
12009 @itemize @bullet
12010 @item The name of an existing package in the current project
12011 @item The name of an imported project of the current project
12012 @item The name of an ancestor project (i.e., a project extended by the current
12013 project, either directly or indirectly)
12014 @item An expanded name whose prefix is an imported/parent project name, and
12015 whose selector is a package name in that project.
12016 @end itemize
12017
12018 @noindent
12019 A variable reference may be used in an expression.
12020
12021 @node Attributes
12022 @subsection Attributes
12023
12024 @noindent
12025 A project (and its packages) may have @emph{attributes} that define
12026 the project's properties.  Some attributes have values that are strings;
12027 others have values that are string lists.
12028
12029 There are two categories of attributes: @emph{simple attributes}
12030 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12031
12032 Legal project attribute names, and attribute names for each legal package are
12033 listed below. Attributes names are case-insensitive.
12034
12035 The following attributes are defined on projects (all are simple attributes):
12036
12037 @multitable @columnfractions .4 .3
12038 @item @emph{Attribute Name}
12039 @tab @emph{Value}
12040 @item @code{Source_Files}
12041 @tab string list
12042 @item @code{Source_Dirs}
12043 @tab string list
12044 @item @code{Source_List_File}
12045 @tab string
12046 @item @code{Object_Dir}
12047 @tab string
12048 @item @code{Exec_Dir}
12049 @tab string
12050 @item @code{Locally_Removed_Files}
12051 @tab string list
12052 @item @code{Languages}
12053 @tab string list
12054 @item @code{Main}
12055 @tab string list
12056 @item @code{Library_Dir}
12057 @tab string
12058 @item @code{Library_Name}
12059 @tab string
12060 @item @code{Library_Kind}
12061 @tab string
12062 @item @code{Library_Version}
12063 @tab string
12064 @item @code{Library_Interface}
12065 @tab string
12066 @item @code{Library_Auto_Init}
12067 @tab string
12068 @item @code{Library_Options}
12069 @tab string list
12070 @item @code{Library_Src_Dir}
12071 @tab string
12072 @item @code{Library_ALI_Dir}
12073 @tab string
12074 @item @code{Library_GCC}
12075 @tab string
12076 @item @code{Library_Symbol_File}
12077 @tab string
12078 @item @code{Library_Symbol_Policy}
12079 @tab string
12080 @item @code{Library_Reference_Symbol_File}
12081 @tab string
12082 @item @code{Externally_Built}
12083 @tab string
12084 @end multitable
12085
12086 @noindent
12087 The following attributes are defined for package  @code{Naming}
12088 (@pxref{Naming Schemes}):
12089
12090 @multitable @columnfractions .4 .2 .2 .2
12091 @item Attribute Name @tab Category @tab Index @tab Value
12092 @item @code{Spec_Suffix}
12093 @tab associative array
12094 @tab language name
12095 @tab string
12096 @item @code{Body_Suffix}
12097 @tab associative array
12098 @tab language name
12099 @tab string
12100 @item @code{Separate_Suffix}
12101 @tab simple attribute
12102 @tab n/a
12103 @tab string
12104 @item @code{Casing}
12105 @tab simple attribute
12106 @tab n/a
12107 @tab string
12108 @item @code{Dot_Replacement}
12109 @tab simple attribute
12110 @tab n/a
12111 @tab string
12112 @item @code{Spec}
12113 @tab associative array
12114 @tab Ada unit name
12115 @tab string
12116 @item @code{Body}
12117 @tab associative array
12118 @tab Ada unit name
12119 @tab string
12120 @item @code{Specification_Exceptions}
12121 @tab associative array
12122 @tab language name
12123 @tab string list
12124 @item @code{Implementation_Exceptions}
12125 @tab associative array
12126 @tab language name
12127 @tab string list
12128 @end multitable
12129
12130 @noindent
12131 The following attributes are defined for packages @code{Builder},
12132 @code{Compiler}, @code{Binder},
12133 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12134 (@pxref{^Switches^Switches^ and Project Files}).
12135
12136 @multitable @columnfractions .4 .2 .2 .2
12137 @item Attribute Name @tab Category @tab Index @tab Value
12138 @item @code{^Default_Switches^Default_Switches^}
12139 @tab associative array
12140 @tab language name
12141 @tab string list
12142 @item @code{^Switches^Switches^}
12143 @tab associative array
12144 @tab file name
12145 @tab string list
12146 @end multitable
12147
12148 @noindent
12149 In addition, package @code{Compiler} has a single string attribute
12150 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12151 string attribute @code{Global_Configuration_Pragmas}.
12152
12153 @noindent
12154 Each simple attribute has a default value: the empty string (for string-valued
12155 attributes) and the empty list (for string list-valued attributes).
12156
12157 An attribute declaration defines a new value for an attribute.
12158
12159 Examples of simple attribute declarations:
12160
12161 @smallexample @c projectfile
12162    for Object_Dir use "objects";
12163    for Source_Dirs use ("units", "test/drivers");
12164 @end smallexample
12165
12166 @noindent
12167 The syntax of a @dfn{simple attribute declaration} is similar to that of an
12168 attribute definition clause in Ada.
12169
12170 Attributes references may be appear in expressions.
12171 The general form for such a reference is @code{<entity>'<attribute>}:
12172 Associative array attributes are functions. Associative
12173 array attribute references must have an argument that is a string literal.
12174
12175 Examples are:
12176
12177 @smallexample @c projectfile
12178   project'Object_Dir
12179   Naming'Dot_Replacement
12180   Imported_Project'Source_Dirs
12181   Imported_Project.Naming'Casing
12182   Builder'^Default_Switches^Default_Switches^("Ada")
12183 @end smallexample
12184
12185 @noindent
12186 The prefix of an attribute may be:
12187 @itemize @bullet
12188 @item @code{project} for an attribute of the current project
12189 @item The name of an existing package of the current project
12190 @item The name of an imported project
12191 @item The name of a parent project that is extended by the current project
12192 @item An expanded name whose prefix is imported/parent project name,
12193       and whose selector is a package name
12194 @end itemize
12195
12196 @noindent
12197 Example:
12198 @smallexample @c projectfile
12199 @group
12200    project Prj is
12201      for Source_Dirs use project'Source_Dirs & "units";
12202      for Source_Dirs use project'Source_Dirs & "test/drivers"
12203    end Prj;
12204 @end group
12205 @end smallexample
12206
12207 @noindent
12208 In the first attribute declaration, initially the attribute @code{Source_Dirs}
12209 has the default value: an empty string list. After this declaration,
12210 @code{Source_Dirs} is a string list of one element: @code{"units"}.
12211 After the second attribute declaration @code{Source_Dirs} is a string list of
12212 two elements: @code{"units"} and @code{"test/drivers"}.
12213
12214 Note: this example is for illustration only. In practice,
12215 the project file would contain only one attribute declaration:
12216
12217 @smallexample @c projectfile
12218    for Source_Dirs use ("units", "test/drivers");
12219 @end smallexample
12220
12221 @node Associative Array Attributes
12222 @subsection Associative Array Attributes
12223
12224 @noindent
12225 Some attributes are defined as @emph{associative arrays}. An associative
12226 array may be regarded as a function that takes a string as a parameter
12227 and delivers a string or string list value as its result.
12228
12229 Here are some examples of single associative array attribute associations:
12230
12231 @smallexample @c projectfile
12232    for Body ("main") use "Main.ada";
12233    for ^Switches^Switches^ ("main.ada")
12234        use ("^-v^-v^",
12235             "^-gnatv^-gnatv^");
12236    for ^Switches^Switches^ ("main.ada")
12237             use Builder'^Switches^Switches^ ("main.ada")
12238               & "^-g^-g^";
12239 @end smallexample
12240
12241 @noindent
12242 Like untyped variables and simple attributes, associative array attributes
12243 may be declared several times. Each declaration supplies a new value for the
12244 attribute, and replaces the previous setting.
12245
12246 @noindent
12247 An associative array attribute may be declared as a full associative array
12248 declaration, with the value of the same attribute in an imported or extended
12249 project.
12250
12251 @smallexample @c projectfile
12252    package Builder is
12253       for Default_Switches use Default.Builder'Default_Switches;
12254    end Builder;
12255 @end smallexample
12256
12257 @noindent
12258 In this example, @code{Default} must be either a project imported by the
12259 current project, or the project that the current project extends. If the
12260 attribute is in a package (in this case, in package @code{Builder}), the same
12261 package needs to be specified.
12262
12263 @noindent
12264 A full associative array declaration replaces any other declaration for the
12265 attribute, including other full associative array declaration. Single
12266 associative array associations may be declare after a full associative
12267 declaration, modifying the value for a single association of the attribute.
12268
12269 @node case Constructions
12270 @subsection @code{case} Constructions
12271
12272 @noindent
12273 A @code{case} construction is used in a project file to effect conditional
12274 behavior.
12275 Here is a typical example:
12276
12277 @smallexample @c projectfile
12278 @group
12279 project MyProj is
12280    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
12281
12282    OS : OS_Type := external ("OS", "GNU/Linux");
12283 @end group
12284
12285 @group
12286    package Compiler is
12287      case OS is
12288        when "GNU/Linux" | "Unix" =>
12289          for ^Default_Switches^Default_Switches^ ("Ada")
12290              use ("^-gnath^-gnath^");
12291        when "NT" =>
12292          for ^Default_Switches^Default_Switches^ ("Ada")
12293              use ("^-gnatP^-gnatP^");
12294        when others =>
12295      end case;
12296    end Compiler;
12297 end MyProj;
12298 @end group
12299 @end smallexample
12300
12301 @noindent
12302 The syntax of a @code{case} construction is based on the Ada case statement
12303 (although there is no @code{null} construction for empty alternatives).
12304
12305 The case expression must be a typed string variable.
12306 Each alternative comprises the reserved word @code{when}, either a list of
12307 literal strings separated by the @code{"|"} character or the reserved word
12308 @code{others},  and the @code{"=>"} token.
12309 Each literal string must belong to the string type that is the type of the
12310 case variable.
12311 An @code{others} alternative, if present, must occur last.
12312
12313 After each @code{=>}, there are zero or more constructions.  The only
12314 constructions allowed in a case construction are other case constructions,
12315 attribute declarations and variable declarations. String type declarations and
12316 package declarations are not allowed. Variable declarations are restricted to
12317 variables that have already been declared before the case construction.
12318
12319 The value of the case variable is often given by an external reference
12320 (@pxref{External References in Project Files}).
12321
12322 @c ****************************************
12323 @c * Objects and Sources in Project Files *
12324 @c ****************************************
12325
12326 @node Objects and Sources in Project Files
12327 @section Objects and Sources in Project Files
12328
12329 @menu
12330 * Object Directory::
12331 * Exec Directory::
12332 * Source Directories::
12333 * Source File Names::
12334 @end menu
12335
12336 @noindent
12337 Each project has exactly one object directory and one or more source
12338 directories. The source directories must contain at least one source file,
12339 unless  the project file explicitly specifies that no source files are present
12340 (@pxref{Source File Names}).
12341
12342 @node Object Directory
12343 @subsection Object Directory
12344
12345 @noindent
12346 The object directory for a project is the directory containing the compiler's
12347 output (such as @file{ALI} files and object files) for the project's immediate
12348 sources.
12349
12350 The object directory is given by the value of the attribute @code{Object_Dir}
12351 in the project file.
12352
12353 @smallexample @c projectfile
12354    for Object_Dir use "objects";
12355 @end smallexample
12356
12357 @noindent
12358 The attribute @var{Object_Dir} has a string value, the path name of the object
12359 directory. The path name may be absolute or relative to the directory of the
12360 project file. This directory must already exist, and be readable and writable.
12361
12362 By default, when the attribute @code{Object_Dir} is not given an explicit value
12363 or when its value is the empty string, the object directory is the same as the
12364 directory containing the project file.
12365
12366 @node Exec Directory
12367 @subsection Exec Directory
12368
12369 @noindent
12370 The exec directory for a project is the directory containing the executables
12371 for the project's main subprograms.
12372
12373 The exec directory is given by the value of the attribute @code{Exec_Dir}
12374 in the project file.
12375
12376 @smallexample @c projectfile
12377    for Exec_Dir use "executables";
12378 @end smallexample
12379
12380 @noindent
12381 The attribute @var{Exec_Dir} has a string value, the path name of the exec
12382 directory. The path name may be absolute or relative to the directory of the
12383 project file. This directory must already exist, and be writable.
12384
12385 By default, when the attribute @code{Exec_Dir} is not given an explicit value
12386 or when its value is the empty string, the exec directory is the same as the
12387 object directory of the project file.
12388
12389 @node Source Directories
12390 @subsection Source Directories
12391
12392 @noindent
12393 The source directories of a project are specified by the project file
12394 attribute @code{Source_Dirs}.
12395
12396 This attribute's value is a string list. If the attribute is not given an
12397 explicit value, then there is only one source directory, the one where the
12398 project file resides.
12399
12400 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
12401 as in
12402
12403 @smallexample @c projectfile
12404     for Source_Dirs use ();
12405 @end smallexample
12406
12407 @noindent
12408 indicates that the project contains no source files.
12409
12410 Otherwise, each string in the string list designates one or more
12411 source directories.
12412
12413 @smallexample @c projectfile
12414    for Source_Dirs use ("sources", "test/drivers");
12415 @end smallexample
12416
12417 @noindent
12418 If a string in the list ends with @code{"/**"},  then the directory whose path
12419 name precedes the two asterisks, as well as all its subdirectories
12420 (recursively), are source directories.
12421
12422 @smallexample @c projectfile
12423    for Source_Dirs use ("/system/sources/**");
12424 @end smallexample
12425
12426 @noindent
12427 Here the directory @code{/system/sources} and all of its subdirectories
12428 (recursively) are source directories.
12429
12430 To specify that the source directories are the directory of the project file
12431 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
12432 @smallexample @c projectfile
12433    for Source_Dirs use ("./**");
12434 @end smallexample
12435
12436 @noindent
12437 Each of the source directories must exist and be readable.
12438
12439 @node Source File Names
12440 @subsection Source File Names
12441
12442 @noindent
12443 In a project that contains source files, their names may be specified by the
12444 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
12445 (a string). Source file names never include any directory information.
12446
12447 If the attribute @code{Source_Files} is given an explicit value, then each
12448 element of the list is a source file name.
12449
12450 @smallexample @c projectfile
12451    for Source_Files use ("main.adb");
12452    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
12453 @end smallexample
12454
12455 @noindent
12456 If the attribute @code{Source_Files} is not given an explicit value,
12457 but the attribute @code{Source_List_File} is given a string value,
12458 then the source file names are contained in the text file whose path name
12459 (absolute or relative to the directory of the project file) is the
12460 value of the attribute @code{Source_List_File}.
12461
12462 Each line in the file that is not empty or is not a comment
12463 contains a source file name.
12464
12465 @smallexample @c projectfile
12466    for Source_List_File use "source_list.txt";
12467 @end smallexample
12468
12469 @noindent
12470 By default, if neither the attribute @code{Source_Files} nor the attribute
12471 @code{Source_List_File} is given an explicit value, then each file in the
12472 source directories that conforms to the project's naming scheme
12473 (@pxref{Naming Schemes}) is an immediate source of the project.
12474
12475 A warning is issued if both attributes @code{Source_Files} and
12476 @code{Source_List_File} are given explicit values. In this case, the attribute
12477 @code{Source_Files} prevails.
12478
12479 Each source file name must be the name of one existing source file
12480 in one of the source directories.
12481
12482 A @code{Source_Files} attribute whose value is an empty list
12483 indicates that there are no source files in the project.
12484
12485 If the order of the source directories is known statically, that is if
12486 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
12487 be several files with the same source file name. In this case, only the file
12488 in the first directory is considered as an immediate source of the project
12489 file. If the order of the source directories is not known statically, it is
12490 an error to have several files with the same source file name.
12491
12492 Projects can be specified to have no Ada source
12493 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
12494 list, or the @code{"Ada"} may be absent from @code{Languages}:
12495
12496 @smallexample @c projectfile
12497    for Source_Dirs use ();
12498    for Source_Files use ();
12499    for Languages use ("C", "C++");
12500 @end smallexample
12501
12502 @noindent
12503 Otherwise, a project must contain at least one immediate source.
12504
12505 Projects with no source files are useful as template packages
12506 (@pxref{Packages in Project Files}) for other projects; in particular to
12507 define a package @code{Naming} (@pxref{Naming Schemes}).
12508
12509 @c ****************************
12510 @c * Importing Projects *
12511 @c ****************************
12512
12513 @node  Importing Projects
12514 @section Importing Projects
12515 @cindex @code{ADA_PROJECT_PATH}
12516
12517 @noindent
12518 An immediate source of a project P may depend on source files that
12519 are neither immediate sources of P nor in the predefined library.
12520 To get this effect, P must @emph{import} the projects that contain the needed
12521 source files.
12522
12523 @smallexample @c projectfile
12524 @group
12525   with "project1", "utilities.gpr";
12526   with "/namings/apex.gpr";
12527   project Main is
12528     ...
12529 @end group
12530 @end smallexample
12531
12532 @noindent
12533 As can be seen in this example, the syntax for importing projects is similar
12534 to the syntax for importing compilation units in Ada. However, project files
12535 use literal strings instead of names, and the @code{with} clause identifies
12536 project files rather than packages.
12537
12538 Each literal string is the file name or path name (absolute or relative) of a
12539 project file. If a string corresponds to a file name, with no path or a
12540 relative path, then its location is determined by the @emph{project path}. The
12541 latter can be queried using @code{gnatls -v}. It contains:
12542
12543 @itemize @bullet
12544 @item
12545 In first position, the directory containing the current project file.
12546 @item
12547 In last position, the default project directory. This default project directory
12548 is part of the GNAT installation and is the standard place to install project
12549 files giving access to standard support libraries.
12550 @ifclear vms
12551 @ref{Installing a library}
12552 @end ifclear
12553
12554 @item
12555 In between, all the directories referenced in the
12556 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
12557 @end itemize
12558
12559 @noindent
12560 If a relative pathname is used, as in
12561
12562 @smallexample @c projectfile
12563   with "tests/proj";
12564 @end smallexample
12565
12566 @noindent
12567 then the full path for the project is constructed by concatenating this
12568 relative path to those in the project path, in order, until a matching file is
12569 found. Any symbolic link will be fully resolved in the directory of the
12570 importing project file before the imported project file is examined.
12571
12572 If the @code{with}'ed project file name does not have an extension,
12573 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
12574 then the file name as specified in the @code{with} clause (no extension) will
12575 be used. In the above example, if a file @code{project1.gpr} is found, then it
12576 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
12577 then it will be used; if neither file exists, this is an error.
12578
12579 A warning is issued if the name of the project file does not match the
12580 name of the project; this check is case insensitive.
12581
12582 Any source file that is an immediate source of the imported project can be
12583 used by the immediate sources of the importing project, transitively. Thus
12584 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
12585 sources of @code{A} may depend on the immediate sources of @code{C}, even if
12586 @code{A} does not import @code{C} explicitly. However, this is not recommended,
12587 because if and when @code{B} ceases to import @code{C}, some sources in
12588 @code{A} will no longer compile.
12589
12590 A side effect of this capability is that normally cyclic dependencies are not
12591 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
12592 is not allowed to import @code{A}. However, there are cases when cyclic
12593 dependencies would be beneficial. For these cases, another form of import
12594 between projects exists, the @code{limited with}: a project @code{A} that
12595 imports a project @code{B} with a straight @code{with} may also be imported,
12596 directly or indirectly, by @code{B} on the condition that imports from @code{B}
12597 to @code{A} include at least one @code{limited with}.
12598
12599 @smallexample @c 0projectfile
12600 with "../b/b.gpr";
12601 with "../c/c.gpr";
12602 project A is
12603 end A;
12604
12605 limited with "../a/a.gpr";
12606 project B is
12607 end B;
12608
12609 with "../d/d.gpr";
12610 project C is
12611 end C;
12612
12613 limited with "../a/a.gpr";
12614 project D is
12615 end D;
12616 @end smallexample
12617
12618 @noindent
12619 In the above legal example, there are two project cycles:
12620 @itemize @bullet
12621 @item A-> B-> A
12622 @item A -> C -> D -> A
12623 @end itemize
12624
12625 @noindent
12626 In each of these cycle there is one @code{limited with}: import of @code{A}
12627 from @code{B} and import of @code{A} from @code{D}.
12628
12629 The difference between straight @code{with} and @code{limited with} is that
12630 the name of a project imported with a @code{limited with} cannot be used in the
12631 project that imports it. In particular, its packages cannot be renamed and
12632 its variables cannot be referred to.
12633
12634 An exception to the above rules for @code{limited with} is that for the main
12635 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12636 @code{limited with} is equivalent to a straight @code{with}. For example,
12637 in the example above, projects @code{B} and @code{D} could not be main
12638 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12639 each have a @code{limited with} that is the only one in a cycle of importing
12640 projects.
12641
12642 @c *********************
12643 @c * Project Extension *
12644 @c *********************
12645
12646 @node Project Extension
12647 @section Project Extension
12648
12649 @noindent
12650 During development of a large system, it is sometimes necessary to use
12651 modified versions of some of the source files, without changing the original
12652 sources. This can be achieved through the @emph{project extension} facility.
12653
12654 @smallexample @c projectfile
12655    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12656 @end smallexample
12657
12658 @noindent
12659 A project extension declaration introduces an extending project
12660 (the @emph{child}) and a project being extended (the @emph{parent}).
12661
12662 By default, a child project inherits all the sources of its parent.
12663 However, inherited sources can be overridden: a unit in a parent is hidden
12664 by a unit of the same name in the child.
12665
12666 Inherited sources are considered to be sources (but not immediate sources)
12667 of the child project; see @ref{Project File Syntax}.
12668
12669 An inherited source file retains any switches specified in the parent project.
12670
12671 For example if the project @code{Utilities} contains the specification and the
12672 body of an Ada package @code{Util_IO}, then the project
12673 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12674 The original body of @code{Util_IO} will not be considered in program builds.
12675 However, the package specification will still be found in the project
12676 @code{Utilities}.
12677
12678 A child project can have only one parent but it may import any number of other
12679 projects.
12680
12681 A project is not allowed to import directly or indirectly at the same time a
12682 child project and any of its ancestors.
12683
12684 @c *******************************
12685 @c * Project Hierarchy Extension *
12686 @c *******************************
12687
12688 @node Project Hierarchy Extension
12689 @section Project Hierarchy Extension
12690
12691 @noindent
12692 When extending a large system spanning multiple projects, it is often
12693 inconvenient to extend every project in the hierarchy that is impacted by a
12694 small change introduced. In such cases, it is possible to create a virtual
12695 extension of entire hierarchy using @code{extends all} relationship.
12696
12697 When the project is extended using @code{extends all} inheritance, all projects
12698 that are imported by it, both directly and indirectly, are considered virtually
12699 extended. That is, the Project Manager creates "virtual projects"
12700 that extend every project in the hierarchy; all these virtual projects have
12701 no sources of their own and have as object directory the object directory of
12702 the root of "extending all" project.
12703
12704 It is possible to explicitly extend one or more projects in the hierarchy
12705 in order to modify the sources. These extending projects must be imported by
12706 the "extending all" project, which will replace the corresponding virtual
12707 projects with the explicit ones.
12708
12709 When building such a project hierarchy extension, the Project Manager will
12710 ensure that both modified sources and sources in virtual extending projects
12711 that depend on them, are recompiled.
12712
12713 By means of example, consider the following hierarchy of projects.
12714
12715 @enumerate
12716 @item
12717 project A, containing package P1
12718 @item
12719 project B importing A and containing package P2 which depends on P1
12720 @item
12721 project C importing B and containing package P3 which depends on P2
12722 @end enumerate
12723
12724 @noindent
12725 We want to modify packages P1 and P3.
12726
12727 This project hierarchy will need to be extended as follows:
12728
12729 @enumerate
12730 @item
12731 Create project A1 that extends A, placing modified P1 there:
12732
12733 @smallexample @c 0projectfile
12734 project A1 extends "(...)/A" is
12735 end A1;
12736 @end smallexample
12737
12738 @item
12739 Create project C1 that "extends all" C and imports A1, placing modified
12740 P3 there:
12741
12742 @smallexample @c 0projectfile
12743 with "(...)/A1";
12744 project C1 extends all "(...)/C" is
12745 end C1;
12746 @end smallexample
12747 @end enumerate
12748
12749 When you build project C1, your entire modified project space will be
12750 recompiled, including the virtual project B1 that has been impacted by the
12751 "extending all" inheritance of project C.
12752
12753 Note that if a Library Project in the hierarchy is virtually extended,
12754 the virtual project that extends the Library Project is not a Library Project.
12755
12756 @c ****************************************
12757 @c * External References in Project Files *
12758 @c ****************************************
12759
12760 @node  External References in Project Files
12761 @section External References in Project Files
12762
12763 @noindent
12764 A project file may contain references to external variables; such references
12765 are called @emph{external references}.
12766
12767 An external variable is either defined as part of the environment (an
12768 environment variable in Unix, for example) or else specified on the command
12769 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12770 If both, then the command line value is used.
12771
12772 The value of an external reference is obtained by means of the built-in
12773 function @code{external}, which returns a string value.
12774 This function has two forms:
12775 @itemize @bullet
12776 @item @code{external (external_variable_name)}
12777 @item @code{external (external_variable_name, default_value)}
12778 @end itemize
12779
12780 @noindent
12781 Each parameter must be a string literal.  For example:
12782
12783 @smallexample @c projectfile
12784    external ("USER")
12785    external ("OS", "GNU/Linux")
12786 @end smallexample
12787
12788 @noindent
12789 In the form with one parameter, the function returns the value of
12790 the external variable given as parameter. If this name is not present in the
12791 environment, the function returns an empty string.
12792
12793 In the form with two string parameters, the second argument is
12794 the value returned when the variable given as the first argument is not
12795 present in the environment. In the example above, if @code{"OS"} is not
12796 the name of ^an environment variable^a logical name^ and is not passed on
12797 the command line, then the returned value is @code{"GNU/Linux"}.
12798
12799 An external reference may be part of a string expression or of a string
12800 list expression, and can therefore appear in a variable declaration or
12801 an attribute declaration.
12802
12803 @smallexample @c projectfile
12804 @group
12805    type Mode_Type is ("Debug", "Release");
12806    Mode : Mode_Type := external ("MODE");
12807    case Mode is
12808      when "Debug" =>
12809         ...
12810 @end group
12811 @end smallexample
12812
12813 @c *****************************
12814 @c * Packages in Project Files *
12815 @c *****************************
12816
12817 @node  Packages in Project Files
12818 @section Packages in Project Files
12819
12820 @noindent
12821 A @emph{package} defines the settings for project-aware tools within a
12822 project.
12823 For each such tool one can declare a package; the names for these
12824 packages are preset (@pxref{Packages}).
12825 A package may contain variable declarations, attribute declarations, and case
12826 constructions.
12827
12828 @smallexample @c projectfile
12829 @group
12830    project Proj is
12831       package Builder is  -- used by gnatmake
12832          for ^Default_Switches^Default_Switches^ ("Ada")
12833              use ("^-v^-v^",
12834                   "^-g^-g^");
12835       end Builder;
12836    end Proj;
12837 @end group
12838 @end smallexample
12839
12840 @noindent
12841 The syntax of package declarations mimics that of package in Ada.
12842
12843 Most of the packages have an attribute
12844 @code{^Default_Switches^Default_Switches^}.
12845 This attribute is an associative array, and its value is a string list.
12846 The index of the associative array is the name of a programming language (case
12847 insensitive). This attribute indicates the ^switch^switch^
12848 or ^switches^switches^ to be used
12849 with the corresponding tool.
12850
12851 Some packages also have another attribute, @code{^Switches^Switches^},
12852 an associative array whose value is a string list.
12853 The index is the name of a source file.
12854 This attribute indicates the ^switch^switch^
12855 or ^switches^switches^ to be used by the corresponding
12856 tool when dealing with this specific file.
12857
12858 Further information on these ^switch^switch^-related attributes is found in
12859 @ref{^Switches^Switches^ and Project Files}.
12860
12861 A package may be declared as a @emph{renaming} of another package; e.g., from
12862 the project file for an imported project.
12863
12864 @smallexample @c projectfile
12865 @group
12866   with "/global/apex.gpr";
12867   project Example is
12868     package Naming renames Apex.Naming;
12869     ...
12870   end Example;
12871 @end group
12872 @end smallexample
12873
12874 @noindent
12875 Packages that are renamed in other project files often come from project files
12876 that have no sources: they are just used as templates. Any modification in the
12877 template will be reflected automatically in all the project files that rename
12878 a package from the template.
12879
12880 In addition to the tool-oriented packages, you can also declare a package
12881 named @code{Naming} to establish specialized source file naming conventions
12882 (@pxref{Naming Schemes}).
12883
12884 @c ************************************
12885 @c * Variables from Imported Projects *
12886 @c ************************************
12887
12888 @node Variables from Imported Projects
12889 @section Variables from Imported Projects
12890
12891 @noindent
12892 An attribute or variable defined in an imported or parent project can
12893 be used in expressions in the importing / extending project.
12894 Such an attribute or variable is denoted by an expanded name whose prefix
12895 is either the name of the project or the expanded name of a package within
12896 a project.
12897
12898 @smallexample @c projectfile
12899 @group
12900   with "imported";
12901   project Main extends "base" is
12902      Var1 := Imported.Var;
12903      Var2 := Base.Var & ".new";
12904 @end group
12905
12906 @group
12907      package Builder is
12908         for ^Default_Switches^Default_Switches^ ("Ada")
12909             use Imported.Builder'Ada_^Switches^Switches^ &
12910                 "^-gnatg^-gnatg^" &
12911                 "^-v^-v^";
12912      end Builder;
12913 @end group
12914
12915 @group
12916      package Compiler is
12917         for ^Default_Switches^Default_Switches^ ("Ada")
12918             use Base.Compiler'Ada_^Switches^Switches^;
12919      end Compiler;
12920   end Main;
12921 @end group
12922 @end smallexample
12923
12924 @noindent
12925 In this example:
12926
12927 @itemize @bullet
12928 @item
12929 The value of @code{Var1} is a copy of the variable @code{Var} defined
12930 in the project file @file{"imported.gpr"}
12931 @item
12932 the value of @code{Var2} is a copy of the value of variable @code{Var}
12933 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12934 @item
12935 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12936 @code{Builder} is a string list that includes in its value a copy of the value
12937 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12938 in project file @file{imported.gpr} plus two new elements:
12939 @option{"^-gnatg^-gnatg^"}
12940 and @option{"^-v^-v^"};
12941 @item
12942 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12943 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12944 defined in the @code{Compiler} package in project file @file{base.gpr},
12945 the project being extended.
12946 @end itemize
12947
12948 @c ******************
12949 @c * Naming Schemes *
12950 @c ******************
12951
12952 @node  Naming Schemes
12953 @section Naming Schemes
12954
12955 @noindent
12956 Sometimes an Ada software system is ported from a foreign compilation
12957 environment to GNAT, and the file names do not use the default GNAT
12958 conventions. Instead of changing all the file names (which for a variety
12959 of reasons might not be possible), you can define the relevant file
12960 naming scheme in the @code{Naming} package in your project file.
12961
12962 @noindent
12963 Note that the use of pragmas described in
12964 @ref{Alternative File Naming Schemes} by mean of a configuration
12965 pragmas file is not supported when using project files. You must use
12966 the features described in this paragraph. You can however use specify
12967 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
12968
12969 @ifclear vms
12970 For example, the following
12971 package models the Apex file naming rules:
12972
12973 @smallexample @c projectfile
12974 @group
12975   package Naming is
12976     for Casing               use "lowercase";
12977     for Dot_Replacement      use ".";
12978     for Spec_Suffix ("Ada")  use ".1.ada";
12979     for Body_Suffix ("Ada")  use ".2.ada";
12980   end Naming;
12981 @end group
12982 @end smallexample
12983 @end ifclear
12984
12985 @ifset vms
12986 For example, the following package models the HP Ada file naming rules:
12987
12988 @smallexample @c projectfile
12989 @group
12990   package Naming is
12991     for Casing               use "lowercase";
12992     for Dot_Replacement      use "__";
12993     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12994     for Body_Suffix ("Ada")  use ".^ada^ada^";
12995   end Naming;
12996 @end group
12997 @end smallexample
12998
12999 @noindent
13000 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13001 names in lower case)
13002 @end ifset
13003
13004 @noindent
13005 You can define the following attributes in package @code{Naming}:
13006
13007 @table @code
13008
13009 @item @var{Casing}
13010 This must be a string with one of the three values @code{"lowercase"},
13011 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13012
13013 @noindent
13014 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
13015
13016 @item @var{Dot_Replacement}
13017 This must be a string whose value satisfies the following conditions:
13018
13019 @itemize @bullet
13020 @item It must not be empty
13021 @item It cannot start or end with an alphanumeric character
13022 @item It cannot be a single underscore
13023 @item It cannot start with an underscore followed by an alphanumeric
13024 @item It cannot contain a dot @code{'.'} except if the entire string
13025 is @code{"."}
13026 @end itemize
13027
13028 @noindent
13029 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13030
13031 @item @var{Spec_Suffix}
13032 This is an associative array (indexed by the programming language name, case
13033 insensitive) whose value is a string that must satisfy the following
13034 conditions:
13035
13036 @itemize @bullet
13037 @item It must not be empty
13038 @item It must include at least one dot
13039 @end itemize
13040 @noindent
13041 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13042 @code{"^.ads^.ADS^"}.
13043
13044 @item @var{Body_Suffix}
13045 This is an associative array (indexed by the programming language name, case
13046 insensitive) whose value is a string that must satisfy the following
13047 conditions:
13048
13049 @itemize @bullet
13050 @item It must not be empty
13051 @item It must include at least one dot
13052 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
13053 @end itemize
13054 @noindent
13055 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13056 @code{"^.adb^.ADB^"}.
13057
13058 @item @var{Separate_Suffix}
13059 This must be a string whose value satisfies the same conditions as
13060 @code{Body_Suffix}.
13061
13062 @noindent
13063 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13064 value as @code{Body_Suffix ("Ada")}.
13065
13066 @item @var{Spec}
13067 @noindent
13068 You can use the associative array attribute @code{Spec}  to define
13069 the source file name for an individual Ada compilation unit's spec. The array
13070 index must be a string literal that identifies the Ada unit (case insensitive).
13071 The value of this attribute must be a string that identifies the file that
13072 contains this unit's spec (case sensitive or insensitive depending on the
13073 operating system).
13074
13075 @smallexample @c projectfile
13076    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13077 @end smallexample
13078
13079 @item @var{Body}
13080
13081 You can use the associative array attribute @code{Body} to
13082 define the source file name for an individual Ada compilation unit's body
13083 (possibly a subunit).  The array index must be a string literal that identifies
13084 the Ada unit (case insensitive).  The value of this attribute must be a string
13085 that identifies the file that contains this unit's body or subunit (case
13086 sensitive or insensitive depending on the operating system).
13087
13088 @smallexample @c projectfile
13089    for Body ("MyPack.MyChild") use "mypack.mychild.body";
13090 @end smallexample
13091 @end table
13092
13093 @c ********************
13094 @c * Library Projects *
13095 @c ********************
13096
13097 @node Library Projects
13098 @section Library Projects
13099
13100 @noindent
13101 @emph{Library projects} are projects whose object code is placed in a library.
13102 (Note that this facility is not yet supported on all platforms)
13103
13104 To create a library project, you need to define in its project file
13105 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
13106 Additionally, you may define other library-related attributes such as
13107 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
13108 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
13109
13110 The @code{Library_Name} attribute has a string value. There is no restriction
13111 on the name of a library. It is the responsibility of the developer to
13112 choose a name that will be accepted by the platform. It is recommended to
13113 choose names that could be Ada identifiers; such names are almost guaranteed
13114 to be acceptable on all platforms.
13115
13116 The @code{Library_Dir} attribute has a string value that designates the path
13117 (absolute or relative) of the directory where the library will reside.
13118 It must designate an existing directory, and this directory must be writable,
13119 different from the project's object directory and from any source directory
13120 in the project tree.
13121
13122 If both @code{Library_Name} and @code{Library_Dir} are specified and
13123 are legal, then the project file defines a library project.  The optional
13124 library-related attributes are checked only for such project files.
13125
13126 The @code{Library_Kind} attribute has a string value that must be one of the
13127 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13128 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13129 attribute is not specified, the library is a static library, that is
13130 an archive of object files that can be potentially linked into a
13131 static executable. Otherwise, the library may be dynamic or
13132 relocatable, that is a library that is loaded only at the start of execution.
13133
13134 If you need to build both a static and a dynamic library, you should use two
13135 different object directories, since in some cases some extra code needs to
13136 be generated for the latter. For such cases, it is recommended to either use
13137 two different project files, or a single one which uses external variables
13138 to indicate what kind of library should be build.
13139
13140 The @code{Library_ALI_Dir} attribute may be specified to indicate the
13141 directory where the ALI files of the library will be copied. When it is
13142 not specified, the ALI files are copied to the directory specified in
13143 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
13144 must be writable and different from the project's object directory and from
13145 any source directory in the project tree.
13146
13147 The @code{Library_Version} attribute has a string value whose interpretation
13148 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
13149 used only for dynamic/relocatable libraries as the internal name of the
13150 library (the @code{"soname"}). If the library file name (built from the
13151 @code{Library_Name}) is different from the @code{Library_Version}, then the
13152 library file will be a symbolic link to the actual file whose name will be
13153 @code{Library_Version}.
13154
13155 Example (on Unix):
13156
13157 @smallexample @c projectfile
13158 @group
13159 project Plib is
13160
13161    Version := "1";
13162
13163    for Library_Dir use "lib_dir";
13164    for Library_Name use "dummy";
13165    for Library_Kind use "relocatable";
13166    for Library_Version use "libdummy.so." & Version;
13167
13168 end Plib;
13169 @end group
13170 @end smallexample
13171
13172 @noindent
13173 Directory @file{lib_dir} will contain the internal library file whose name
13174 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
13175 @file{libdummy.so.1}.
13176
13177 When @command{gnatmake} detects that a project file
13178 is a library project file, it will check all immediate sources of the project
13179 and rebuild the library if any of the sources have been recompiled.
13180
13181 Standard project files can import library project files. In such cases,
13182 the libraries will only be rebuilt if some of its sources are recompiled
13183 because they are in the closure of some other source in an importing project.
13184 Sources of the library project files that are not in such a closure will
13185 not be checked, unless the full library is checked, because one of its sources
13186 needs to be recompiled.
13187
13188 For instance, assume the project file @code{A} imports the library project file
13189 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
13190 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
13191 @file{l2.ads}, @file{l2.adb}.
13192
13193 If @file{l1.adb} has been modified, then the library associated with @code{L}
13194 will be rebuilt when compiling all the immediate sources of @code{A} only
13195 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
13196 @code{"with L1;"}.
13197
13198 To be sure that all the sources in the library associated with @code{L} are
13199 up to date, and that all the sources of project @code{A} are also up to date,
13200 the following two commands needs to be used:
13201
13202 @smallexample
13203 gnatmake -Pl.gpr
13204 gnatmake -Pa.gpr
13205 @end smallexample
13206
13207 When a library is built or rebuilt, an attempt is made first to delete all
13208 files in the library directory.
13209 All @file{ALI} files will also be copied from the object directory to the
13210 library directory. To build executables, @command{gnatmake} will use the
13211 library rather than the individual object files.
13212
13213 @ifclear vms
13214 It is also possible to create library project files for third-party libraries
13215 that are precompiled and cannot be compiled locally thanks to the
13216 @code{externally_built} attribute. (See @ref{Installing a library}).
13217 @end ifclear
13218
13219 @c *******************************
13220 @c * Stand-alone Library Projects *
13221 @c *******************************
13222
13223 @node Stand-alone Library Projects
13224 @section Stand-alone Library Projects
13225
13226 @noindent
13227 A Stand-alone Library is a library that contains the necessary code to
13228 elaborate the Ada units that are included in the library. A Stand-alone
13229 Library is suitable to be used in an executable when the main is not
13230 in Ada. However, Stand-alone Libraries may also be used with an Ada main
13231 subprogram.
13232
13233 A Stand-alone Library Project is a Library Project where the library is
13234 a Stand-alone Library.
13235
13236 To be a Stand-alone Library Project, in addition to the two attributes
13237 that make a project a Library Project (@code{Library_Name} and
13238 @code{Library_Dir}, see @ref{Library Projects}), the attribute
13239 @code{Library_Interface} must be defined.
13240
13241 @smallexample @c projectfile
13242 @group
13243    for Library_Dir use "lib_dir";
13244    for Library_Name use "dummy";
13245    for Library_Interface use ("int1", "int1.child");
13246 @end group
13247 @end smallexample
13248
13249 Attribute @code{Library_Interface} has a non empty string list value,
13250 each string in the list designating a unit contained in an immediate source
13251 of the project file.
13252
13253 When a Stand-alone Library is built, first the binder is invoked to build
13254 a package whose name depends on the library name
13255 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
13256 This binder-generated package includes initialization and
13257 finalization procedures whose
13258 names depend on the library name (dummyinit and dummyfinal in the example
13259 above). The object corresponding to this package is included in the library.
13260
13261 A dynamic or relocatable Stand-alone Library is automatically initialized
13262 if automatic initialization of Stand-alone Libraries is supported on the
13263 platform and if attribute @code{Library_Auto_Init} is not specified or
13264 is specified with the value "true". A static Stand-alone Library is never
13265 automatically initialized.
13266
13267 Single string attribute @code{Library_Auto_Init} may be specified with only
13268 two possible values: "false" or "true" (case-insensitive). Specifying
13269 "false" for attribute @code{Library_Auto_Init} will prevent automatic
13270 initialization of dynamic or relocatable libraries.
13271
13272 When a non automatically initialized Stand-alone Library is used
13273 in an executable, its initialization procedure must be called before
13274 any service of the library is used.
13275 When the main subprogram is in Ada, it may mean that the initialization
13276 procedure has to be called during elaboration of another package.
13277
13278 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
13279 (those that are listed in attribute @code{Library_Interface}) are copied to
13280 the Library Directory. As a consequence, only the Interface Units may be
13281 imported from Ada units outside of the library. If other units are imported,
13282 the binding phase will fail.
13283
13284 When a Stand-Alone Library is bound, the switches that are specified in
13285 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
13286 used in the call to @command{gnatbind}.
13287
13288 The string list attribute @code{Library_Options} may be used to specified
13289 additional switches to the call to @command{gcc} to link the library.
13290
13291 The attribute @code{Library_Src_Dir}, may be specified for a
13292 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
13293 single string value. Its value must be the path (absolute or relative to the
13294 project directory) of an existing directory. This directory cannot be the
13295 object directory or one of the source directories, but it can be the same as
13296 the library directory. The sources of the Interface
13297 Units of the library, necessary to an Ada client of the library, will be
13298 copied to the designated directory, called Interface Copy directory.
13299 These sources includes the specs of the Interface Units, but they may also
13300 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
13301 are used, or when there is a generic units in the spec. Before the sources
13302 are copied to the Interface Copy directory, an attempt is made to delete all
13303 files in the Interface Copy directory.
13304
13305 @c *************************************
13306 @c * Switches Related to Project Files *
13307 @c *************************************
13308 @node Switches Related to Project Files
13309 @section Switches Related to Project Files
13310
13311 @noindent
13312 The following switches are used by GNAT tools that support project files:
13313
13314 @table @option
13315
13316 @item ^-P^/PROJECT_FILE=^@var{project}
13317 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
13318 Indicates the name of a project file. This project file will be parsed with
13319 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
13320 if any, and using the external references indicated
13321 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
13322 @ifclear vms
13323 There may zero, one or more spaces between @option{-P} and @var{project}.
13324 @end ifclear
13325
13326 @noindent
13327 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
13328
13329 @noindent
13330 Since the Project Manager parses the project file only after all the switches
13331 on the command line are checked, the order of the switches
13332 @option{^-P^/PROJECT_FILE^},
13333 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
13334 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
13335
13336 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
13337 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
13338 Indicates that external variable @var{name} has the value @var{value}.
13339 The Project Manager will use this value for occurrences of
13340 @code{external(name)} when parsing the project file.
13341
13342 @ifclear vms
13343 @noindent
13344 If @var{name} or @var{value} includes a space, then @var{name=value} should be
13345 put between quotes.
13346 @smallexample
13347   -XOS=NT
13348   -X"user=John Doe"
13349 @end smallexample
13350 @end ifclear
13351
13352 @noindent
13353 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
13354 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
13355 @var{name}, only the last one is used.
13356
13357 @noindent
13358 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
13359 takes precedence over the value of the same name in the environment.
13360
13361 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
13362 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
13363 @c Previous line uses code vs option command, to stay less than 80 chars
13364 Indicates the verbosity of the parsing of GNAT project files.
13365
13366 @ifclear vms
13367 @option{-vP0} means Default;
13368 @option{-vP1} means Medium;
13369 @option{-vP2} means High.
13370 @end ifclear
13371
13372 @ifset vms
13373 There are three possible options for this qualifier: DEFAULT, MEDIUM and
13374 HIGH.
13375 @end ifset
13376
13377 @noindent
13378 The default is ^Default^DEFAULT^: no output for syntactically correct
13379 project files.
13380 @noindent
13381 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
13382 only the last one is used.
13383
13384 @end table
13385
13386 @c **********************************
13387 @c * Tools Supporting Project Files *
13388 @c **********************************
13389
13390 @node  Tools Supporting Project Files
13391 @section Tools Supporting Project Files
13392
13393 @menu
13394 * gnatmake and Project Files::
13395 * The GNAT Driver and Project Files::
13396 @end menu
13397
13398 @node gnatmake and Project Files
13399 @subsection gnatmake and Project Files
13400
13401 @noindent
13402 This section covers several topics related to @command{gnatmake} and
13403 project files: defining ^switches^switches^ for @command{gnatmake}
13404 and for the tools that it invokes; specifying configuration pragmas;
13405 the use of the @code{Main} attribute; building and rebuilding library project
13406 files.
13407
13408 @menu
13409 * ^Switches^Switches^ and Project Files::
13410 * Specifying Configuration Pragmas::
13411 * Project Files and Main Subprograms::
13412 * Library Project Files::
13413 @end menu
13414
13415 @node ^Switches^Switches^ and Project Files
13416 @subsubsection ^Switches^Switches^ and Project Files
13417
13418 @ifset vms
13419 It is not currently possible to specify VMS style qualifiers in the project
13420 files; only Unix style ^switches^switches^ may be specified.
13421 @end ifset
13422
13423 @noindent
13424 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
13425 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
13426 attribute, a @code{^Switches^Switches^} attribute, or both;
13427 as their names imply, these ^switch^switch^-related
13428 attributes affect the ^switches^switches^ that are used for each of these GNAT
13429 components when
13430 @command{gnatmake} is invoked.  As will be explained below, these
13431 component-specific ^switches^switches^ precede
13432 the ^switches^switches^ provided on the @command{gnatmake} command line.
13433
13434 The @code{^Default_Switches^Default_Switches^} attribute is an associative
13435 array indexed by language name (case insensitive) whose value is a string list.
13436 For example:
13437
13438 @smallexample @c projectfile
13439 @group
13440 package Compiler is
13441   for ^Default_Switches^Default_Switches^ ("Ada")
13442       use ("^-gnaty^-gnaty^",
13443            "^-v^-v^");
13444 end Compiler;
13445 @end group
13446 @end smallexample
13447
13448 @noindent
13449 The @code{^Switches^Switches^} attribute is also an associative array,
13450 indexed by a file name (which may or may not be case sensitive, depending
13451 on the operating system) whose value is a string list.  For example:
13452
13453 @smallexample @c projectfile
13454 @group
13455 package Builder is
13456    for ^Switches^Switches^ ("main1.adb")
13457        use ("^-O2^-O2^");
13458    for ^Switches^Switches^ ("main2.adb")
13459        use ("^-g^-g^");
13460 end Builder;
13461 @end group
13462 @end smallexample
13463
13464 @noindent
13465 For the @code{Builder} package, the file names must designate source files
13466 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
13467 file names must designate @file{ALI} or source files for main subprograms.
13468 In each case just the file name without an explicit extension is acceptable.
13469
13470 For each tool used in a program build (@command{gnatmake}, the compiler, the
13471 binder, and the linker), the corresponding package @dfn{contributes} a set of
13472 ^switches^switches^ for each file on which the tool is invoked, based on the
13473 ^switch^switch^-related attributes defined in the package.
13474 In particular, the ^switches^switches^
13475 that each of these packages contributes for a given file @var{f} comprise:
13476
13477 @itemize @bullet
13478 @item
13479 the value of attribute @code{^Switches^Switches^ (@var{f})},
13480 if it is specified in the package for the given file,
13481 @item
13482 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
13483 if it is specified in the package.
13484 @end itemize
13485
13486 @noindent
13487 If neither of these attributes is defined in the package, then the package does
13488 not contribute any ^switches^switches^ for the given file.
13489
13490 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
13491 two sets, in the following order: those contributed for the file
13492 by the @code{Builder} package;
13493 and the switches passed on the command line.
13494
13495 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
13496 the ^switches^switches^ passed to the tool comprise three sets,
13497 in the following order:
13498
13499 @enumerate
13500 @item
13501 the applicable ^switches^switches^ contributed for the file
13502 by the @code{Builder} package in the project file supplied on the command line;
13503
13504 @item
13505 those contributed for the file by the package (in the relevant project file --
13506 see below) corresponding to the tool; and
13507
13508 @item
13509 the applicable switches passed on the command line.
13510 @end enumerate
13511
13512 @noindent
13513 The term @emph{applicable ^switches^switches^} reflects the fact that
13514 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
13515 tools, depending on the individual ^switch^switch^.
13516
13517 @command{gnatmake} may invoke the compiler on source files from different
13518 projects. The Project Manager will use the appropriate project file to
13519 determine the @code{Compiler} package for each source file being compiled.
13520 Likewise for the @code{Binder} and @code{Linker} packages.
13521
13522 As an example, consider the following package in a project file:
13523
13524 @smallexample @c projectfile
13525 @group
13526 project Proj1 is
13527    package Compiler is
13528       for ^Default_Switches^Default_Switches^ ("Ada")
13529           use ("^-g^-g^");
13530       for ^Switches^Switches^ ("a.adb")
13531           use ("^-O1^-O1^");
13532       for ^Switches^Switches^ ("b.adb")
13533           use ("^-O2^-O2^",
13534                "^-gnaty^-gnaty^");
13535    end Compiler;
13536 end Proj1;
13537 @end group
13538 @end smallexample
13539
13540 @noindent
13541 If @command{gnatmake} is invoked with this project file, and it needs to
13542 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
13543 @file{a.adb} will be compiled with the ^switch^switch^
13544 @option{^-O1^-O1^},
13545 @file{b.adb} with ^switches^switches^
13546 @option{^-O2^-O2^}
13547 and @option{^-gnaty^-gnaty^},
13548 and @file{c.adb} with @option{^-g^-g^}.
13549
13550 The following example illustrates the ordering of the ^switches^switches^
13551 contributed by different packages:
13552
13553 @smallexample @c projectfile
13554 @group
13555 project Proj2 is
13556    package Builder is
13557       for ^Switches^Switches^ ("main.adb")
13558           use ("^-g^-g^",
13559                "^-O1^-)1^",
13560                "^-f^-f^");
13561    end Builder;
13562 @end group
13563
13564 @group
13565    package Compiler is
13566       for ^Switches^Switches^ ("main.adb")
13567           use ("^-O2^-O2^");
13568    end Compiler;
13569 end Proj2;
13570 @end group
13571 @end smallexample
13572
13573 @noindent
13574 If you issue the command:
13575
13576 @smallexample
13577     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
13578 @end smallexample
13579
13580 @noindent
13581 then the compiler will be invoked on @file{main.adb} with the following
13582 sequence of ^switches^switches^
13583
13584 @smallexample
13585    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
13586 @end smallexample
13587
13588 with the last @option{^-O^-O^}
13589 ^switch^switch^ having precedence over the earlier ones;
13590 several other ^switches^switches^
13591 (such as @option{^-c^-c^}) are added implicitly.
13592
13593 The ^switches^switches^
13594 @option{^-g^-g^}
13595 and @option{^-O1^-O1^} are contributed by package
13596 @code{Builder},  @option{^-O2^-O2^} is contributed
13597 by the package @code{Compiler}
13598 and @option{^-O0^-O0^} comes from the command line.
13599
13600 The @option{^-g^-g^}
13601 ^switch^switch^ will also be passed in the invocation of
13602 @command{Gnatlink.}
13603
13604 A final example illustrates switch contributions from packages in different
13605 project files:
13606
13607 @smallexample @c projectfile
13608 @group
13609 project Proj3 is
13610    for Source_Files use ("pack.ads", "pack.adb");
13611    package Compiler is
13612       for ^Default_Switches^Default_Switches^ ("Ada")
13613           use ("^-gnata^-gnata^");
13614    end Compiler;
13615 end Proj3;
13616 @end group
13617
13618 @group
13619 with "Proj3";
13620 project Proj4 is
13621    for Source_Files use ("foo_main.adb", "bar_main.adb");
13622    package Builder is
13623       for ^Switches^Switches^ ("foo_main.adb")
13624           use ("^-s^-s^",
13625                "^-g^-g^");
13626    end Builder;
13627 end Proj4;
13628 @end group
13629
13630 @group
13631 -- Ada source file:
13632 with Pack;
13633 procedure Foo_Main is
13634    ...
13635 end Foo_Main;
13636 @end group
13637 @end smallexample
13638
13639 If the command is
13640 @smallexample
13641 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13642 @end smallexample
13643
13644 @noindent
13645 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13646 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13647 @option{^-gnato^-gnato^} (passed on the command line).
13648 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13649 are @option{^-g^-g^} from @code{Proj4.Builder},
13650 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13651 and @option{^-gnato^-gnato^} from the command line.
13652
13653 @noindent
13654 When using @command{gnatmake} with project files, some ^switches^switches^ or
13655 arguments may be expressed as relative paths. As the working directory where
13656 compilation occurs may change, these relative paths are converted to absolute
13657 paths. For the ^switches^switches^ found in a project file, the relative paths
13658 are relative to the project file directory, for the switches on the command
13659 line, they are relative to the directory where @command{gnatmake} is invoked.
13660 The ^switches^switches^ for which this occurs are:
13661 ^-I^-I^,
13662 ^-A^-A^,
13663 ^-L^-L^,
13664 ^-aO^-aO^,
13665 ^-aL^-aL^,
13666 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13667 ^switch^switch^
13668 ^-o^-o^, object files specified in package @code{Linker} or after
13669 -largs on the command line). The exception to this rule is the ^switch^switch^
13670 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13671
13672 @node Specifying Configuration Pragmas
13673 @subsubsection Specifying Configuration Pragmas
13674
13675 When using @command{gnatmake} with project files, if there exists a file
13676 @file{gnat.adc} that contains configuration pragmas, this file will be
13677 ignored.
13678
13679 Configuration pragmas can be defined by means of the following attributes in
13680 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13681 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13682
13683 Both these attributes are single string attributes. Their values is the path
13684 name of a file containing configuration pragmas. If a path name is relative,
13685 then it is relative to the project directory of the project file where the
13686 attribute is defined.
13687
13688 When compiling a source, the configuration pragmas used are, in order,
13689 those listed in the file designated by attribute
13690 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13691 project file, if it is specified, and those listed in the file designated by
13692 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13693 the project file of the source, if it exists.
13694
13695 @node Project Files and Main Subprograms
13696 @subsubsection Project Files and Main Subprograms
13697
13698 @noindent
13699 When using a project file, you can invoke @command{gnatmake}
13700 with one or several main subprograms, by specifying their source files on the
13701 command line.
13702
13703 @smallexample
13704     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13705 @end smallexample
13706
13707 @noindent
13708 Each of these needs to be a source file of the same project, except
13709 when the switch ^-u^/UNIQUE^ is used.
13710
13711 @noindent
13712 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13713 same project, one of the project in the tree rooted at the project specified
13714 on the command line. The package @code{Builder} of this common project, the
13715 "main project" is the one that is considered by @command{gnatmake}.
13716
13717 @noindent
13718 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13719 imported directly or indirectly by the project specified on the command line.
13720 Note that if such a source file is not part of the project specified on the
13721 command line, the ^switches^switches^ found in package @code{Builder} of the
13722 project specified on the command line, if any, that are transmitted
13723 to the compiler will still be used, not those found in the project file of
13724 the source file.
13725
13726 @noindent
13727 When using a project file, you can also invoke @command{gnatmake} without
13728 explicitly specifying any main, and the effect depends on whether you have
13729 defined the @code{Main} attribute.  This attribute has a string list value,
13730 where each element in the list is the name of a source file (the file
13731 extension is optional) that contains a unit that can be a main subprogram.
13732
13733 If the @code{Main} attribute is defined in a project file as a non-empty
13734 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13735 line, then invoking @command{gnatmake} with this project file but without any
13736 main on the command line is equivalent to invoking @command{gnatmake} with all
13737 the file names in the @code{Main} attribute on the command line.
13738
13739 Example:
13740 @smallexample @c projectfile
13741 @group
13742    project Prj is
13743       for Main use ("main1", "main2", "main3");
13744    end Prj;
13745 @end group
13746 @end smallexample
13747
13748 @noindent
13749 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13750 is equivalent to
13751 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13752
13753 When the project attribute @code{Main} is not specified, or is specified
13754 as an empty string list, or when the switch @option{-u} is used on the command
13755 line, then invoking @command{gnatmake} with no main on the command line will
13756 result in all immediate sources of the project file being checked, and
13757 potentially recompiled. Depending on the presence of the switch @option{-u},
13758 sources from other project files on which the immediate sources of the main
13759 project file depend are also checked and potentially recompiled. In other
13760 words, the @option{-u} switch is applied to all of the immediate sources of the
13761 main project file.
13762
13763 When no main is specified on the command line and attribute @code{Main} exists
13764 and includes several mains, or when several mains are specified on the
13765 command line, the default ^switches^switches^ in package @code{Builder} will
13766 be used for all mains, even if there are specific ^switches^switches^
13767 specified for one or several mains.
13768
13769 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13770 the specific ^switches^switches^ for each main, if they are specified.
13771
13772 @node Library Project Files
13773 @subsubsection Library Project Files
13774
13775 @noindent
13776 When @command{gnatmake} is invoked with a main project file that is a library
13777 project file, it is not allowed to specify one or more mains on the command
13778 line.
13779
13780 @noindent
13781 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13782 ^-l^/ACTION=LINK^ have special meanings.
13783
13784 @itemize @bullet
13785 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13786 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13787 library.
13788
13789 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13790 to @command{gnatmake} that the binder generated file should be compiled
13791 (in the case of a stand-alone library) and that the library should be built.
13792
13793 @end itemize
13794
13795 @node The GNAT Driver and Project Files
13796 @subsection The GNAT Driver and Project Files
13797
13798 @noindent
13799 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13800 can benefit from project files:
13801 @command{^gnatbind^gnatbind^},
13802 @command{^gnatcheck^gnatcheck^}),
13803 @command{^gnatclean^gnatclean^}),
13804 @command{^gnatelim^gnatelim^},
13805 @command{^gnatfind^gnatfind^},
13806 @command{^gnatlink^gnatlink^},
13807 @command{^gnatls^gnatls^},
13808 @command{^gnatmetric^gnatmetric^},
13809 @command{^gnatpp^gnatpp^},
13810 @command{^gnatstub^gnatstub^},
13811 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13812 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13813 They must be invoked through the @command{gnat} driver.
13814
13815 The @command{gnat} driver is a wrapper that accepts a number of commands and
13816 calls the corresponding tool. It was designed initially for VMS platforms (to
13817 convert VMS qualifiers to Unix-style switches), but it is now available on all
13818 GNAT platforms.
13819
13820 On non-VMS platforms, the @command{gnat} driver accepts the following commands
13821 (case insensitive):
13822
13823 @itemize @bullet
13824 @item
13825 BIND to invoke @command{^gnatbind^gnatbind^}
13826 @item
13827 CHOP to invoke @command{^gnatchop^gnatchop^}
13828 @item
13829 CLEAN to invoke @command{^gnatclean^gnatclean^}
13830 @item
13831 COMP or COMPILE to invoke the compiler
13832 @item
13833 ELIM to invoke @command{^gnatelim^gnatelim^}
13834 @item
13835 FIND to invoke @command{^gnatfind^gnatfind^}
13836 @item
13837 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13838 @item
13839 LINK to invoke @command{^gnatlink^gnatlink^}
13840 @item
13841 LS or LIST to invoke @command{^gnatls^gnatls^}
13842 @item
13843 MAKE to invoke @command{^gnatmake^gnatmake^}
13844 @item
13845 NAME to invoke @command{^gnatname^gnatname^}
13846 @item
13847 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13848 @item
13849 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13850 @item
13851 METRIC to invoke @command{^gnatmetric^gnatmetric^}
13852 @item
13853 STUB to invoke @command{^gnatstub^gnatstub^}
13854 @item
13855 XREF to invoke @command{^gnatxref^gnatxref^}
13856 @end itemize
13857
13858 @noindent
13859 (note that the compiler is invoked using the command
13860 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13861
13862 @noindent
13863 On non VMS platforms, between @command{gnat} and the command, two
13864 special switches may be used:
13865
13866 @itemize @bullet
13867 @item
13868 @command{-v} to display the invocation of the tool.
13869 @item
13870 @command{-dn} to prevent the @command{gnat} driver from removing
13871 the temporary files it has created. These temporary files are
13872 configuration files and temporary file list files.
13873 @end itemize
13874
13875 @noindent
13876 The command may be followed by switches and arguments for the invoked
13877 tool.
13878
13879 @smallexample
13880   gnat bind -C main.ali
13881   gnat ls -a main
13882   gnat chop foo.txt
13883 @end smallexample
13884
13885 @noindent
13886 Switches may also be put in text files, one switch per line, and the text
13887 files may be specified with their path name preceded by '@@'.
13888
13889 @smallexample
13890    gnat bind @@args.txt main.ali
13891 @end smallexample
13892
13893 @noindent
13894 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13895 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
13896 (@option{^-P^/PROJECT_FILE^},
13897 @option{^-X^/EXTERNAL_REFERENCE^} and
13898 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13899 the switches of the invoking tool.
13900
13901 @noindent
13902 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13903 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13904 the immediate sources of the specified project file.
13905
13906 @noindent
13907 When GNAT METRIC is used with a project file, but with no source
13908 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13909 with all the immediate sources of the specified project file and with
13910 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13911 of the project.
13912
13913 @noindent
13914 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
13915 a project file, no source is specified on the command line and
13916 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
13917 the underlying tool (^gnatpp^gnatpp^ or
13918 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
13919 not only for the immediate sources of the main project.
13920 @ifclear vms
13921 (-U stands for Universal or Union of the project files of the project tree)
13922 @end ifclear
13923
13924 @noindent
13925 For each of the following commands, there is optionally a corresponding
13926 package in the main project.
13927
13928 @itemize @bullet
13929 @item
13930 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13931
13932 @item
13933 package @code{Check} for command CHECK (invoking
13934 @code{^gnatcheck^gnatcheck^})
13935
13936 @item
13937 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13938
13939 @item
13940 package @code{Cross_Reference} for command XREF (invoking
13941 @code{^gnatxref^gnatxref^})
13942
13943 @item
13944 package @code{Eliminate} for command ELIM (invoking
13945 @code{^gnatelim^gnatelim^})
13946
13947 @item
13948 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13949
13950 @item
13951 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13952
13953 @item
13954 package @code{Gnatstub} for command STUB
13955 (invoking @code{^gnatstub^gnatstub^})
13956
13957 @item
13958 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13959
13960 @item
13961 package @code{Metrics} for command METRIC
13962 (invoking @code{^gnatmetric^gnatmetric^})
13963
13964 @item
13965 package @code{Pretty_Printer} for command PP or PRETTY
13966 (invoking @code{^gnatpp^gnatpp^})
13967
13968 @end itemize
13969
13970 @noindent
13971 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13972 a simple variable with a string list value. It contains ^switches^switches^
13973 for the invocation of @code{^gnatls^gnatls^}.
13974
13975 @smallexample @c projectfile
13976 @group
13977 project Proj1 is
13978    package gnatls is
13979       for ^Switches^Switches^
13980           use ("^-a^-a^",
13981                "^-v^-v^");
13982    end gnatls;
13983 end Proj1;
13984 @end group
13985 @end smallexample
13986
13987 @noindent
13988 All other packages have two attribute @code{^Switches^Switches^} and
13989 @code{^Default_Switches^Default_Switches^}.
13990
13991 @noindent
13992 @code{^Switches^Switches^} is an associative array attribute, indexed by the
13993 source file name, that has a string list value: the ^switches^switches^ to be
13994 used when the tool corresponding to the package is invoked for the specific
13995 source file.
13996
13997 @noindent
13998 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13999 indexed by  the programming language that has a string list value.
14000 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14001 ^switches^switches^ for the invocation of the tool corresponding
14002 to the package, except if a specific @code{^Switches^Switches^} attribute
14003 is specified for the source file.
14004
14005 @smallexample @c projectfile
14006 @group
14007 project Proj is
14008
14009    for Source_Dirs use ("./**");
14010
14011    package gnatls is
14012       for ^Switches^Switches^ use
14013           ("^-a^-a^",
14014            "^-v^-v^");
14015    end gnatls;
14016 @end group
14017 @group
14018
14019    package Compiler is
14020       for ^Default_Switches^Default_Switches^ ("Ada")
14021           use ("^-gnatv^-gnatv^",
14022                "^-gnatwa^-gnatwa^");
14023    end Binder;
14024 @end group
14025 @group
14026
14027    package Binder is
14028       for ^Default_Switches^Default_Switches^ ("Ada")
14029           use ("^-C^-C^",
14030                "^-e^-e^");
14031    end Binder;
14032 @end group
14033 @group
14034
14035    package Linker is
14036       for ^Default_Switches^Default_Switches^ ("Ada")
14037           use ("^-C^-C^");
14038       for ^Switches^Switches^ ("main.adb")
14039           use ("^-C^-C^",
14040                "^-v^-v^",
14041                "^-v^-v^");
14042    end Linker;
14043 @end group
14044 @group
14045
14046    package Finder is
14047       for ^Default_Switches^Default_Switches^ ("Ada")
14048            use ("^-a^-a^",
14049                 "^-f^-f^");
14050    end Finder;
14051 @end group
14052 @group
14053
14054    package Cross_Reference is
14055       for ^Default_Switches^Default_Switches^ ("Ada")
14056           use ("^-a^-a^",
14057                "^-f^-f^",
14058                "^-d^-d^",
14059                "^-u^-u^");
14060    end Cross_Reference;
14061 end Proj;
14062 @end group
14063 @end smallexample
14064
14065 @noindent
14066 With the above project file, commands such as
14067
14068 @smallexample
14069    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
14070    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
14071    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
14072    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
14073    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
14074 @end smallexample
14075
14076 @noindent
14077 will set up the environment properly and invoke the tool with the switches
14078 found in the package corresponding to the tool:
14079 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
14080 except @code{^Switches^Switches^ ("main.adb")}
14081 for @code{^gnatlink^gnatlink^}.
14082 It is also possible to invoke some of the tools,
14083 @code{^gnatcheck^gnatcheck^}),
14084 @code{^gnatmetric^gnatmetric^}),
14085 and @code{^gnatpp^gnatpp^})
14086 on a set of project units thanks to the combination of the switches
14087 @code{-P}, @code{-U} and possibly the main unit when one is interested
14088 in its closure. For instance,
14089 @smallexample
14090 gnat metric -Pproj
14091 @end smallexample
14092 will compute the metrics for all the immediate units of project
14093 @code{proj}.
14094 @smallexample
14095 gnat metric -Pproj -U
14096 @end smallexample
14097 will compute the metrics for all the units of the closure of projects
14098 rooted at @code{proj}.
14099 @smallexample
14100 gnat metric -Pproj -U main_unit
14101 @end smallexample
14102 will compute the metrics for the closure of units rooted at
14103 @code{main_unit}. This last possibility relies implicitly
14104 on @command{gnatbind}'s option @option{-R}.
14105
14106 @c **********************
14107 @node An Extended Example
14108 @section An Extended Example
14109
14110 @noindent
14111 Suppose that we have two programs, @var{prog1} and @var{prog2},
14112 whose sources are in corresponding directories. We would like
14113 to build them with a single @command{gnatmake} command, and we want to place
14114 their object files into @file{build} subdirectories of the source directories.
14115 Furthermore, we want to have to have two separate subdirectories
14116 in @file{build}  -- @file{release} and @file{debug} -- which will contain
14117 the object files compiled with different set of compilation flags.
14118
14119 In other words, we have the following structure:
14120
14121 @smallexample
14122 @group
14123    main
14124      |- prog1
14125      |    |- build
14126      |         | debug
14127      |         | release
14128      |- prog2
14129           |- build
14130                | debug
14131                | release
14132 @end group
14133 @end smallexample
14134
14135 @noindent
14136 Here are the project files that we must place in a directory @file{main}
14137 to maintain this structure:
14138
14139 @enumerate
14140
14141 @item We create a @code{Common} project with a package @code{Compiler} that
14142 specifies the compilation ^switches^switches^:
14143
14144 @smallexample
14145 File "common.gpr":
14146 @group
14147 @b{project} Common @b{is}
14148
14149    @b{for} Source_Dirs @b{use} (); -- No source files
14150 @end group
14151
14152 @group
14153    @b{type} Build_Type @b{is} ("release", "debug");
14154    Build : Build_Type := External ("BUILD", "debug");
14155 @end group
14156 @group
14157    @b{package} Compiler @b{is}
14158       @b{case} Build @b{is}
14159          @b{when} "release" =>
14160            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14161                    @b{use} ("^-O2^-O2^");
14162          @b{when} "debug"   =>
14163            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14164                    @b{use} ("^-g^-g^");
14165       @b{end case};
14166    @b{end} Compiler;
14167
14168 @b{end} Common;
14169 @end group
14170 @end smallexample
14171
14172 @item We create separate projects for the two programs:
14173
14174 @smallexample
14175 @group
14176 File "prog1.gpr":
14177
14178 @b{with} "common";
14179 @b{project} Prog1 @b{is}
14180
14181     @b{for} Source_Dirs @b{use} ("prog1");
14182     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
14183
14184     @b{package} Compiler @b{renames} Common.Compiler;
14185
14186 @b{end} Prog1;
14187 @end group
14188 @end smallexample
14189
14190 @smallexample
14191 @group
14192 File "prog2.gpr":
14193
14194 @b{with} "common";
14195 @b{project} Prog2 @b{is}
14196
14197     @b{for} Source_Dirs @b{use} ("prog2");
14198     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
14199
14200     @b{package} Compiler @b{renames} Common.Compiler;
14201
14202 @end group
14203 @b{end} Prog2;
14204 @end smallexample
14205
14206 @item We create a wrapping project @code{Main}:
14207
14208 @smallexample
14209 @group
14210 File "main.gpr":
14211
14212 @b{with} "common";
14213 @b{with} "prog1";
14214 @b{with} "prog2";
14215 @b{project} Main @b{is}
14216
14217    @b{package} Compiler @b{renames} Common.Compiler;
14218
14219 @b{end} Main;
14220 @end group
14221 @end smallexample
14222
14223 @item Finally we need to create a dummy procedure that @code{with}s (either
14224 explicitly or implicitly) all the sources of our two programs.
14225
14226 @end enumerate
14227
14228 @noindent
14229 Now we can build the programs using the command
14230
14231 @smallexample
14232    gnatmake ^-P^/PROJECT_FILE=^main dummy
14233 @end smallexample
14234
14235 @noindent
14236 for the Debug mode, or
14237
14238 @ifclear vms
14239 @smallexample
14240    gnatmake -Pmain -XBUILD=release
14241 @end smallexample
14242 @end ifclear
14243
14244 @ifset vms
14245 @smallexample
14246    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
14247 @end smallexample
14248 @end ifset
14249
14250 @noindent
14251 for the Release mode.
14252
14253 @c ********************************
14254 @c * Project File Complete Syntax *
14255 @c ********************************
14256
14257 @node Project File Complete Syntax
14258 @section Project File Complete Syntax
14259
14260 @smallexample
14261 project ::=
14262   context_clause project_declaration
14263
14264 context_clause ::=
14265   @{with_clause@}
14266
14267 with_clause ::=
14268   @b{with} path_name @{ , path_name @} ;
14269
14270 path_name ::=
14271    string_literal
14272
14273 project_declaration ::=
14274   simple_project_declaration | project_extension
14275
14276 simple_project_declaration ::=
14277   @b{project} <project_>simple_name @b{is}
14278     @{declarative_item@}
14279   @b{end} <project_>simple_name;
14280
14281 project_extension ::=
14282   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
14283     @{declarative_item@}
14284   @b{end} <project_>simple_name;
14285
14286 declarative_item ::=
14287   package_declaration |
14288   typed_string_declaration |
14289   other_declarative_item
14290
14291 package_declaration ::=
14292   package_specification | package_renaming
14293
14294 package_specification ::=
14295   @b{package} package_identifier @b{is}
14296     @{simple_declarative_item@}
14297   @b{end} package_identifier ;
14298
14299 package_identifier ::=
14300   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
14301   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
14302   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
14303
14304 package_renaming ::==
14305   @b{package} package_identifier @b{renames}
14306        <project_>simple_name.package_identifier ;
14307
14308 typed_string_declaration ::=
14309   @b{type} <typed_string_>_simple_name @b{is}
14310    ( string_literal @{, string_literal@} );
14311
14312 other_declarative_item ::=
14313   attribute_declaration |
14314   typed_variable_declaration |
14315   variable_declaration |
14316   case_construction
14317
14318 attribute_declaration ::=
14319   full_associative_array_declaration |
14320   @b{for} attribute_designator @b{use} expression ;
14321
14322 full_associative_array_declaration ::=
14323   @b{for} <associative_array_attribute_>simple_name @b{use}
14324   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
14325
14326 attribute_designator ::=
14327   <simple_attribute_>simple_name |
14328   <associative_array_attribute_>simple_name ( string_literal )
14329
14330 typed_variable_declaration ::=
14331   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
14332
14333 variable_declaration ::=
14334   <variable_>simple_name := expression;
14335
14336 expression ::=
14337   term @{& term@}
14338
14339 term ::=
14340   literal_string |
14341   string_list |
14342   <variable_>name |
14343   external_value |
14344   attribute_reference
14345
14346 string_literal ::=
14347   (same as Ada)
14348
14349 string_list ::=
14350   ( <string_>expression @{ , <string_>expression @} )
14351
14352 external_value ::=
14353   @b{external} ( string_literal [, string_literal] )
14354
14355 attribute_reference ::=
14356   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
14357
14358 attribute_prefix ::=
14359   @b{project} |
14360   <project_>simple_name | package_identifier |
14361   <project_>simple_name . package_identifier
14362
14363 case_construction ::=
14364   @b{case} <typed_variable_>name @b{is}
14365     @{case_item@}
14366   @b{end case} ;
14367
14368 case_item ::=
14369   @b{when} discrete_choice_list =>
14370       @{case_construction | attribute_declaration@}
14371
14372 discrete_choice_list ::=
14373   string_literal @{| string_literal@} |
14374   @b{others}
14375
14376 name ::=
14377   simple_name @{. simple_name@}
14378
14379 simple_name ::=
14380   identifier (same as Ada)
14381
14382 @end smallexample
14383
14384 @node The Cross-Referencing Tools gnatxref and gnatfind
14385 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
14386 @findex gnatxref
14387 @findex gnatfind
14388
14389 @noindent
14390 The compiler generates cross-referencing information (unless
14391 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
14392 This information indicates where in the source each entity is declared and
14393 referenced. Note that entities in package Standard are not included, but
14394 entities in all other predefined units are included in the output.
14395
14396 Before using any of these two tools, you need to compile successfully your
14397 application, so that GNAT gets a chance to generate the cross-referencing
14398 information.
14399
14400 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
14401 information to provide the user with the capability to easily locate the
14402 declaration and references to an entity. These tools are quite similar,
14403 the difference being that @code{gnatfind} is intended for locating
14404 definitions and/or references to a specified entity or entities, whereas
14405 @code{gnatxref} is oriented to generating a full report of all
14406 cross-references.
14407
14408 To use these tools, you must not compile your application using the
14409 @option{-gnatx} switch on the @command{gnatmake} command line
14410 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
14411 information will not be generated.
14412
14413 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
14414 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14415
14416 @menu
14417 * gnatxref Switches::
14418 * gnatfind Switches::
14419 * Project Files for gnatxref and gnatfind::
14420 * Regular Expressions in gnatfind and gnatxref::
14421 * Examples of gnatxref Usage::
14422 * Examples of gnatfind Usage::
14423 @end menu
14424
14425 @node gnatxref Switches
14426 @section @code{gnatxref} Switches
14427
14428 @noindent
14429 The command invocation for @code{gnatxref} is:
14430 @smallexample
14431 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
14432 @end smallexample
14433
14434 @noindent
14435 where
14436
14437 @table @code
14438 @item sourcefile1, sourcefile2
14439 identifies the source files for which a report is to be generated. The
14440 ``with''ed units will be processed too. You must provide at least one file.
14441
14442 These file names are considered to be regular expressions, so for instance
14443 specifying @file{source*.adb} is the same as giving every file in the current
14444 directory whose name starts with @file{source} and whose extension is
14445 @file{adb}.
14446
14447 You shouldn't specify any directory name, just base names. @command{gnatxref}
14448 and @command{gnatfind} will be able to locate these files by themselves using
14449 the source path. If you specify directories, no result is produced.
14450
14451 @end table
14452
14453 @noindent
14454 The switches can be :
14455 @table @option
14456 @c !sort!
14457 @item ^-a^/ALL_FILES^
14458 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
14459 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14460 the read-only files found in the library search path. Otherwise, these files
14461 will be ignored. This option can be used to protect Gnat sources or your own
14462 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14463 much faster, and their output much smaller. Read-only here refers to access
14464 or permissions status in the file system for the current user.
14465
14466 @item -aIDIR
14467 @cindex @option{-aIDIR} (@command{gnatxref})
14468 When looking for source files also look in directory DIR. The order in which
14469 source file search is undertaken is the same as for @command{gnatmake}.
14470
14471 @item -aODIR
14472 @cindex @option{-aODIR} (@command{gnatxref})
14473 When searching for library and object files, look in directory
14474 DIR. The order in which library files are searched is the same as for
14475 @command{gnatmake}.
14476
14477 @item -nostdinc
14478 @cindex @option{-nostdinc} (@command{gnatxref})
14479 Do not look for sources in the system default directory.
14480
14481 @item -nostdlib
14482 @cindex @option{-nostdlib} (@command{gnatxref})
14483 Do not look for library files in the system default directory.
14484
14485 @item --RTS=@var{rts-path}
14486 @cindex @option{--RTS} (@command{gnatxref})
14487 Specifies the default location of the runtime library. Same meaning as the
14488 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14489
14490 @item ^-d^/DERIVED_TYPES^
14491 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
14492 If this switch is set @code{gnatxref} will output the parent type
14493 reference for each matching derived types.
14494
14495 @item ^-f^/FULL_PATHNAME^
14496 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
14497 If this switch is set, the output file names will be preceded by their
14498 directory (if the file was found in the search path). If this switch is
14499 not set, the directory will not be printed.
14500
14501 @item ^-g^/IGNORE_LOCALS^
14502 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
14503 If this switch is set, information is output only for library-level
14504 entities, ignoring local entities. The use of this switch may accelerate
14505 @code{gnatfind} and @code{gnatxref}.
14506
14507 @item -IDIR
14508 @cindex @option{-IDIR} (@command{gnatxref})
14509 Equivalent to @samp{-aODIR -aIDIR}.
14510
14511 @item -pFILE
14512 @cindex @option{-pFILE} (@command{gnatxref})
14513 Specify a project file to use @xref{Project Files}.
14514 If you need to use the @file{.gpr}
14515 project files, you should use gnatxref through the GNAT driver
14516 (@command{gnat xref -Pproject}).
14517
14518 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14519 project file in the current directory.
14520
14521 If a project file is either specified or found by the tools, then the content
14522 of the source directory and object directory lines are added as if they
14523 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
14524 and @samp{^-aO^OBJECT_SEARCH^}.
14525 @item ^-u^/UNUSED^
14526 Output only unused symbols. This may be really useful if you give your
14527 main compilation unit on the command line, as @code{gnatxref} will then
14528 display every unused entity and 'with'ed package.
14529
14530 @ifclear vms
14531 @item -v
14532 Instead of producing the default output, @code{gnatxref} will generate a
14533 @file{tags} file that can be used by vi. For examples how to use this
14534 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
14535 to the standard output, thus you will have to redirect it to a file.
14536 @end ifclear
14537
14538 @end table
14539
14540 @noindent
14541 All these switches may be in any order on the command line, and may even
14542 appear after the file names. They need not be separated by spaces, thus
14543 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14544 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14545
14546 @node gnatfind Switches
14547 @section @code{gnatfind} Switches
14548
14549 @noindent
14550 The command line for @code{gnatfind} is:
14551
14552 @smallexample
14553 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
14554       [file1 file2 ...]
14555 @end smallexample
14556
14557 @noindent
14558 where
14559
14560 @table @code
14561 @item pattern
14562 An entity will be output only if it matches the regular expression found
14563 in @samp{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
14564
14565 Omitting the pattern is equivalent to specifying @samp{*}, which
14566 will match any entity. Note that if you do not provide a pattern, you
14567 have to provide both a sourcefile and a line.
14568
14569 Entity names are given in Latin-1, with uppercase/lowercase equivalence
14570 for matching purposes. At the current time there is no support for
14571 8-bit codes other than Latin-1, or for wide characters in identifiers.
14572
14573 @item sourcefile
14574 @code{gnatfind} will look for references, bodies or declarations
14575 of symbols referenced in @file{sourcefile}, at line @samp{line}
14576 and column @samp{column}. See @ref{Examples of gnatfind Usage}
14577 for syntax examples.
14578
14579 @item line
14580 is a decimal integer identifying the line number containing
14581 the reference to the entity (or entities) to be located.
14582
14583 @item column
14584 is a decimal integer identifying the exact location on the
14585 line of the first character of the identifier for the
14586 entity reference. Columns are numbered from 1.
14587
14588 @item file1 file2 ...
14589 The search will be restricted to these source files. If none are given, then
14590 the search will be done for every library file in the search path.
14591 These file must appear only after the pattern or sourcefile.
14592
14593 These file names are considered to be regular expressions, so for instance
14594 specifying 'source*.adb' is the same as giving every file in the current
14595 directory whose name starts with 'source' and whose extension is 'adb'.
14596
14597 The location of the spec of the entity will always be displayed, even if it
14598 isn't in one of file1, file2,... The occurrences of the entity in the
14599 separate units of the ones given on the command line will also be displayed.
14600
14601 Note that if you specify at least one file in this part, @code{gnatfind} may
14602 sometimes not be able to find the body of the subprograms...
14603
14604 @end table
14605
14606 @noindent
14607 At least one of 'sourcefile' or 'pattern' has to be present on
14608 the command line.
14609
14610 The following switches are available:
14611 @table @option
14612 @c !sort!
14613
14614 @item ^-a^/ALL_FILES^
14615 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
14616 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14617 the read-only files found in the library search path. Otherwise, these files
14618 will be ignored. This option can be used to protect Gnat sources or your own
14619 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14620 much faster, and their output much smaller. Read-only here refers to access
14621 or permission status in the file system for the current user.
14622
14623 @item -aIDIR
14624 @cindex @option{-aIDIR} (@command{gnatfind})
14625 When looking for source files also look in directory DIR. The order in which
14626 source file search is undertaken is the same as for @command{gnatmake}.
14627
14628 @item -aODIR
14629 @cindex @option{-aODIR} (@command{gnatfind})
14630 When searching for library and object files, look in directory
14631 DIR. The order in which library files are searched is the same as for
14632 @command{gnatmake}.
14633
14634 @item -nostdinc
14635 @cindex @option{-nostdinc} (@command{gnatfind})
14636 Do not look for sources in the system default directory.
14637
14638 @item -nostdlib
14639 @cindex @option{-nostdlib} (@command{gnatfind})
14640 Do not look for library files in the system default directory.
14641
14642 @item --RTS=@var{rts-path}
14643 @cindex @option{--RTS} (@command{gnatfind})
14644 Specifies the default location of the runtime library. Same meaning as the
14645 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14646
14647 @item ^-d^/DERIVED_TYPE_INFORMATION^
14648 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
14649 If this switch is set, then @code{gnatfind} will output the parent type
14650 reference for each matching derived types.
14651
14652 @item ^-e^/EXPRESSIONS^
14653 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14654 By default, @code{gnatfind} accept the simple regular expression set for
14655 @samp{pattern}. If this switch is set, then the pattern will be
14656 considered as full Unix-style regular expression.
14657
14658 @item ^-f^/FULL_PATHNAME^
14659 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14660 If this switch is set, the output file names will be preceded by their
14661 directory (if the file was found in the search path). If this switch is
14662 not set, the directory will not be printed.
14663
14664 @item ^-g^/IGNORE_LOCALS^
14665 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14666 If this switch is set, information is output only for library-level
14667 entities, ignoring local entities. The use of this switch may accelerate
14668 @code{gnatfind} and @code{gnatxref}.
14669
14670 @item -IDIR
14671 @cindex @option{-IDIR} (@command{gnatfind})
14672 Equivalent to @samp{-aODIR -aIDIR}.
14673
14674 @item -pFILE
14675 @cindex @option{-pFILE} (@command{gnatfind})
14676 Specify a project file (@pxref{Project Files}) to use.
14677 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14678 project file in the current directory.
14679
14680 If a project file is either specified or found by the tools, then the content
14681 of the source directory and object directory lines are added as if they
14682 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14683 @samp{^-aO^/OBJECT_SEARCH^}.
14684
14685 @item ^-r^/REFERENCES^
14686 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14687 By default, @code{gnatfind} will output only the information about the
14688 declaration, body or type completion of the entities. If this switch is
14689 set, the @code{gnatfind} will locate every reference to the entities in
14690 the files specified on the command line (or in every file in the search
14691 path if no file is given on the command line).
14692
14693 @item ^-s^/PRINT_LINES^
14694 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14695 If this switch is set, then @code{gnatfind} will output the content
14696 of the Ada source file lines were the entity was found.
14697
14698 @item ^-t^/TYPE_HIERARCHY^
14699 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14700 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14701 the specified type. It act like -d option but recursively from parent
14702 type to parent type. When this switch is set it is not possible to
14703 specify more than one file.
14704
14705 @end table
14706
14707 @noindent
14708 All these switches may be in any order on the command line, and may even
14709 appear after the file names. They need not be separated by spaces, thus
14710 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14711 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14712
14713 As stated previously, gnatfind will search in every directory in the
14714 search path. You can force it to look only in the current directory if
14715 you specify @code{*} at the end of the command line.
14716
14717 @node Project Files for gnatxref and gnatfind
14718 @section Project Files for @command{gnatxref} and @command{gnatfind}
14719
14720 @noindent
14721 Project files allow a programmer to specify how to compile its
14722 application, where to find sources, etc.  These files are used
14723 @ifclear vms
14724 primarily by GPS, but they can also be used
14725 @end ifclear
14726 by the two tools
14727 @code{gnatxref} and @code{gnatfind}.
14728
14729 A project file name must end with @file{.gpr}. If a single one is
14730 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14731 extract the information from it. If multiple project files are found, none of
14732 them is read, and you have to use the @samp{-p} switch to specify the one
14733 you want to use.
14734
14735 The following lines can be included, even though most of them have default
14736 values which can be used in most cases.
14737 The lines can be entered in any order in the file.
14738 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14739 each line. If you have multiple instances, only the last one is taken into
14740 account.
14741
14742 @table @code
14743 @item src_dir=DIR
14744 [default: @code{"^./^[]^"}]
14745 specifies a directory where to look for source files. Multiple @code{src_dir}
14746 lines can be specified and they will be searched in the order they
14747 are specified.
14748
14749 @item obj_dir=DIR
14750 [default: @code{"^./^[]^"}]
14751 specifies a directory where to look for object and library files. Multiple
14752 @code{obj_dir} lines can be specified, and they will be searched in the order
14753 they are specified
14754
14755 @item comp_opt=SWITCHES
14756 [default: @code{""}]
14757 creates a variable which can be referred to subsequently by using
14758 the @code{$@{comp_opt@}} notation. This is intended to store the default
14759 switches given to @command{gnatmake} and @command{gcc}.
14760
14761 @item bind_opt=SWITCHES
14762 [default: @code{""}]
14763 creates a variable which can be referred to subsequently by using
14764 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14765 switches given to @command{gnatbind}.
14766
14767 @item link_opt=SWITCHES
14768 [default: @code{""}]
14769 creates a variable which can be referred to subsequently by using
14770 the @samp{$@{link_opt@}} notation. This is intended to store the default
14771 switches given to @command{gnatlink}.
14772
14773 @item main=EXECUTABLE
14774 [default: @code{""}]
14775 specifies the name of the executable for the application. This variable can
14776 be referred to in the following lines by using the @samp{$@{main@}} notation.
14777
14778 @ifset vms
14779 @item comp_cmd=COMMAND
14780 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14781 @end ifset
14782 @ifclear vms
14783 @item comp_cmd=COMMAND
14784 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14785 @end ifclear
14786 specifies the command used to compile a single file in the application.
14787
14788 @ifset vms
14789 @item make_cmd=COMMAND
14790 [default: @code{"GNAT MAKE $@{main@}
14791 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14792 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14793 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14794 @end ifset
14795 @ifclear vms
14796 @item make_cmd=COMMAND
14797 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14798  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14799  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14800 @end ifclear
14801 specifies the command used to recompile the whole application.
14802
14803 @item run_cmd=COMMAND
14804 [default: @code{"$@{main@}"}]
14805 specifies the command used to run the application.
14806
14807 @item debug_cmd=COMMAND
14808 [default: @code{"gdb $@{main@}"}]
14809 specifies the command used to debug the application
14810
14811 @end table
14812
14813 @noindent
14814 @command{gnatxref} and @command{gnatfind} only take into account the
14815 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14816
14817 @node Regular Expressions in gnatfind and gnatxref
14818 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
14819
14820 @noindent
14821 As specified in the section about @command{gnatfind}, the pattern can be a
14822 regular expression. Actually, there are to set of regular expressions
14823 which are recognized by the program :
14824
14825 @table @code
14826 @item globbing patterns
14827 These are the most usual regular expression. They are the same that you
14828 generally used in a Unix shell command line, or in a DOS session.
14829
14830 Here is a more formal grammar :
14831 @smallexample
14832 @group
14833 @iftex
14834 @leftskip=.5cm
14835 @end iftex
14836 regexp ::= term
14837 term   ::= elmt            -- matches elmt
14838 term   ::= elmt elmt       -- concatenation (elmt then elmt)
14839 term   ::= *               -- any string of 0 or more characters
14840 term   ::= ?               -- matches any character
14841 term   ::= [char @{char@}] -- matches any character listed
14842 term   ::= [char - char]   -- matches any character in range
14843 @end group
14844 @end smallexample
14845
14846 @item full regular expression
14847 The second set of regular expressions is much more powerful. This is the
14848 type of regular expressions recognized by utilities such a @file{grep}.
14849
14850 The following is the form of a regular expression, expressed in Ada
14851 reference manual style BNF is as follows
14852
14853 @smallexample
14854 @iftex
14855 @leftskip=.5cm
14856 @end iftex
14857 @group
14858 regexp ::= term @{| term@} -- alternation (term or term ...)
14859
14860 term ::= item @{item@}     -- concatenation (item then item)
14861
14862 item ::= elmt              -- match elmt
14863 item ::= elmt *            -- zero or more elmt's
14864 item ::= elmt +            -- one or more elmt's
14865 item ::= elmt ?            -- matches elmt or nothing
14866 @end group
14867 @group
14868 elmt ::= nschar            -- matches given character
14869 elmt ::= [nschar @{nschar@}]   -- matches any character listed
14870 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14871 elmt ::= [char - char]     -- matches chars in given range
14872 elmt ::= \ char            -- matches given character
14873 elmt ::= .                 -- matches any single character
14874 elmt ::= ( regexp )        -- parens used for grouping
14875
14876 char ::= any character, including special characters
14877 nschar ::= any character except ()[].*+?^^^
14878 @end group
14879 @end smallexample
14880
14881 Following are a few examples :
14882
14883 @table @samp
14884 @item abcde|fghi
14885 will match any of the two strings 'abcde' and 'fghi'.
14886
14887 @item abc*d
14888 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14889
14890 @item [a-z]+
14891 will match any string which has only lowercase characters in it (and at
14892 least one character
14893
14894 @end table
14895 @end table
14896
14897 @node Examples of gnatxref Usage
14898 @section Examples of @code{gnatxref} Usage
14899
14900 @subsection General Usage
14901
14902 @noindent
14903 For the following examples, we will consider the following units :
14904
14905 @smallexample @c ada
14906 @group
14907 @cartouche
14908 main.ads:
14909 1: with Bar;
14910 2: package Main is
14911 3:     procedure Foo (B : in Integer);
14912 4:     C : Integer;
14913 5: private
14914 6:     D : Integer;
14915 7: end Main;
14916
14917 main.adb:
14918 1: package body Main is
14919 2:     procedure Foo (B : in Integer) is
14920 3:     begin
14921 4:        C := B;
14922 5:        D := B;
14923 6:        Bar.Print (B);
14924 7:        Bar.Print (C);
14925 8:     end Foo;
14926 9: end Main;
14927
14928 bar.ads:
14929 1: package Bar is
14930 2:     procedure Print (B : Integer);
14931 3: end bar;
14932 @end cartouche
14933 @end group
14934 @end smallexample
14935
14936 @table @code
14937
14938 @noindent
14939 The first thing to do is to recompile your application (for instance, in
14940 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14941 the cross-referencing information.
14942 You can then issue any of the following commands:
14943
14944 @item gnatxref main.adb
14945 @code{gnatxref} generates cross-reference information for main.adb
14946 and every unit 'with'ed by main.adb.
14947
14948 The output would be:
14949 @smallexample
14950 @iftex
14951 @leftskip=0cm
14952 @end iftex
14953 B                                                      Type: Integer
14954   Decl: bar.ads           2:22
14955 B                                                      Type: Integer
14956   Decl: main.ads          3:20
14957   Body: main.adb          2:20
14958   Ref:  main.adb          4:13     5:13     6:19
14959 Bar                                                    Type: Unit
14960   Decl: bar.ads           1:9
14961   Ref:  main.adb          6:8      7:8
14962        main.ads           1:6
14963 C                                                      Type: Integer
14964   Decl: main.ads          4:5
14965   Modi: main.adb          4:8
14966   Ref:  main.adb          7:19
14967 D                                                      Type: Integer
14968   Decl: main.ads          6:5
14969   Modi: main.adb          5:8
14970 Foo                                                    Type: Unit
14971   Decl: main.ads          3:15
14972   Body: main.adb          2:15
14973 Main                                                    Type: Unit
14974   Decl: main.ads          2:9
14975   Body: main.adb          1:14
14976 Print                                                   Type: Unit
14977   Decl: bar.ads           2:15
14978   Ref:  main.adb          6:12     7:12
14979 @end smallexample
14980
14981 @noindent
14982 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14983 its body is in main.adb, line 1, column 14 and is not referenced any where.
14984
14985 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14986 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14987
14988 @item gnatxref package1.adb package2.ads
14989 @code{gnatxref} will generates cross-reference information for
14990 package1.adb, package2.ads and any other package 'with'ed by any
14991 of these.
14992
14993 @end table
14994
14995 @ifclear vms
14996 @subsection Using gnatxref with vi
14997
14998 @code{gnatxref} can generate a tags file output, which can be used
14999 directly from @file{vi}. Note that the standard version of @file{vi}
15000 will not work properly with overloaded symbols. Consider using another
15001 free implementation of @file{vi}, such as @file{vim}.
15002
15003 @smallexample
15004 $ gnatxref -v gnatfind.adb > tags
15005 @end smallexample
15006
15007 @noindent
15008 will generate the tags file for @code{gnatfind} itself (if the sources
15009 are in the search path!).
15010
15011 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
15012 (replacing @i{entity} by whatever you are looking for), and vi will
15013 display a new file with the corresponding declaration of entity.
15014 @end ifclear
15015
15016 @node Examples of gnatfind Usage
15017 @section Examples of @code{gnatfind} Usage
15018
15019 @table @code
15020
15021 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15022 Find declarations for all entities xyz referenced at least once in
15023 main.adb. The references are search in every library file in the search
15024 path.
15025
15026 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15027 switch is set)
15028
15029 The output will look like:
15030 @smallexample
15031 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15032 ^directory/^[directory]^main.adb:24:10: xyz <= body
15033 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15034 @end smallexample
15035
15036 @noindent
15037 that is to say, one of the entities xyz found in main.adb is declared at
15038 line 12 of main.ads (and its body is in main.adb), and another one is
15039 declared at line 45 of foo.ads
15040
15041 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
15042 This is the same command as the previous one, instead @code{gnatfind} will
15043 display the content of the Ada source file lines.
15044
15045 The output will look like:
15046
15047 @smallexample
15048 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15049    procedure xyz;
15050 ^directory/^[directory]^main.adb:24:10: xyz <= body
15051    procedure xyz is
15052 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15053    xyz : Integer;
15054 @end smallexample
15055
15056 @noindent
15057 This can make it easier to find exactly the location your are looking
15058 for.
15059
15060 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
15061 Find references to all entities containing an x that are
15062 referenced on line 123 of main.ads.
15063 The references will be searched only in main.ads and foo.adb.
15064
15065 @item gnatfind main.ads:123
15066 Find declarations and bodies for all entities that are referenced on
15067 line 123 of main.ads.
15068
15069 This is the same as @code{gnatfind "*":main.adb:123}.
15070
15071 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
15072 Find the declaration for the entity referenced at column 45 in
15073 line 123 of file main.adb in directory mydir. Note that it
15074 is usual to omit the identifier name when the column is given,
15075 since the column position identifies a unique reference.
15076
15077 The column has to be the beginning of the identifier, and should not
15078 point to any character in the middle of the identifier.
15079
15080 @end table
15081
15082 @c *********************************
15083 @node The GNAT Pretty-Printer gnatpp
15084 @chapter The GNAT Pretty-Printer @command{gnatpp}
15085 @findex gnatpp
15086 @cindex Pretty-Printer
15087
15088 @noindent
15089 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
15090 for source reformatting / pretty-printing.
15091 It takes an Ada source file as input and generates a reformatted
15092 version as output.
15093 You can specify various style directives via switches; e.g.,
15094 identifier case conventions, rules of indentation, and comment layout.
15095
15096 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
15097 tree for the input source and thus requires the input to be syntactically and
15098 semantically legal.
15099 If this condition is not met, @command{gnatpp} will terminate with an
15100 error message; no output file will be generated.
15101
15102 If the source files presented to @command{gnatpp} contain
15103 preprocessing directives, then the output file will
15104 correspond to the generated source after all
15105 preprocessing is carried out. There is no way
15106 using @command{gnatpp} to obtain pretty printed files that
15107 include the preprocessing directives.
15108
15109 If the compilation unit
15110 contained in the input source depends semantically upon units located
15111 outside the current directory, you have to provide the source search path
15112 when invoking @command{gnatpp}, if these units are contained in files with
15113 names that do not follow the GNAT file naming rules, you have to provide
15114 the configuration file describing the corresponding naming scheme;
15115 see the description of the @command{gnatpp}
15116 switches below. Another possibility is to use a project file and to
15117 call @command{gnatpp} through the @command{gnat} driver
15118
15119 The @command{gnatpp} command has the form
15120
15121 @smallexample
15122 $ gnatpp [@var{switches}] @var{filename}
15123 @end smallexample
15124
15125 @noindent
15126 where
15127 @itemize @bullet
15128 @item
15129 @var{switches} is an optional sequence of switches defining such properties as
15130 the formatting rules, the source search path, and the destination for the
15131 output source file
15132
15133 @item
15134 @var{filename} is the name (including the extension) of the source file to
15135 reformat; ``wildcards'' or several file names on the same gnatpp command are
15136 allowed.  The file name may contain path information; it does not have to
15137 follow the GNAT file naming rules
15138 @end itemize
15139
15140 @menu
15141 * Switches for gnatpp::
15142 * Formatting Rules::
15143 @end menu
15144
15145 @node Switches for gnatpp
15146 @section Switches for @command{gnatpp}
15147
15148 @noindent
15149 The following subsections describe the various switches accepted by
15150 @command{gnatpp}, organized by category.
15151
15152 @ifclear vms
15153 You specify a switch by supplying a name and generally also a value.
15154 In many cases the values for a switch with a given name are incompatible with
15155 each other
15156 (for example the switch that controls the casing of a reserved word may have
15157 exactly one value: upper case, lower case, or
15158 mixed case) and thus exactly one such switch can be in effect for an
15159 invocation of @command{gnatpp}.
15160 If more than one is supplied, the last one is used.
15161 However, some values for the same switch are mutually compatible.
15162 You may supply several such switches to @command{gnatpp}, but then
15163 each must be specified in full, with both the name and the value.
15164 Abbreviated forms (the name appearing once, followed by each value) are
15165 not permitted.
15166 For example, to set
15167 the alignment of the assignment delimiter both in declarations and in
15168 assignment statements, you must write @option{-A2A3}
15169 (or @option{-A2 -A3}), but not @option{-A23}.
15170 @end ifclear
15171
15172 @ifset vms
15173 In many cases the set of options for a given qualifier are incompatible with
15174 each other (for example the qualifier that controls the casing of a reserved
15175 word may have exactly one option, which specifies either upper case, lower
15176 case, or mixed case), and thus exactly one such option can be in effect for
15177 an invocation of @command{gnatpp}.
15178 If more than one is supplied, the last one is used.
15179 However, some qualifiers have options that are mutually compatible,
15180 and then you may then supply several such options when invoking
15181 @command{gnatpp}.
15182 @end ifset
15183
15184 In most cases, it is obvious whether or not the
15185 ^values for a switch with a given name^options for a given qualifier^
15186 are compatible with each other.
15187 When the semantics might not be evident, the summaries below explicitly
15188 indicate the effect.
15189
15190 @menu
15191 * Alignment Control::
15192 * Casing Control::
15193 * Construct Layout Control::
15194 * General Text Layout Control::
15195 * Other Formatting Options::
15196 * Setting the Source Search Path::
15197 * Output File Control::
15198 * Other gnatpp Switches::
15199 @end menu
15200
15201 @node Alignment Control
15202 @subsection Alignment Control
15203 @cindex Alignment control in @command{gnatpp}
15204
15205 @noindent
15206 Programs can be easier to read if certain constructs are vertically aligned.
15207 By default all alignments are set ON.
15208 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
15209 OFF, and then use one or more of the other
15210 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
15211 to activate alignment for specific constructs.
15212
15213 @table @option
15214 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
15215
15216 @ifset vms
15217 @item /ALIGN=ON
15218 Set all alignments to ON
15219 @end ifset
15220
15221 @item ^-A0^/ALIGN=OFF^
15222 Set all alignments to OFF
15223
15224 @item ^-A1^/ALIGN=COLONS^
15225 Align @code{:} in declarations
15226
15227 @item ^-A2^/ALIGN=DECLARATIONS^
15228 Align @code{:=} in initializations in declarations
15229
15230 @item ^-A3^/ALIGN=STATEMENTS^
15231 Align @code{:=} in assignment statements
15232
15233 @item ^-A4^/ALIGN=ARROWS^
15234 Align @code{=>} in associations
15235
15236 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
15237 Align @code{at} keywords in the component clauses in record
15238 representation clauses
15239 @end table
15240
15241 @noindent
15242 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
15243 is allowed.
15244
15245 @node Casing Control
15246 @subsection Casing Control
15247 @cindex Casing control in @command{gnatpp}
15248
15249 @noindent
15250 @command{gnatpp} allows you to specify the casing for reserved words,
15251 pragma names, attribute designators and identifiers.
15252 For identifiers you may define a
15253 general rule for name casing but also override this rule
15254 via a set of dictionary files.
15255
15256 Three types of casing are supported: lower case, upper case, and mixed case.
15257 Lower and upper case are self-explanatory (but since some letters in
15258 Latin1 and other GNAT-supported character sets
15259 exist only in lower-case form, an upper case conversion will have no
15260 effect on them.)
15261 ``Mixed case'' means that the first letter, and also each letter immediately
15262 following an underscore, are converted to their uppercase forms;
15263 all the other letters are converted to their lowercase forms.
15264
15265 @table @option
15266 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
15267 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
15268 Attribute designators are lower case
15269
15270 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
15271 Attribute designators are upper case
15272
15273 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
15274 Attribute designators are mixed case (this is the default)
15275
15276 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
15277 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
15278 Keywords (technically, these are known in Ada as @emph{reserved words}) are
15279 lower case (this is the default)
15280
15281 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
15282 Keywords are upper case
15283
15284 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
15285 @item ^-nD^/NAME_CASING=AS_DECLARED^
15286 Name casing for defining occurrences are as they appear in the source file
15287 (this is the default)
15288
15289 @item ^-nU^/NAME_CASING=UPPER_CASE^
15290 Names are in upper case
15291
15292 @item ^-nL^/NAME_CASING=LOWER_CASE^
15293 Names are in lower case
15294
15295 @item ^-nM^/NAME_CASING=MIXED_CASE^
15296 Names are in mixed case
15297
15298 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
15299 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
15300 Pragma names are lower case
15301
15302 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
15303 Pragma names are upper case
15304
15305 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
15306 Pragma names are mixed case (this is the default)
15307
15308 @item ^-D@var{file}^/DICTIONARY=@var{file}^
15309 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
15310 Use @var{file} as a @emph{dictionary file} that defines
15311 the casing for a set of specified names,
15312 thereby overriding the effect on these names by
15313 any explicit or implicit
15314 ^-n^/NAME_CASING^ switch.
15315 To supply more than one dictionary file,
15316 use ^several @option{-D} switches^a list of files as options^.
15317
15318 @noindent
15319 @option{gnatpp} implicitly uses a @emph{default dictionary file}
15320 to define the casing for the Ada predefined names and
15321 the names declared in the GNAT libraries.
15322
15323 @item ^-D-^/SPECIFIC_CASING^
15324 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
15325 Do not use the default dictionary file;
15326 instead, use the casing
15327 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
15328 dictionary file(s)
15329 @end table
15330
15331 @noindent
15332 The structure of a dictionary file, and details on the conventions
15333 used in the default dictionary file, are defined in @ref{Name Casing}.
15334
15335 The @option{^-D-^/SPECIFIC_CASING^} and
15336 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
15337 compatible.
15338
15339 @node Construct Layout Control
15340 @subsection Construct Layout Control
15341 @cindex Layout control in @command{gnatpp}
15342
15343 @noindent
15344 This group of @command{gnatpp} switches controls the layout of comments and
15345 complex syntactic constructs.  See @ref{Formatting Comments} for details
15346 on their effect.
15347
15348 @table @option
15349 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
15350 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
15351 All the comments remain unchanged
15352
15353 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
15354 GNAT-style comment line indentation (this is the default).
15355
15356 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
15357 Reference-manual comment line indentation.
15358
15359 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
15360 GNAT-style comment beginning
15361
15362 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
15363 Reformat comment blocks
15364
15365 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
15366 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
15367 GNAT-style layout (this is the default)
15368
15369 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
15370 Compact layout
15371
15372 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
15373 Uncompact layout
15374
15375 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
15376 @item ^-N^/NOTABS^
15377 All the VT characters are removed from the comment text. All the HT characters
15378 are expanded with the sequences of space characters to get to the next tab
15379 stops.
15380
15381 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
15382 @item ^--no-separate-is^/NO_SEPARATE_IS^
15383 Do not place the keyword @code{is} on a separate line in a subprogram body in
15384 case if the specification occupies more then one line.
15385
15386 @end table
15387
15388 @ifclear vms
15389 @noindent
15390 The @option{-c1} and @option{-c2} switches are incompatible.
15391 The @option{-c3} and @option{-c4} switches are compatible with each other and
15392 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
15393 the other comment formatting switches.
15394
15395 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
15396 @end ifclear
15397
15398 @ifset vms
15399 @noindent
15400 For the @option{/COMMENTS_LAYOUT} qualifier:
15401 @itemize @bullet
15402 @item
15403 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
15404 @item
15405 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
15406 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
15407 @end itemize
15408
15409 @noindent
15410 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
15411 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
15412 @end ifset
15413
15414 @node General Text Layout Control
15415 @subsection General Text Layout Control
15416
15417 @noindent
15418 These switches allow control over line length and indentation.
15419
15420 @table @option
15421 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
15422 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
15423 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
15424
15425 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
15426 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
15427 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
15428
15429 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
15430 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
15431 Indentation level for continuation lines (relative to the line being
15432 continued), @i{nnn} from 1 .. 9.
15433 The default
15434 value is one less then the (normal) indentation level, unless the
15435 indentation is set to 1 (in which case the default value for continuation
15436 line indentation is also 1)
15437 @end table
15438
15439 @node Other Formatting Options
15440 @subsection Other Formatting Options
15441
15442 @noindent
15443 These switches control the inclusion of missing end/exit labels, and
15444 the indentation level in @b{case} statements.
15445
15446 @table @option
15447 @item ^-e^/NO_MISSED_LABELS^
15448 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
15449 Do not insert missing end/exit labels. An end label is the name of
15450 a construct that may optionally be repeated at the end of the
15451 construct's declaration;
15452 e.g., the names of packages, subprograms, and tasks.
15453 An exit label is the name of a loop that may appear as target
15454 of an exit statement within the loop.
15455 By default, @command{gnatpp} inserts these end/exit labels when
15456 they are absent from the original source. This option suppresses such
15457 insertion, so that the formatted source reflects the original.
15458
15459 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
15460 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
15461 Insert a Form Feed character after a pragma Page.
15462
15463 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
15464 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
15465 Do not use an additional indentation level for @b{case} alternatives
15466 and variants if there are @i{nnn} or more (the default
15467 value is 10).
15468 If @i{nnn} is 0, an additional indentation level is
15469 used for @b{case} alternatives and variants regardless of their number.
15470 @end table
15471
15472 @node Setting the Source Search Path
15473 @subsection Setting the Source Search Path
15474
15475 @noindent
15476 To define the search path for the input source file, @command{gnatpp}
15477 uses the same switches as the GNAT compiler, with the same effects.
15478
15479 @table @option
15480 @item ^-I^/SEARCH=^@var{dir}
15481 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
15482 The same as the corresponding gcc switch
15483
15484 @item ^-I-^/NOCURRENT_DIRECTORY^
15485 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
15486 The same as the corresponding gcc switch
15487
15488 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
15489 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
15490 The same as the corresponding gcc switch
15491
15492 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
15493 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
15494 The same as the corresponding gcc switch
15495
15496 @end table
15497
15498 @node Output File Control
15499 @subsection Output File Control
15500
15501 @noindent
15502 By default the output is sent to the file whose name is obtained by appending
15503 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
15504 (if the file with this name already exists, it is unconditionally overwritten).
15505 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
15506 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
15507 as output file.
15508 The output may be redirected by the following switches:
15509
15510 @table @option
15511 @item ^-pipe^/STANDARD_OUTPUT^
15512 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
15513 Send the output to @code{Standard_Output}
15514
15515 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
15516 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
15517 Write the output into @var{output_file}.
15518 If @var{output_file} already exists, @command{gnatpp} terminates without
15519 reading or processing the input file.
15520
15521 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
15522 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
15523 Write the output into @var{output_file}, overwriting the existing file
15524 (if one is present).
15525
15526 @item ^-r^/REPLACE^
15527 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
15528 Replace the input source file with the reformatted output, and copy the
15529 original input source into the file whose name is obtained by appending the
15530 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
15531 If a file with this name already exists, @command{gnatpp} terminates without
15532 reading or processing the input file.
15533
15534 @item ^-rf^/OVERRIDING_REPLACE^
15535 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
15536 Like @option{^-r^/REPLACE^} except that if the file with the specified name
15537 already exists, it is overwritten.
15538
15539 @item ^-rnb^/NO_BACKUP^
15540 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
15541 Replace the input source file with the reformatted output without
15542 creating any backup copy of the input source.
15543
15544 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
15545 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
15546 Specifies the format of the reformatted output file. The @var{xxx}
15547 ^string specified with the switch^option^ may be either
15548 @itemize @bullet
15549 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
15550 @item ``@option{^crlf^CRLF^}''
15551 the same as @option{^crlf^CRLF^}
15552 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
15553 @item ``@option{^lf^LF^}''
15554 the same as @option{^unix^UNIX^}
15555 @end itemize
15556
15557 @item ^-W^/RESULT_ENCODING=^@var{e}
15558 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
15559 Specify the wide character encoding method used to write the code in the
15560 result file
15561 @var{e} is one of the following:
15562
15563 @itemize @bullet
15564
15565 @item ^h^HEX^
15566 Hex encoding
15567
15568 @item ^u^UPPER^
15569 Upper half encoding
15570
15571 @item ^s^SHIFT_JIS^
15572 Shift/JIS encoding
15573
15574 @item ^e^EUC^
15575 EUC encoding
15576
15577 @item ^8^UTF8^
15578 UTF-8 encoding
15579
15580 @item ^b^BRACKETS^
15581 Brackets encoding (default value)
15582 @end itemize
15583
15584 @end table
15585
15586 @noindent
15587 Options @option{^-pipe^/STANDARD_OUTPUT^},
15588 @option{^-o^/OUTPUT^} and
15589 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
15590 contains only one file to reformat.
15591 Option
15592 @option{^--eol^/END_OF_LINE^}
15593 and
15594 @option{^-W^/RESULT_ENCODING^}
15595 cannot be used together
15596 with @option{^-pipe^/STANDARD_OUTPUT^} option.
15597
15598 @node Other gnatpp Switches
15599 @subsection Other @code{gnatpp} Switches
15600
15601 @noindent
15602 The additional @command{gnatpp} switches are defined in this subsection.
15603
15604 @table @option
15605 @item ^-files @var{filename}^/FILES=@var{output_file}^
15606 @cindex @option{^-files^/FILES^} (@code{gnatpp})
15607 Take the argument source files from the specified file. This file should be an
15608 ordinary textual file containing file names separated by spaces or
15609 line breaks. You can use this switch more then once in the same call to
15610 @command{gnatpp}. You also can combine this switch with explicit list of
15611 files.
15612
15613 @item ^-v^/VERBOSE^
15614 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
15615 Verbose mode;
15616 @command{gnatpp} generates version information and then
15617 a trace of the actions it takes to produce or obtain the ASIS tree.
15618
15619 @item ^-w^/WARNINGS^
15620 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
15621 Warning mode;
15622 @command{gnatpp} generates a warning whenever it cannot provide
15623 a required layout in the result source.
15624 @end table
15625
15626 @node Formatting Rules
15627 @section Formatting Rules
15628
15629 @noindent
15630 The following subsections show how @command{gnatpp} treats ``white space'',
15631 comments, program layout, and name casing.
15632 They provide the detailed descriptions of the switches shown above.
15633
15634 @menu
15635 * White Space and Empty Lines::
15636 * Formatting Comments::
15637 * Construct Layout::
15638 * Name Casing::
15639 @end menu
15640
15641 @node White Space and Empty Lines
15642 @subsection White Space and Empty Lines
15643
15644 @noindent
15645 @command{gnatpp} does not have an option to control space characters.
15646 It will add or remove spaces according to the style illustrated by the
15647 examples in the @cite{Ada Reference Manual}.
15648
15649 The only format effectors
15650 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
15651 that will appear in the output file are platform-specific line breaks,
15652 and also format effectors within (but not at the end of) comments.
15653 In particular, each horizontal tab character that is not inside
15654 a comment will be treated as a space and thus will appear in the
15655 output file as zero or more spaces depending on
15656 the reformatting of the line in which it appears.
15657 The only exception is a Form Feed character, which is inserted after a
15658 pragma @code{Page} when @option{-ff} is set.
15659
15660 The output file will contain no lines with trailing ``white space'' (spaces,
15661 format effectors).
15662
15663 Empty lines in the original source are preserved
15664 only if they separate declarations or statements.
15665 In such contexts, a
15666 sequence of two or more empty lines is replaced by exactly one empty line.
15667 Note that a blank line will be removed if it separates two ``comment blocks''
15668 (a comment block is a sequence of whole-line comments).
15669 In order to preserve a visual separation between comment blocks, use an
15670 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
15671 Likewise, if for some reason you wish to have a sequence of empty lines,
15672 use a sequence of empty comments instead.
15673
15674 @node Formatting Comments
15675 @subsection Formatting Comments
15676
15677 @noindent
15678 Comments in Ada code are of two kinds:
15679 @itemize @bullet
15680 @item
15681 a @emph{whole-line comment}, which appears by itself (possibly preceded by
15682 ``white space'') on a line
15683
15684 @item
15685 an @emph{end-of-line comment}, which follows some other Ada lexical element
15686 on the same line.
15687 @end itemize
15688
15689 @noindent
15690 The indentation of a whole-line comment is that of either
15691 the preceding or following line in
15692 the formatted source, depending on switch settings as will be described below.
15693
15694 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
15695 between the end of the preceding Ada lexical element and the beginning
15696 of the comment as appear in the original source,
15697 unless either the comment has to be split to
15698 satisfy the line length limitation, or else the next line contains a
15699 whole line comment that is considered a continuation of this end-of-line
15700 comment (because it starts at the same position).
15701 In the latter two
15702 cases, the start of the end-of-line comment is moved right to the nearest
15703 multiple of the indentation level.
15704 This may result in a ``line overflow'' (the right-shifted comment extending
15705 beyond the maximum line length), in which case the comment is split as
15706 described below.
15707
15708 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15709 (GNAT-style comment line indentation)
15710 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15711 (reference-manual comment line indentation).
15712 With reference-manual style, a whole-line comment is indented as if it
15713 were a declaration or statement at the same place
15714 (i.e., according to the indentation of the preceding line(s)).
15715 With GNAT style, a whole-line comment that is immediately followed by an
15716 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15717 word @b{begin}, is indented based on the construct that follows it.
15718
15719 For example:
15720 @smallexample @c ada
15721 @cartouche
15722 if A then
15723     null;
15724        -- some comment
15725 else
15726    null;
15727 end if;
15728 @end cartouche
15729 @end smallexample
15730
15731 @noindent
15732 Reference-manual indentation produces:
15733
15734 @smallexample @c ada
15735 @cartouche
15736 if A then
15737    null;
15738    --  some comment
15739 else
15740    null;
15741 end if;
15742 @end cartouche
15743 @end smallexample
15744
15745 @noindent
15746 while GNAT-style indentation produces:
15747
15748 @smallexample @c ada
15749 @cartouche
15750 if A then
15751    null;
15752 --  some comment
15753 else
15754    null;
15755 end if;
15756 @end cartouche
15757 @end smallexample
15758
15759 @noindent
15760 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15761 (GNAT style comment beginning) has the following
15762 effect:
15763
15764 @itemize @bullet
15765 @item
15766 For each whole-line comment that does not end with two hyphens,
15767 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15768 to ensure that there are at least two spaces between these hyphens and the
15769 first non-blank character of the comment.
15770 @end itemize
15771
15772 @noindent
15773 For an end-of-line comment, if in the original source the next line is a
15774 whole-line comment that starts at the same position
15775 as the end-of-line comment,
15776 then the whole-line comment (and all whole-line comments
15777 that follow it and that start at the same position)
15778 will start at this position in the output file.
15779
15780 @noindent
15781 That is, if in the original source we have:
15782
15783 @smallexample @c ada
15784 @cartouche
15785 begin
15786 A := B + C;            --  B must be in the range Low1..High1
15787                        --  C must be in the range Low2..High2
15788              --B+C will be in the range Low1+Low2..High1+High2
15789 X := X + 1;
15790 @end cartouche
15791 @end smallexample
15792
15793 @noindent
15794 Then in the formatted source we get
15795
15796 @smallexample @c ada
15797 @cartouche
15798 begin
15799    A := B + C;            --  B must be in the range Low1..High1
15800                           --  C must be in the range Low2..High2
15801    --  B+C will be in the range Low1+Low2..High1+High2
15802    X := X + 1;
15803 @end cartouche
15804 @end smallexample
15805
15806 @noindent
15807 A comment that exceeds the line length limit will be split.
15808 Unless switch
15809 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15810 the line belongs to a reformattable block, splitting the line generates a
15811 @command{gnatpp} warning.
15812 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15813 comments may be reformatted in typical
15814 word processor style (that is, moving words between lines and putting as
15815 many words in a line as possible).
15816
15817 @node Construct Layout
15818 @subsection Construct Layout
15819
15820 @noindent
15821 In several cases the suggested layout in the Ada Reference Manual includes
15822 an extra level of indentation that many programmers prefer to avoid. The
15823 affected cases include:
15824
15825 @itemize @bullet
15826
15827 @item Record type declaration (RM 3.8)
15828
15829 @item Record representation clause (RM 13.5.1)
15830
15831 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
15832
15833 @item Block statement in case if a block has a statement identifier (RM 5.6)
15834 @end itemize
15835
15836 @noindent
15837 In compact mode (when GNAT style layout or compact layout is set),
15838 the pretty printer uses one level of indentation instead
15839 of two. This is achieved in the record definition and record representation
15840 clause cases by putting the @code{record} keyword on the same line as the
15841 start of the declaration or representation clause, and in the block and loop
15842 case by putting the block or loop header on the same line as the statement
15843 identifier.
15844
15845 @noindent
15846 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15847 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15848 layout on the one hand, and uncompact layout
15849 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15850 can be illustrated by the following examples:
15851
15852 @iftex
15853 @cartouche
15854 @multitable @columnfractions .5 .5
15855 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15856
15857 @item
15858 @smallexample @c ada
15859 type q is record
15860    a : integer;
15861    b : integer;
15862 end record;
15863 @end smallexample
15864 @tab
15865 @smallexample @c ada
15866 type q is
15867    record
15868       a : integer;
15869       b : integer;
15870    end record;
15871 @end smallexample
15872
15873 @item
15874 @smallexample @c ada
15875 for q use record
15876    a at 0 range  0 .. 31;
15877    b at 4 range  0 .. 31;
15878 end record;
15879 @end smallexample
15880 @tab
15881 @smallexample @c ada
15882 for q use
15883    record
15884       a at 0 range  0 .. 31;
15885       b at 4 range  0 .. 31;
15886    end record;
15887 @end smallexample
15888
15889 @item
15890 @smallexample @c ada
15891 Block : declare
15892    A : Integer := 3;
15893 begin
15894    Proc (A, A);
15895 end Block;
15896 @end smallexample
15897 @tab
15898 @smallexample @c ada
15899 Block :
15900    declare
15901       A : Integer := 3;
15902    begin
15903       Proc (A, A);
15904    end Block;
15905 @end smallexample
15906
15907 @item
15908 @smallexample @c ada
15909 Clear : for J in 1 .. 10 loop
15910    A (J) := 0;
15911 end loop Clear;
15912 @end smallexample
15913 @tab
15914 @smallexample @c ada
15915 Clear :
15916    for J in 1 .. 10 loop
15917       A (J) := 0;
15918    end loop Clear;
15919 @end smallexample
15920 @end multitable
15921 @end cartouche
15922 @end iftex
15923
15924 @ifnottex
15925 @smallexample
15926 @cartouche
15927 GNAT style, compact layout              Uncompact layout
15928
15929 type q is record                        type q is
15930    a : integer;                            record
15931    b : integer;                               a : integer;
15932 end record;                                   b : integer;
15933                                            end record;
15934
15935 for q use record                        for q use
15936    a at 0 range  0 .. 31;                  record
15937    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
15938 end record;                                   b at 4 range  0 .. 31;
15939                                            end record;
15940
15941 Block : declare                         Block :
15942    A : Integer := 3;                       declare
15943 begin                                         A : Integer := 3;
15944    Proc (A, A);                            begin
15945 end Block;                                    Proc (A, A);
15946                                            end Block;
15947
15948 Clear : for J in 1 .. 10 loop           Clear :
15949    A (J) := 0;                             for J in 1 .. 10 loop
15950 end loop Clear;                               A (J) := 0;
15951                                            end loop Clear;
15952 @end cartouche
15953 @end smallexample
15954 @end ifnottex
15955
15956 @noindent
15957 A further difference between GNAT style layout and compact layout is that
15958 GNAT style layout inserts empty lines as separation for
15959 compound statements, return statements and bodies.
15960
15961 @node Name Casing
15962 @subsection Name Casing
15963
15964 @noindent
15965 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15966 the same casing as the corresponding defining identifier.
15967
15968 You control the casing for defining occurrences via the
15969 @option{^-n^/NAME_CASING^} switch.
15970 @ifclear vms
15971 With @option{-nD} (``as declared'', which is the default),
15972 @end ifclear
15973 @ifset vms
15974 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15975 @end ifset
15976 defining occurrences appear exactly as in the source file
15977 where they are declared.
15978 The other ^values for this switch^options for this qualifier^ ---
15979 @option{^-nU^UPPER_CASE^},
15980 @option{^-nL^LOWER_CASE^},
15981 @option{^-nM^MIXED_CASE^} ---
15982 result in
15983 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15984 If @command{gnatpp} changes the casing of a defining
15985 occurrence, it analogously changes the casing of all the
15986 usage occurrences of this name.
15987
15988 If the defining occurrence of a name is not in the source compilation unit
15989 currently being processed by @command{gnatpp}, the casing of each reference to
15990 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15991 switch (subject to the dictionary file mechanism described below).
15992 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15993 had affected the
15994 casing for the defining occurrence of the name.
15995
15996 Some names may need to be spelled with casing conventions that are not
15997 covered by the upper-, lower-, and mixed-case transformations.
15998 You can arrange correct casing by placing such names in a
15999 @emph{dictionary file},
16000 and then supplying a @option{^-D^/DICTIONARY^} switch.
16001 The casing of names from dictionary files overrides
16002 any @option{^-n^/NAME_CASING^} switch.
16003
16004 To handle the casing of Ada predefined names and the names from GNAT libraries,
16005 @command{gnatpp} assumes a default dictionary file.
16006 The name of each predefined entity is spelled with the same casing as is used
16007 for the entity in the @cite{Ada Reference Manual}.
16008 The name of each entity in the GNAT libraries is spelled with the same casing
16009 as is used in the declaration of that entity.
16010
16011 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
16012 default dictionary file.
16013 Instead, the casing for predefined and GNAT-defined names will be established
16014 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
16015 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
16016 will appear as just shown,
16017 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
16018 To ensure that even such names are rendered in uppercase,
16019 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
16020 (or else, less conveniently, place these names in upper case in a dictionary
16021 file).
16022
16023 A dictionary file is
16024 a plain text file; each line in this file can be either a blank line
16025 (containing only space characters and ASCII.HT characters), an Ada comment
16026 line, or the specification of exactly one @emph{casing schema}.
16027
16028 A casing schema is a string that has the following syntax:
16029
16030 @smallexample
16031 @cartouche
16032   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
16033
16034   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
16035 @end cartouche
16036 @end smallexample
16037
16038 @noindent
16039 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
16040 @var{identifier} lexical element and the @var{letter_or_digit} category.)
16041
16042 The casing schema string can be followed by white space and/or an Ada-style
16043 comment; any amount of white space is allowed before the string.
16044
16045 If a dictionary file is passed as
16046 @ifclear vms
16047 the value of a @option{-D@var{file}} switch
16048 @end ifclear
16049 @ifset vms
16050 an option to the @option{/DICTIONARY} qualifier
16051 @end ifset
16052 then for every
16053 simple name and every identifier, @command{gnatpp} checks if the dictionary
16054 defines the casing for the name or for some of its parts (the term ``subword''
16055 is used below to denote the part of a name which is delimited by ``_'' or by
16056 the beginning or end of the word and which does not contain any ``_'' inside):
16057
16058 @itemize @bullet
16059 @item
16060 if the whole name is in the dictionary, @command{gnatpp} uses for this name
16061 the casing defined by the dictionary; no subwords are checked for this word
16062
16063 @item
16064 for every subword @command{gnatpp} checks if the dictionary contains the
16065 corresponding string of the form @code{*@var{simple_identifier}*},
16066 and if it does, the casing of this @var{simple_identifier} is used
16067 for this subword
16068
16069 @item
16070 if the whole name does not contain any ``_'' inside, and if for this name
16071 the dictionary contains two entries - one of the form @var{identifier},
16072 and another - of the form *@var{simple_identifier}*, then the first one
16073 is applied to define the casing of this name
16074
16075 @item
16076 if more than one dictionary file is passed as @command{gnatpp} switches, each
16077 dictionary adds new casing exceptions and overrides all the existing casing
16078 exceptions set by the previous dictionaries
16079
16080 @item
16081 when @command{gnatpp} checks if the word or subword is in the dictionary,
16082 this check is not case sensitive
16083 @end itemize
16084
16085 @noindent
16086 For example, suppose we have the following source to reformat:
16087
16088 @smallexample @c ada
16089 @cartouche
16090 procedure test is
16091    name1 : integer := 1;
16092    name4_name3_name2 : integer := 2;
16093    name2_name3_name4 : Boolean;
16094    name1_var : Float;
16095 begin
16096    name2_name3_name4 := name4_name3_name2 > name1;
16097 end;
16098 @end cartouche
16099 @end smallexample
16100
16101 @noindent
16102 And suppose we have two dictionaries:
16103
16104 @smallexample
16105 @cartouche
16106 @i{dict1:}
16107    NAME1
16108    *NaMe3*
16109    *Name1*
16110 @end cartouche
16111
16112 @cartouche
16113 @i{dict2:}
16114   *NAME3*
16115 @end cartouche
16116 @end smallexample
16117
16118 @noindent
16119 If @command{gnatpp} is called with the following switches:
16120
16121 @smallexample
16122 @ifclear vms
16123 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
16124 @end ifclear
16125 @ifset vms
16126 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
16127 @end ifset
16128 @end smallexample
16129
16130 @noindent
16131 then we will get the following name casing in the @command{gnatpp} output:
16132
16133 @smallexample @c ada
16134 @cartouche
16135 procedure Test is
16136    NAME1             : Integer := 1;
16137    Name4_NAME3_Name2 : Integer := 2;
16138    Name2_NAME3_Name4 : Boolean;
16139    Name1_Var         : Float;
16140 begin
16141    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
16142 end Test;
16143 @end cartouche
16144 @end smallexample
16145
16146 @c *********************************
16147 @node The GNAT Metric Tool gnatmetric
16148 @chapter The GNAT Metric Tool @command{gnatmetric}
16149 @findex gnatmetric
16150 @cindex Metric tool
16151
16152 @noindent
16153 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
16154 for computing various program metrics.
16155 It takes an Ada source file as input and generates a file containing the
16156 metrics data as output. Various switches control which
16157 metrics are computed and output.
16158
16159 @command{gnatmetric} generates and uses the ASIS
16160 tree for the input source and thus requires the input to be syntactically and
16161 semantically legal.
16162 If this condition is not met, @command{gnatmetric} will generate
16163 an error message; no metric information for this file will be
16164 computed and reported.
16165
16166 If the compilation unit contained in the input source depends semantically
16167 upon units in files located outside the current directory, you have to provide
16168 the source search path when invoking @command{gnatmetric}.
16169 If it depends semantically upon units that are contained
16170 in files with names that do not follow the GNAT file naming rules, you have to
16171 provide the configuration file describing the corresponding naming scheme (see
16172 the description of the @command{gnatmetric} switches below.)
16173 Alternatively, you may use a project file and invoke @command{gnatmetric}
16174 through the @command{gnat} driver.
16175
16176 The @command{gnatmetric} command has the form
16177
16178 @smallexample
16179 $ gnatmetric [@i{switches}] @{@i{filename}@} [@i{-cargs gcc_switches}]
16180 @end smallexample
16181
16182 @noindent
16183 where
16184 @itemize @bullet
16185 @item
16186 @i{switches} specify the metrics to compute and define the destination for
16187 the output
16188
16189 @item
16190 Each @i{filename} is the name (including the extension) of a source
16191 file to process. ``Wildcards'' are allowed, and
16192 the file name may contain path information.
16193 If no @i{filename} is supplied, then the @i{switches} list must contain
16194 at least one
16195 @option{-files} switch (@pxref{Other gnatmetric Switches}).
16196 Including both a @option{-files} switch and one or more
16197 @i{filename} arguments is permitted.
16198
16199 @item
16200 @i{-cargs gcc_switches} is a list of switches for
16201 @command{gcc}. They will be passed on to all compiler invocations made by
16202 @command{gnatmetric} to generate the ASIS trees. Here you can provide
16203 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
16204 and use the @option{-gnatec} switch to set the configuration file.
16205 @end itemize
16206
16207 @menu
16208 * Switches for gnatmetric::
16209 @end menu
16210
16211 @node Switches for gnatmetric
16212 @section Switches for @command{gnatmetric}
16213
16214 @noindent
16215 The following subsections describe the various switches accepted by
16216 @command{gnatmetric}, organized by category.
16217
16218 @menu
16219 * Output Files Control::
16220 * Disable Metrics For Local Units::
16221 * Line Metrics Control::
16222 * Syntax Metrics Control::
16223 * Complexity Metrics Control::
16224 * Other gnatmetric Switches::
16225 * Generate project-wide metrics::
16226 @end menu
16227
16228 @node Output Files Control
16229 @subsection Output File Control
16230 @cindex Output file control in @command{gnatmetric}
16231
16232 @noindent
16233 @command{gnatmetric} has two output formats. It can generate a
16234 textual (human-readable) form, and also XML. By default only textual
16235 output is generated.
16236
16237 When generating the output in textual form, @command{gnatmetric} creates
16238 for each Ada source file a corresponding text file
16239 containing the computed metrics. By default, this file
16240 is placed in the same directory as where the source file is located, and
16241 its name is obtained
16242 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
16243 input file.
16244
16245 All the output information generated in XML format is placed in a single
16246 file. By default this file is placed in the current directory and has the
16247 name ^@file{metrix.xml}^@file{METRIX$XML}^.
16248
16249 Some of the computed metrics are summed over the units passed to
16250 @command{gnatmetric}; for example, the total number of lines of code.
16251 By default this information is sent to @file{stdout}, but a file
16252 can be specified with the @option{-og} switch.
16253
16254 The following switches control the @command{gnatmetric} output:
16255
16256 @table @option
16257 @cindex @option{^-x^/XML^} (@command{gnatmetric})
16258 @item ^-x^/XML^
16259 Generate the XML output
16260
16261 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
16262 @item ^-nt^/NO_TEXT^
16263 Do not generate the output in text form (implies @option{^-x^/XML^})
16264
16265 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
16266 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
16267 Put textual files with detailed metrics into @var{output_dir}
16268
16269 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
16270 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
16271 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
16272 in the name of the output file.
16273
16274 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
16275 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
16276 Put global metrics into @var{file_name}
16277
16278 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
16279 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
16280 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
16281
16282 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
16283 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
16284 Use ``short'' source file names in the output.  (The @command{gnatmetric}
16285 output includes the name(s) of the Ada source file(s) from which the metrics
16286 are computed.  By default each name includes the absolute path. The
16287 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
16288 to exclude all directory information from the file names that are output.)
16289
16290 @end table
16291
16292 @node Disable Metrics For Local Units
16293 @subsection Disable Metrics For Local Units
16294 @cindex Disable Metrics For Local Units in @command{gnatmetric}
16295
16296 @noindent
16297 @command{gnatmetric} relies on the GNAT compilation model @minus{}
16298 one compilation
16299 unit per one source file. It computes line metrics for the whole source
16300 file, and it also computes syntax
16301 and complexity metrics for the file's outermost unit.
16302
16303 By default, @command{gnatmetric} will also compute all metrics for certain
16304 kinds of locally declared program units:
16305
16306 @itemize @bullet
16307 @item
16308 subprogram (and generic subprogram) bodies;
16309
16310 @item
16311 package (and generic package) specifications and bodies;
16312
16313 @item
16314 task object and type specifications and bodies;
16315
16316 @item
16317 protected object and type specifications and bodies.
16318 @end itemize
16319
16320 @noindent
16321 These kinds of entities will be referred to as
16322 @emph{eligible local program units}, or simply @emph{eligible local units},
16323 @cindex Eligible local unit (for @command{gnatmetric})
16324 in the discussion below.
16325
16326 Note that a subprogram declaration, generic instantiation,
16327 or renaming declaration only receives metrics
16328 computation when it appear as the outermost entity
16329 in a source file.
16330
16331 Suppression of metrics computation for eligible local units can be
16332 obtained via the following switch:
16333
16334 @table @option
16335 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16336 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
16337 Do not compute detailed metrics for eligible local program units
16338
16339 @end table
16340
16341 @node Line Metrics Control
16342 @subsection Line Metrics Control
16343 @cindex Line metrics control in @command{gnatmetric}
16344
16345 @noindent
16346 For any (legal) source file, and for each of its
16347 eligible local program units, @command{gnatmetric} computes the following
16348 metrics:
16349
16350 @itemize @bullet
16351 @item
16352 the total number of lines;
16353
16354 @item
16355 the total number of code lines (i.e., non-blank lines that are not comments)
16356
16357 @item
16358 the number of comment lines
16359
16360 @item
16361 the number of code lines containing end-of-line comments;
16362
16363 @item
16364 the number of empty lines and lines containing only space characters and/or
16365 format effectors (blank lines)
16366
16367 @end itemize
16368
16369 If @command{gnatmetric} is invoked on more than one source file, it sums the
16370 values of the line metrics for all the files being processed and then
16371 generates the cumulative results.
16372
16373 By default, all the line metrics are computed and reported. You can use the
16374 following switches to select the specific line metrics to be computed and
16375 reported (if any of these parameters is set, only explicitly specified line
16376 metrics are computed).
16377
16378 @table @option
16379 @cindex @option{^-la^/LINES_ALL^} (@command{gnatmetric})
16380 @item ^-la^/LINES_ALL^
16381 The number of all lines
16382
16383 @cindex @option{^-lcode^/CODE_LINES^} (@command{gnatmetric})
16384 @item ^-lcode^/CODE_LINES^
16385 The number of code lines
16386
16387 @cindex @option{^-lcomm^/COMMENT_LINES^} (@command{gnatmetric})
16388 @item ^-lcomm^/COMENT_LINES^
16389 The number of comment lines
16390
16391 @cindex @option{^-leol^/MIXED_CODE_COMMENTS^} (@command{gnatmetric})
16392 @item ^-leol^/MIXED_CODE_COMMENTS^
16393 The number of code lines containing
16394 end-of-line comments
16395
16396 @cindex @option{^-lb^/BLANK_LINES^} (@command{gnatmetric})
16397 @item ^-lb^/BLANK_LINES^
16398 The number of blank lines
16399
16400 @end table
16401
16402 @node Syntax Metrics Control
16403 @subsection Syntax Metrics Control
16404 @cindex Syntax metrics control in @command{gnatmetric}
16405
16406 @noindent
16407 @command{gnatmetric} computes various syntactic metrics for the
16408 outermost unit and for each eligible local unit:
16409
16410 @table @emph
16411 @item LSLOC (``Logical Source Lines Of Code'')
16412 The total number of declarations and the total number of statements
16413
16414 @item Maximal static nesting level of inner program units
16415 According to
16416 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
16417 package, a task unit, a protected unit, a
16418 protected entry, a generic unit, or an explicitly declared subprogram other
16419 than an enumeration literal.''
16420
16421 @item Maximal nesting level of composite syntactic constructs
16422 This corresponds to the notion of the
16423 maximum nesting level in the GNAT built-in style checks
16424 (@pxref{Style Checking})
16425 @end table
16426
16427 @noindent
16428 For the outermost unit in the file, @command{gnatmetric} additionally computes
16429 the following metrics:
16430
16431 @table @emph
16432 @item Public subprograms
16433 This metric is computed for package specifications. It is the
16434 number of subprograms and generic subprograms declared in the visible
16435 part (including in nested packages, protected objects, and
16436 protected types).
16437
16438 @item All subprograms
16439 This metric is computed for bodies and subunits. The
16440 metric is equal to a total number of subprogram bodies in the compilation
16441 unit.
16442 Neither generic instantiations nor renamings-as-a-body nor body stubs
16443 are counted. Any subprogram body is counted, independently of its nesting
16444 level and enclosing constructs. Generic bodies and bodies of protected
16445 subprograms are counted in the same way as ``usual'' subprogram bodies.
16446
16447 @item Public types
16448 This metric is computed for package specifications and
16449 generic package declarations. It is the total number of types
16450 that can be referenced from outside this compilation unit, plus the
16451 number of types from all the visible parts of all the visible generic packages.
16452 Generic formal types are not counted.  Only types, not subtypes,
16453 are included.
16454
16455 @noindent
16456 Along with the total number of public types, the following
16457 types are counted and reported separately:
16458
16459 @itemize @bullet
16460 @item
16461 Abstract types
16462
16463 @item
16464 Root tagged types (abstract, non-abstract, private, non-private). Type
16465 extensions are @emph{not} counted
16466
16467 @item
16468 Private types (including private extensions)
16469
16470 @item
16471 Task types
16472
16473 @item
16474 Protected types
16475
16476 @end itemize
16477
16478 @item All types
16479 This metric is computed for any compilation unit. It is equal to the total
16480 number of the declarations of different types given in the compilation unit.
16481 The private and the corresponding full type declaration are counted as one
16482 type declaration. Incomplete type declarations and generic formal types
16483 are not counted.
16484 No distinction is made among different kinds of types (abstract,
16485 private etc.); the total number of types is computed and reported.
16486
16487 @end table
16488
16489 @noindent
16490 By default, all the syntax metrics are computed and reported. You can use the
16491 following switches to select specific syntax metrics;
16492 if any of these is set, only the explicitly specified metrics are computed.
16493
16494 @table @option
16495 @cindex @option{^-ed^/DECLARATION_TOTAL^} (@command{gnatmetric})
16496 @item ^-ed^/DECLARATION_TOTAL^
16497 The total number of declarations
16498
16499 @cindex @option{^-es^/STATEMENT_TOTAL^} (@command{gnatmetric})
16500 @item ^-es^/STATEMENT_TOTAL^
16501 The total number of statements
16502
16503 @cindex @option{^-eps^/^} (@command{gnatmetric})
16504 @item ^-eps^/INT_SUBPROGRAMS^
16505 The number of public subprograms in a compilation unit
16506
16507 @cindex @option{^-eas^/SUBPROGRAMS_ALL^} (@command{gnatmetric})
16508 @item ^-eas^/SUBPROGRAMS_ALL^
16509 The number of all the subprograms in a compilation unit
16510
16511 @cindex @option{^-ept^/INT_TYPES^} (@command{gnatmetric})
16512 @item ^-ept^/INT_TYPES^
16513 The number of public types in a compilation unit
16514
16515 @cindex @option{^-eat^/TYPES_ALL^} (@command{gnatmetric})
16516 @item ^-eat^/TYPES_ALL^
16517 The number of all the types in a compilation unit
16518
16519 @cindex @option{^-enu^/PROGRAM_NESTING_MAX^} (@command{gnatmetric})
16520 @item ^-enu^/PROGRAM_NESTING_MAX^
16521 The maximal program unit nesting level
16522
16523 @cindex @option{^-ec^/CONSTRUCT_NESTING_MAX^} (@command{gnatmetric})
16524 @item ^-ec^/CONSTRUCT_NESTING_MAX^
16525 The maximal construct nesting level
16526
16527 @end table
16528
16529 @node Complexity Metrics Control
16530 @subsection Complexity Metrics Control
16531 @cindex Complexity metrics control in @command{gnatmetric}
16532
16533 @noindent
16534 For a program unit that is an executable body (a subprogram body (including
16535 generic bodies), task body, entry body or a package body containing
16536 its own statement sequence ) @command{gnatmetric} computes the following
16537 complexity metrics:
16538
16539 @itemize @bullet
16540 @item
16541 McCabe cyclomatic complexity;
16542
16543 @item
16544 McCabe essential complexity;
16545
16546 @item
16547 maximal loop nesting level
16548
16549 @end itemize
16550
16551 @noindent
16552 The McCabe complexity metrics are defined
16553 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
16554
16555 According to McCabe, both control statements and short-circuit control forms
16556 should be taken into account when computing cyclomatic complexity. For each
16557 body, we compute three metric values:
16558
16559 @itemize @bullet
16560 @item
16561 the complexity introduced by control
16562 statements only, without taking into account short-circuit forms,
16563
16564 @item
16565 the complexity introduced by short-circuit control forms only, and
16566
16567 @item
16568 the total
16569 cyclomatic complexity, which is the sum of these two values.
16570 @end itemize
16571
16572 @noindent
16573 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16574 the code in the exception handlers and in all the nested program units.
16575
16576 By default, all the complexity metrics are computed and reported.
16577 For more finely-grained control you can use
16578 the following switches:
16579
16580 @table @option
16581 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16582
16583 @item ^-nocc^/SUPPRESS=CYCLOMATIC_COMPLEXITY^
16584 Do not compute the McCabe Cyclomatic Complexity
16585
16586 @item ^-noec^/SUPPRESS=ESSENTIAL_COMPLEXITY^
16587 Do not compute the Essential Complexity
16588
16589 @item ^-nonl^/SUPPRESS=MAXIMAL_LOOP_NESTING^
16590 Do not compute maximal loop nesting level
16591
16592 @item ^-ne^/SUPPRESS=EXITS_AS_GOTOS^
16593 Do not consider @code{exit} statements as @code{goto}s when
16594 computing Essential Complexity
16595
16596 @end table
16597
16598 @node Other gnatmetric Switches
16599 @subsection Other @code{gnatmetric} Switches
16600
16601 @noindent
16602 Additional @command{gnatmetric} switches are as follows:
16603
16604 @table @option
16605 @item ^-files @var{filename}^/FILES=@var{filename}^
16606 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16607 Take the argument source files from the specified file. This file should be an
16608 ordinary textual file containing file names separated by spaces or
16609 line breaks. You can use this switch more then once in the same call to
16610 @command{gnatmetric}. You also can combine this switch with
16611 an explicit list of files.
16612
16613 @item ^-v^/VERBOSE^
16614 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16615 Verbose mode;
16616 @command{gnatmetric} generates version information and then
16617 a trace of sources being processed.
16618
16619 @item ^-dv^/DEBUG_OUTPUT^
16620 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
16621 Debug mode;
16622 @command{gnatmetric} generates various messages useful to understand what
16623 happens during the metrics computation
16624
16625 @item ^-q^/QUIET^
16626 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16627 Quiet mode.
16628 @end table
16629
16630 @node Generate project-wide metrics
16631 @subsection Generate project-wide metrics
16632
16633 In order to compute metrics on all units of a given project, one can use
16634 the @command{gnat} driver along with the @option{-P} option:
16635 @smallexample
16636    gnat metric -Pproj
16637 @end smallexample
16638 If the project @code{proj} depends upon other projects, one can compute
16639 the metrics on the project closure using the @option{-U} option:
16640 @smallexample
16641    gnat metric -Pproj -U
16642 @end smallexample
16643 Finally, if not all the units are relevant to a particular main
16644 program in the project closure, one can generate metrics for the set
16645 of units needed to create a given main program (unit closure) using
16646 the @option{-U} option followed by the name of the main unit:
16647 @smallexample
16648    gnat metric -Pproj -U main
16649 @end smallexample
16650
16651
16652 @c ***********************************
16653 @node File Name Krunching Using gnatkr
16654 @chapter File Name Krunching Using @code{gnatkr}
16655 @findex gnatkr
16656
16657 @noindent
16658 This chapter discusses the method used by the compiler to shorten
16659 the default file names chosen for Ada units so that they do not
16660 exceed the maximum length permitted. It also describes the
16661 @code{gnatkr} utility that can be used to determine the result of
16662 applying this shortening.
16663 @menu
16664 * About gnatkr::
16665 * Using gnatkr::
16666 * Krunching Method::
16667 * Examples of gnatkr Usage::
16668 @end menu
16669
16670 @node About gnatkr
16671 @section About @code{gnatkr}
16672
16673 @noindent
16674 The default file naming rule in GNAT
16675 is that the file name must be derived from
16676 the unit name. The exact default rule is as follows:
16677 @itemize @bullet
16678 @item
16679 Take the unit name and replace all dots by hyphens.
16680 @item
16681 If such a replacement occurs in the
16682 second character position of a name, and the first character is
16683 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
16684 ^~ (tilde)^$ (dollar sign)^
16685 instead of a minus.
16686 @end itemize
16687 The reason for this exception is to avoid clashes
16688 with the standard names for children of System, Ada, Interfaces,
16689 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
16690 respectively.
16691
16692 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16693 switch of the compiler activates a ``krunching''
16694 circuit that limits file names to nn characters (where nn is a decimal
16695 integer). For example, using OpenVMS,
16696 where the maximum file name length is
16697 39, the value of nn is usually set to 39, but if you want to generate
16698 a set of files that would be usable if ported to a system with some
16699 different maximum file length, then a different value can be specified.
16700 The default value of 39 for OpenVMS need not be specified.
16701
16702 The @code{gnatkr} utility can be used to determine the krunched name for
16703 a given file, when krunched to a specified maximum length.
16704
16705 @node Using gnatkr
16706 @section Using @code{gnatkr}
16707
16708 @noindent
16709 The @code{gnatkr} command has the form
16710
16711 @ifclear vms
16712 @smallexample
16713 $ gnatkr @var{name} [@var{length}]
16714 @end smallexample
16715 @end ifclear
16716
16717 @ifset vms
16718 @smallexample
16719 $ gnatkr @var{name} /COUNT=nn
16720 @end smallexample
16721 @end ifset
16722
16723 @noindent
16724 @var{name} is the uncrunched file name, derived from the name of the unit
16725 in the standard manner described in the previous section (i.e. in particular
16726 all dots are replaced by hyphens). The file name may or may not have an
16727 extension (defined as a suffix of the form period followed by arbitrary
16728 characters other than period). If an extension is present then it will
16729 be preserved in the output. For example, when krunching @file{hellofile.ads}
16730 to eight characters, the result will be hellofil.ads.
16731
16732 Note: for compatibility with previous versions of @code{gnatkr} dots may
16733 appear in the name instead of hyphens, but the last dot will always be
16734 taken as the start of an extension. So if @code{gnatkr} is given an argument
16735 such as @file{Hello.World.adb} it will be treated exactly as if the first
16736 period had been a hyphen, and for example krunching to eight characters
16737 gives the result @file{hellworl.adb}.
16738
16739 Note that the result is always all lower case (except on OpenVMS where it is
16740 all upper case). Characters of the other case are folded as required.
16741
16742 @var{length} represents the length of the krunched name. The default
16743 when no argument is given is ^8^39^ characters. A length of zero stands for
16744 unlimited, in other words do not chop except for system files where the
16745 implied crunching length is always eight characters.
16746
16747 @noindent
16748 The output is the krunched name. The output has an extension only if the
16749 original argument was a file name with an extension.
16750
16751 @node Krunching Method
16752 @section Krunching Method
16753
16754 @noindent
16755 The initial file name is determined by the name of the unit that the file
16756 contains. The name is formed by taking the full expanded name of the
16757 unit and replacing the separating dots with hyphens and
16758 using ^lowercase^uppercase^
16759 for all letters, except that a hyphen in the second character position is
16760 replaced by a ^tilde^dollar sign^ if the first character is
16761 ^a, i, g, or s^A, I, G, or S^.
16762 The extension is @code{.ads} for a
16763 specification and @code{.adb} for a body.
16764 Krunching does not affect the extension, but the file name is shortened to
16765 the specified length by following these rules:
16766
16767 @itemize @bullet
16768 @item
16769 The name is divided into segments separated by hyphens, tildes or
16770 underscores and all hyphens, tildes, and underscores are
16771 eliminated. If this leaves the name short enough, we are done.
16772
16773 @item
16774 If the name is too long, the longest segment is located (left-most
16775 if there are two of equal length), and shortened by dropping
16776 its last character. This is repeated until the name is short enough.
16777
16778 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16779 to fit the name into 8 characters as required by some operating systems.
16780
16781 @smallexample
16782 our-strings-wide_fixed 22
16783 our strings wide fixed 19
16784 our string  wide fixed 18
16785 our strin   wide fixed 17
16786 our stri    wide fixed 16
16787 our stri    wide fixe  15
16788 our str     wide fixe  14
16789 our str     wid  fixe  13
16790 our str     wid  fix   12
16791 ou  str     wid  fix   11
16792 ou  st      wid  fix   10
16793 ou  st      wi   fix   9
16794 ou  st      wi   fi    8
16795 Final file name: oustwifi.adb
16796 @end smallexample
16797
16798 @item
16799 The file names for all predefined units are always krunched to eight
16800 characters. The krunching of these predefined units uses the following
16801 special prefix replacements:
16802
16803 @table @file
16804 @item ada-
16805 replaced by @file{^a^A^-}
16806
16807 @item gnat-
16808 replaced by @file{^g^G^-}
16809
16810 @item interfaces-
16811 replaced by @file{^i^I^-}
16812
16813 @item system-
16814 replaced by @file{^s^S^-}
16815 @end table
16816
16817 These system files have a hyphen in the second character position. That
16818 is why normal user files replace such a character with a
16819 ^tilde^dollar sign^, to
16820 avoid confusion with system file names.
16821
16822 As an example of this special rule, consider
16823 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16824
16825 @smallexample
16826 ada-strings-wide_fixed 22
16827 a-  strings wide fixed 18
16828 a-  string  wide fixed 17
16829 a-  strin   wide fixed 16
16830 a-  stri    wide fixed 15
16831 a-  stri    wide fixe  14
16832 a-  str     wide fixe  13
16833 a-  str     wid  fixe  12
16834 a-  str     wid  fix   11
16835 a-  st      wid  fix   10
16836 a-  st      wi   fix   9
16837 a-  st      wi   fi    8
16838 Final file name: a-stwifi.adb
16839 @end smallexample
16840 @end itemize
16841
16842 Of course no file shortening algorithm can guarantee uniqueness over all
16843 possible unit names, and if file name krunching is used then it is your
16844 responsibility to ensure that no name clashes occur. The utility
16845 program @code{gnatkr} is supplied for conveniently determining the
16846 krunched name of a file.
16847
16848 @node Examples of gnatkr Usage
16849 @section Examples of @code{gnatkr} Usage
16850
16851 @smallexample
16852 @iftex
16853 @leftskip=0cm
16854 @end iftex
16855 @ifclear vms
16856 $ gnatkr very_long_unit_name.ads      --> velounna.ads
16857 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16858 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16859 $ gnatkr grandparent-parent-child     --> grparchi
16860 @end ifclear
16861 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16862 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16863 @end smallexample
16864
16865 @node Preprocessing Using gnatprep
16866 @chapter Preprocessing Using @code{gnatprep}
16867 @findex gnatprep
16868
16869 @noindent
16870 The @code{gnatprep} utility provides
16871 a simple preprocessing capability for Ada programs.
16872 It is designed for use with GNAT, but is not dependent on any special
16873 features of GNAT.
16874
16875 @menu
16876 * Using gnatprep::
16877 * Switches for gnatprep::
16878 * Form of Definitions File::
16879 * Form of Input Text for gnatprep::
16880 @end menu
16881
16882 @node Using gnatprep
16883 @section Using @code{gnatprep}
16884
16885 @noindent
16886 To call @code{gnatprep} use
16887
16888 @smallexample
16889 $ gnatprep [switches] infile outfile [deffile]
16890 @end smallexample
16891
16892 @noindent
16893 where
16894 @table @code
16895 @item switches
16896 is an optional sequence of switches as described in the next section.
16897
16898 @item infile
16899 is the full name of the input file, which is an Ada source
16900 file containing preprocessor directives.
16901
16902 @item outfile
16903 is the full name of the output file, which is an Ada source
16904 in standard Ada form. When used with GNAT, this file name will
16905 normally have an ads or adb suffix.
16906
16907 @item deffile
16908 is the full name of a text file containing definitions of
16909 symbols to be referenced by the preprocessor. This argument is
16910 optional, and can be replaced by the use of the @option{-D} switch.
16911
16912 @end table
16913
16914 @node Switches for gnatprep
16915 @section Switches for @code{gnatprep}
16916
16917 @table @option
16918 @c !sort!
16919
16920 @item ^-b^/BLANK_LINES^
16921 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16922 Causes both preprocessor lines and the lines deleted by
16923 preprocessing to be replaced by blank lines in the output source file,
16924 preserving line numbers in the output file.
16925
16926 @item ^-c^/COMMENTS^
16927 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16928 Causes both preprocessor lines and the lines deleted
16929 by preprocessing to be retained in the output source as comments marked
16930 with the special string @code{"--! "}. This option will result in line numbers
16931 being preserved in the output file.
16932
16933 @item ^-C^/REPLACE_IN_COMMENTS^
16934 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16935 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16936 If this option is specified, then comments are scanned and any $symbol
16937 substitutions performed as in program text. This is particularly useful
16938 when structured comments are used (e.g. when writing programs in the
16939 SPARK dialect of Ada). Note that this switch is not available when
16940 doing integrated preprocessing (it would be useless in this context
16941 since comments are ignored by the compiler in any case).
16942
16943 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16944 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16945 Defines a new symbol, associated with value. If no value is given on the
16946 command line, then symbol is considered to be @code{True}. This switch
16947 can be used in place of a definition file.
16948
16949 @ifset vms
16950 @item /REMOVE
16951 @cindex @option{/REMOVE} (@command{gnatprep})
16952 This is the default setting which causes lines deleted by preprocessing
16953 to be entirely removed from the output file.
16954 @end ifset
16955
16956 @item ^-r^/REFERENCE^
16957 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16958 Causes a @code{Source_Reference} pragma to be generated that
16959 references the original input file, so that error messages will use
16960 the file name of this original file. The use of this switch implies
16961 that preprocessor lines are not to be removed from the file, so its
16962 use will force @option{^-b^/BLANK_LINES^} mode if
16963 @option{^-c^/COMMENTS^}
16964 has not been specified explicitly.
16965
16966 Note that if the file to be preprocessed contains multiple units, then
16967 it will be necessary to @code{gnatchop} the output file from
16968 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16969 in the preprocessed file, it will be respected by
16970 @code{gnatchop ^-r^/REFERENCE^}
16971 so that the final chopped files will correctly refer to the original
16972 input source file for @code{gnatprep}.
16973
16974 @item ^-s^/SYMBOLS^
16975 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16976 Causes a sorted list of symbol names and values to be
16977 listed on the standard output file.
16978
16979 @item ^-u^/UNDEFINED^
16980 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16981 Causes undefined symbols to be treated as having the value FALSE in the context
16982 of a preprocessor test. In the absence of this option, an undefined symbol in
16983 a @code{#if} or @code{#elsif} test will be treated as an error.
16984
16985 @end table
16986
16987 @ifclear vms
16988 @noindent
16989 Note: if neither @option{-b} nor @option{-c} is present,
16990 then preprocessor lines and
16991 deleted lines are completely removed from the output, unless -r is
16992 specified, in which case -b is assumed.
16993 @end ifclear
16994
16995 @node Form of Definitions File
16996 @section Form of Definitions File
16997
16998 @noindent
16999 The definitions file contains lines of the form
17000
17001 @smallexample
17002 symbol := value
17003 @end smallexample
17004
17005 @noindent
17006 where symbol is an identifier, following normal Ada (case-insensitive)
17007 rules for its syntax, and value is one of the following:
17008
17009 @itemize @bullet
17010 @item
17011 Empty, corresponding to a null substitution
17012 @item
17013 A string literal using normal Ada syntax
17014 @item
17015 Any sequence of characters from the set
17016 (letters, digits, period, underline).
17017 @end itemize
17018
17019 @noindent
17020 Comment lines may also appear in the definitions file, starting with
17021 the usual @code{--},
17022 and comments may be added to the definitions lines.
17023
17024 @node Form of Input Text for gnatprep
17025 @section Form of Input Text for @code{gnatprep}
17026
17027 @noindent
17028 The input text may contain preprocessor conditional inclusion lines,
17029 as well as general symbol substitution sequences.
17030
17031 The preprocessor conditional inclusion commands have the form
17032
17033 @smallexample
17034 @group
17035 @cartouche
17036 #if @i{expression} [then]
17037    lines
17038 #elsif @i{expression} [then]
17039    lines
17040 #elsif @i{expression} [then]
17041    lines
17042 ...
17043 #else
17044    lines
17045 #end if;
17046 @end cartouche
17047 @end group
17048 @end smallexample
17049
17050 @noindent
17051 In this example, @i{expression} is defined by the following grammar:
17052 @smallexample
17053 @i{expression} ::=  <symbol>
17054 @i{expression} ::=  <symbol> = "<value>"
17055 @i{expression} ::=  <symbol> = <symbol>
17056 @i{expression} ::=  <symbol> 'Defined
17057 @i{expression} ::=  not @i{expression}
17058 @i{expression} ::=  @i{expression} and @i{expression}
17059 @i{expression} ::=  @i{expression} or @i{expression}
17060 @i{expression} ::=  @i{expression} and then @i{expression}
17061 @i{expression} ::=  @i{expression} or else @i{expression}
17062 @i{expression} ::=  ( @i{expression} )
17063 @end smallexample
17064
17065 @noindent
17066 For the first test (@i{expression} ::= <symbol>) the symbol must have
17067 either the value true or false, that is to say the right-hand of the
17068 symbol definition must be one of the (case-insensitive) literals
17069 @code{True} or @code{False}. If the value is true, then the
17070 corresponding lines are included, and if the value is false, they are
17071 excluded.
17072
17073 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
17074 the symbol has been defined in the definition file or by a @option{-D}
17075 switch on the command line. Otherwise, the test is false.
17076
17077 The equality tests are case insensitive, as are all the preprocessor lines.
17078
17079 If the symbol referenced is not defined in the symbol definitions file,
17080 then the effect depends on whether or not switch @option{-u}
17081 is specified. If so, then the symbol is treated as if it had the value
17082 false and the test fails. If this switch is not specified, then
17083 it is an error to reference an undefined symbol. It is also an error to
17084 reference a symbol that is defined with a value other than @code{True}
17085 or @code{False}.
17086
17087 The use of the @code{not} operator inverts the sense of this logical test.
17088 The @code{not} operator cannot be combined with the @code{or} or @code{and}
17089 operators, without parentheses. For example, "if not X or Y then" is not
17090 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
17091
17092 The @code{then} keyword is optional as shown
17093
17094 The @code{#} must be the first non-blank character on a line, but
17095 otherwise the format is free form. Spaces or tabs may appear between
17096 the @code{#} and the keyword. The keywords and the symbols are case
17097 insensitive as in normal Ada code. Comments may be used on a
17098 preprocessor line, but other than that, no other tokens may appear on a
17099 preprocessor line. Any number of @code{elsif} clauses can be present,
17100 including none at all. The @code{else} is optional, as in Ada.
17101
17102 The @code{#} marking the start of a preprocessor line must be the first
17103 non-blank character on the line, i.e. it must be preceded only by
17104 spaces or horizontal tabs.
17105
17106 Symbol substitution outside of preprocessor lines is obtained by using
17107 the sequence
17108
17109 @smallexample
17110 $symbol
17111 @end smallexample
17112
17113 @noindent
17114 anywhere within a source line, except in a comment or within a
17115 string literal. The identifier
17116 following the @code{$} must match one of the symbols defined in the symbol
17117 definition file, and the result is to substitute the value of the
17118 symbol in place of @code{$symbol} in the output file.
17119
17120 Note that although the substitution of strings within a string literal
17121 is not possible, it is possible to have a symbol whose defined value is
17122 a string literal. So instead of setting XYZ to @code{hello} and writing:
17123
17124 @smallexample
17125 Header : String := "$XYZ";
17126 @end smallexample
17127
17128 @noindent
17129 you should set XYZ to @code{"hello"} and write:
17130
17131 @smallexample
17132 Header : String := $XYZ;
17133 @end smallexample
17134
17135 @noindent
17136 and then the substitution will occur as desired.
17137
17138 @ifset vms
17139 @node The GNAT Run-Time Library Builder gnatlbr
17140 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
17141 @findex gnatlbr
17142 @cindex Library builder
17143
17144 @noindent
17145 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
17146 supplied configuration pragmas.
17147
17148 @menu
17149 * Running gnatlbr::
17150 * Switches for gnatlbr::
17151 * Examples of gnatlbr Usage::
17152 @end menu
17153
17154 @node Running gnatlbr
17155 @section Running @code{gnatlbr}
17156
17157 @noindent
17158 The @code{gnatlbr} command has the form
17159
17160 @smallexample
17161 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
17162 @end smallexample
17163
17164 @node Switches for gnatlbr
17165 @section Switches for @code{gnatlbr}
17166
17167 @noindent
17168 @code{gnatlbr} recognizes the following switches:
17169
17170 @table @option
17171 @c !sort!
17172 @item /CREATE=directory
17173 @cindex @code{/CREATE} (@code{gnatlbr})
17174      Create the new run-time library in the specified directory.
17175
17176 @item /SET=directory
17177 @cindex @code{/SET} (@code{gnatlbr})
17178      Make the library in the specified directory the current run-time
17179      library.
17180
17181 @item /DELETE=directory
17182 @cindex @code{/DELETE} (@code{gnatlbr})
17183      Delete the run-time library in the specified directory.
17184
17185 @item /CONFIG=file
17186 @cindex @code{/CONFIG} (@code{gnatlbr})
17187      With /CREATE:
17188      Use the configuration pragmas in the specified file when building
17189      the library.
17190
17191      With /SET:
17192      Use the configuration pragmas in the specified file when compiling.
17193
17194 @end table
17195
17196 @node Examples of gnatlbr Usage
17197 @section Example of @code{gnatlbr} Usage
17198
17199 @smallexample
17200 Contents of VAXFLOAT.ADC:
17201 pragma Float_Representation (VAX_Float);
17202
17203 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
17204
17205 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
17206
17207 @end smallexample
17208 @end ifset
17209
17210 @node The GNAT Library Browser gnatls
17211 @chapter The GNAT Library Browser @code{gnatls}
17212 @findex gnatls
17213 @cindex Library browser
17214
17215 @noindent
17216 @code{gnatls} is a tool that outputs information about compiled
17217 units. It gives the relationship between objects, unit names and source
17218 files. It can also be used to check the source dependencies of a unit
17219 as well as various characteristics.
17220
17221 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
17222 driver (see @ref{The GNAT Driver and Project Files}).
17223
17224 @menu
17225 * Running gnatls::
17226 * Switches for gnatls::
17227 * Examples of gnatls Usage::
17228 @end menu
17229
17230 @node Running gnatls
17231 @section Running @code{gnatls}
17232
17233 @noindent
17234 The @code{gnatls} command has the form
17235
17236 @smallexample
17237 $ gnatls switches @var{object_or_ali_file}
17238 @end smallexample
17239
17240 @noindent
17241 The main argument is the list of object or @file{ali} files
17242 (@pxref{The Ada Library Information Files})
17243 for which information is requested.
17244
17245 In normal mode, without additional option, @code{gnatls} produces a
17246 four-column listing. Each line represents information for a specific
17247 object. The first column gives the full path of the object, the second
17248 column gives the name of the principal unit in this object, the third
17249 column gives the status of the source and the fourth column gives the
17250 full path of the source representing this unit.
17251 Here is a simple example of use:
17252
17253 @smallexample
17254 $ gnatls *.o
17255 ^./^[]^demo1.o            demo1            DIF demo1.adb
17256 ^./^[]^demo2.o            demo2             OK demo2.adb
17257 ^./^[]^hello.o            h1                OK hello.adb
17258 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
17259 ^./^[]^instr.o            instr             OK instr.adb
17260 ^./^[]^tef.o              tef              DIF tef.adb
17261 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
17262 ^./^[]^tgef.o             tgef             DIF tgef.adb
17263 @end smallexample
17264
17265 @noindent
17266 The first line can be interpreted as follows: the main unit which is
17267 contained in
17268 object file @file{demo1.o} is demo1, whose main source is in
17269 @file{demo1.adb}. Furthermore, the version of the source used for the
17270 compilation of demo1 has been modified (DIF). Each source file has a status
17271 qualifier which can be:
17272
17273 @table @code
17274 @item OK (unchanged)
17275 The version of the source file used for the compilation of the
17276 specified unit corresponds exactly to the actual source file.
17277
17278 @item MOK (slightly modified)
17279 The version of the source file used for the compilation of the
17280 specified unit differs from the actual source file but not enough to
17281 require recompilation. If you use gnatmake with the qualifier
17282 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
17283 MOK will not be recompiled.
17284
17285 @item DIF (modified)
17286 No version of the source found on the path corresponds to the source
17287 used to build this object.
17288
17289 @item ??? (file not found)
17290 No source file was found for this unit.
17291
17292 @item HID (hidden,  unchanged version not first on PATH)
17293 The version of the source that corresponds exactly to the source used
17294 for compilation has been found on the path but it is hidden by another
17295 version of the same source that has been modified.
17296
17297 @end table
17298
17299 @node Switches for gnatls
17300 @section Switches for @code{gnatls}
17301
17302 @noindent
17303 @code{gnatls} recognizes the following switches:
17304
17305 @table @option
17306 @c !sort!
17307 @item ^-a^/ALL_UNITS^
17308 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
17309 Consider all units, including those of the predefined Ada library.
17310 Especially useful with @option{^-d^/DEPENDENCIES^}.
17311
17312 @item ^-d^/DEPENDENCIES^
17313 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
17314 List sources from which specified units depend on.
17315
17316 @item ^-h^/OUTPUT=OPTIONS^
17317 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
17318 Output the list of options.
17319
17320 @item ^-o^/OUTPUT=OBJECTS^
17321 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
17322 Only output information about object files.
17323
17324 @item ^-s^/OUTPUT=SOURCES^
17325 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
17326 Only output information about source files.
17327
17328 @item ^-u^/OUTPUT=UNITS^
17329 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
17330 Only output information about compilation units.
17331
17332 @item ^-files^/FILES^=@var{file}
17333 @cindex @option{^-files^/FILES^} (@code{gnatls})
17334 Take as arguments the files listed in text file @var{file}.
17335 Text file @var{file} may contain empty lines that are ignored.
17336 Each non empty line should contain the name of an existing file.
17337 Several such switches may be specified simultaneously.
17338
17339 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17340 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
17341 @itemx ^-I^/SEARCH=^@var{dir}
17342 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
17343 @itemx -nostdinc
17344 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
17345 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
17346 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
17347 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
17348 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
17349 flags (@pxref{Switches for gnatmake}).
17350
17351 @item --RTS=@var{rts-path}
17352 @cindex @option{--RTS} (@code{gnatls})
17353 Specifies the default location of the runtime library. Same meaning as the
17354 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
17355
17356 @item ^-v^/OUTPUT=VERBOSE^
17357 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
17358 Verbose mode. Output the complete source, object and project paths. Do not use
17359 the default column layout but instead use long format giving as much as
17360 information possible on each requested units, including special
17361 characteristics such as:
17362
17363 @table @code
17364 @item  Preelaborable
17365 The unit is preelaborable in the Ada sense.
17366
17367 @item No_Elab_Code
17368 No elaboration code has been produced by the compiler for this unit.
17369
17370 @item Pure
17371 The unit is pure in the Ada sense.
17372
17373 @item Elaborate_Body
17374 The unit contains a pragma Elaborate_Body.
17375
17376 @item Remote_Types
17377 The unit contains a pragma Remote_Types.
17378
17379 @item Shared_Passive
17380 The unit contains a pragma Shared_Passive.
17381
17382 @item Predefined
17383 This unit is part of the predefined environment and cannot be modified
17384 by the user.
17385
17386 @item Remote_Call_Interface
17387 The unit contains a pragma Remote_Call_Interface.
17388
17389 @end table
17390
17391 @end table
17392
17393 @node Examples of gnatls Usage
17394 @section Example of @code{gnatls} Usage
17395 @ifclear vms
17396
17397 @noindent
17398 Example of using the verbose switch. Note how the source and
17399 object paths are affected by the -I switch.
17400
17401 @smallexample
17402 $ gnatls -v -I.. demo1.o
17403
17404 GNATLS 5.03w (20041123-34)
17405 Copyright 1997-2004 Free Software Foundation, Inc.
17406
17407 Source Search Path:
17408    <Current_Directory>
17409    ../
17410    /home/comar/local/adainclude/
17411
17412 Object Search Path:
17413    <Current_Directory>
17414    ../
17415    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17416
17417 Project Search Path:
17418    <Current_Directory>
17419    /home/comar/local/lib/gnat/
17420
17421 ./demo1.o
17422    Unit =>
17423      Name   => demo1
17424      Kind   => subprogram body
17425      Flags  => No_Elab_Code
17426      Source => demo1.adb    modified
17427 @end smallexample
17428
17429 @noindent
17430 The following is an example of use of the dependency list.
17431 Note the use of the -s switch
17432 which gives a straight list of source files. This can be useful for
17433 building specialized scripts.
17434
17435 @smallexample
17436 $ gnatls -d demo2.o
17437 ./demo2.o   demo2        OK demo2.adb
17438                          OK gen_list.ads
17439                          OK gen_list.adb
17440                          OK instr.ads
17441                          OK instr-child.ads
17442
17443 $ gnatls -d -s -a demo1.o
17444 demo1.adb
17445 /home/comar/local/adainclude/ada.ads
17446 /home/comar/local/adainclude/a-finali.ads
17447 /home/comar/local/adainclude/a-filico.ads
17448 /home/comar/local/adainclude/a-stream.ads
17449 /home/comar/local/adainclude/a-tags.ads
17450 gen_list.ads
17451 gen_list.adb
17452 /home/comar/local/adainclude/gnat.ads
17453 /home/comar/local/adainclude/g-io.ads
17454 instr.ads
17455 /home/comar/local/adainclude/system.ads
17456 /home/comar/local/adainclude/s-exctab.ads
17457 /home/comar/local/adainclude/s-finimp.ads
17458 /home/comar/local/adainclude/s-finroo.ads
17459 /home/comar/local/adainclude/s-secsta.ads
17460 /home/comar/local/adainclude/s-stalib.ads
17461 /home/comar/local/adainclude/s-stoele.ads
17462 /home/comar/local/adainclude/s-stratt.ads
17463 /home/comar/local/adainclude/s-tasoli.ads
17464 /home/comar/local/adainclude/s-unstyp.ads
17465 /home/comar/local/adainclude/unchconv.ads
17466 @end smallexample
17467 @end ifclear
17468
17469 @ifset vms
17470 @smallexample
17471 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17472
17473 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17474 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17475 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17476 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17477 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17478 demo1.adb
17479 gen_list.ads
17480 gen_list.adb
17481 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17482 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17483 instr.ads
17484 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17485 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17486 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17487 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17488 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17489 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17490 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17491 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17492 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17493 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17494 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17495 @end smallexample
17496 @end ifset
17497
17498 @node Cleaning Up Using gnatclean
17499 @chapter Cleaning Up Using @code{gnatclean}
17500 @findex gnatclean
17501 @cindex Cleaning tool
17502
17503 @noindent
17504 @code{gnatclean} is a tool that allows the deletion of files produced by the
17505 compiler, binder and linker, including ALI files, object files, tree files,
17506 expanded source files, library files, interface copy source files, binder
17507 generated files and executable files.
17508
17509 @menu
17510 * Running gnatclean::
17511 * Switches for gnatclean::
17512 @c * Examples of gnatclean Usage::
17513 @end menu
17514
17515 @node Running gnatclean
17516 @section Running @code{gnatclean}
17517
17518 @noindent
17519 The @code{gnatclean} command has the form:
17520
17521 @smallexample
17522 $ gnatclean switches @var{names}
17523 @end smallexample
17524
17525 @noindent
17526 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17527 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17528 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17529
17530 @noindent
17531 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17532 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17533 the linker. In informative-only mode, specified by switch
17534 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17535 normal mode is listed, but no file is actually deleted.
17536
17537 @node Switches for gnatclean
17538 @section Switches for @code{gnatclean}
17539
17540 @noindent
17541 @code{gnatclean} recognizes the following switches:
17542
17543 @table @option
17544 @c !sort!
17545 @item ^-c^/COMPILER_FILES_ONLY^
17546 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17547 Only attempt to delete the files produced by the compiler, not those produced
17548 by the binder or the linker. The files that are not to be deleted are library
17549 files, interface copy files, binder generated files and executable files.
17550
17551 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17552 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17553 Indicate that ALI and object files should normally be found in directory
17554 @var{dir}.
17555
17556 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17557 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17558 When using project files, if some errors or warnings are detected during
17559 parsing and verbose mode is not in effect (no use of switch
17560 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17561 file, rather than its simple file name.
17562
17563 @item ^-h^/HELP^
17564 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17565 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17566
17567 @item ^-n^/NODELETE^
17568 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17569 Informative-only mode. Do not delete any files. Output the list of the files
17570 that would have been deleted if this switch was not specified.
17571
17572 @item ^-P^/PROJECT_FILE=^@var{project}
17573 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17574 Use project file @var{project}. Only one such switch can be used.
17575 When cleaning a project file, the files produced by the compilation of the
17576 immediate sources or inherited sources of the project files are to be
17577 deleted. This is not depending on the presence or not of executable names
17578 on the command line.
17579
17580 @item ^-q^/QUIET^
17581 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17582 Quiet output. If there are no errors, do not output anything, except in
17583 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17584 (switch ^-n^/NODELETE^).
17585
17586 @item ^-r^/RECURSIVE^
17587 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17588 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17589 clean all imported and extended project files, recursively. If this switch
17590 is not specified, only the files related to the main project file are to be
17591 deleted. This switch has no effect if no project file is specified.
17592
17593 @item ^-v^/VERBOSE^
17594 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17595 Verbose mode.
17596
17597 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17598 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17599 Indicates the verbosity of the parsing of GNAT project files.
17600 @xref{Switches Related to Project Files}.
17601
17602 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17603 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17604 Indicates that external variable @var{name} has the value @var{value}.
17605 The Project Manager will use this value for occurrences of
17606 @code{external(name)} when parsing the project file.
17607 @xref{Switches Related to Project Files}.
17608
17609 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17610 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17611 When searching for ALI and object files, look in directory
17612 @var{dir}.
17613
17614 @item ^-I^/SEARCH=^@var{dir}
17615 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17616 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17617
17618 @item ^-I-^/NOCURRENT_DIRECTORY^
17619 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17620 @cindex Source files, suppressing search
17621 Do not look for ALI or object files in the directory
17622 where @code{gnatclean} was invoked.
17623
17624 @end table
17625
17626 @c @node Examples of gnatclean Usage
17627 @c @section Examples of @code{gnatclean} Usage
17628
17629 @ifclear vms
17630 @node GNAT and Libraries
17631 @chapter GNAT and Libraries
17632 @cindex Library, building, installing, using
17633
17634 @noindent
17635 This chapter describes how to build and use libraries with GNAT, and also shows
17636 how to recompile the GNAT run-time library. You should be familiar with the
17637 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17638 chapter.
17639
17640 @menu
17641 * Introduction to Libraries in GNAT::
17642 * General Ada Libraries::
17643 * Stand-alone Ada Libraries::
17644 * Rebuilding the GNAT Run-Time Library::
17645 @end menu
17646
17647 @node Introduction to Libraries in GNAT
17648 @section Introduction to Libraries in GNAT
17649
17650 @noindent
17651 A library is, conceptually, a collection of objects which does not have its
17652 own main thread of execution, but rather provides certain services to the
17653 applications that use it. A library can be either statically linked with the
17654 application, in which case its code is directly included in the application,
17655 or, on platforms that support it, be dynamically linked, in which case
17656 its code is shared by all applications making use of this library.
17657
17658 GNAT supports both types of libraries.
17659 In the static case, the compiled code can be provided in different ways. The
17660 simplest approach is to provide directly the set of objects resulting from
17661 compilation of the library source files. Alternatively, you can group the
17662 objects into an archive using whatever commands are provided by the operating
17663 system. For the latter case, the objects are grouped into a shared library.
17664
17665 In the GNAT environment, a library has three types of components:
17666 @itemize @bullet
17667 @item
17668 Source files.
17669 @item
17670 @file{ALI} files.
17671 @xref{The Ada Library Information Files}.
17672 @item
17673 Object files, an archive or a shared library.
17674 @end itemize
17675
17676 @noindent
17677 A GNAT library may expose all its source files, which is useful for
17678 documentation purposes. Alternatively, it may expose only the units needed by
17679 an external user to make use of the library. That is to say, the specs
17680 reflecting the library services along with all the units needed to compile
17681 those specs, which can include generic bodies or any body implementing an
17682 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17683 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17684
17685 All compilation units comprising an application, including those in a library,
17686 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17687 computes the elaboration order from the @file{ALI} files and this is why they
17688 constitute a mandatory part of GNAT libraries. Except in the case of
17689 @emph{stand-alone libraries}, where a specific library elaboration routine is
17690 produced independently of the application(s) using the library.
17691
17692 @node General Ada Libraries
17693 @section General Ada Libraries
17694
17695 @menu
17696 * Building a library::
17697 * Installing a library::
17698 * Using a library::
17699 @end menu
17700
17701 @node Building a library
17702 @subsection Building a library
17703
17704 @noindent
17705 The easiest way to build a library is to use the Project Manager,
17706 which supports a special type of project called a @emph{Library Project}
17707 (@pxref{Library Projects}).
17708
17709 A project is considered a library project, when two project-level attributes
17710 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17711 control different aspects of library configuration, additional optional
17712 project-level attributes can be specified:
17713 @table @code
17714 @item Library_Kind
17715 This attribute controls whether the library is to be static or dynamic
17716
17717 @item Library_Version
17718 This attribute specifies the library version; this value is used
17719 during dynamic linking of shared libraries to determine if the currently
17720 installed versions of the binaries are compatible.
17721
17722 @item Library_Options
17723 @item Library_GCC
17724 These attributes specify additional low-level options to be used during
17725 library generation, and redefine the actual application used to generate
17726 library.
17727 @end table
17728
17729 @noindent
17730 The GNAT Project Manager takes full care of the library maintenance task,
17731 including recompilation of the source files for which objects do not exist
17732 or are not up to date, assembly of the library archive, and installation of
17733 the library (i.e., copying associated source, object and @file{ALI} files
17734 to the specified location).
17735
17736 Here is a simple library project file:
17737 @smallexample @c ada
17738 project My_Lib is
17739    for Source_Dirs use ("src1", "src2");
17740    for Object_Dir use "obj";
17741    for Library_Name use "mylib";
17742    for Library_Dir use "lib";
17743    for Library_Kind use "dynamic";
17744 end My_lib;
17745 @end smallexample
17746
17747 @noindent
17748 and the compilation command to build and install the library:
17749
17750 @smallexample @c ada
17751   $ gnatmake -Pmy_lib
17752 @end smallexample
17753
17754 @noindent
17755 It is not entirely trivial to perform manually all the steps required to
17756 produce a library. We recommend that you use the GNAT Project Manager
17757 for this task. In special cases where this is not desired, the necessary
17758 steps are discussed below.
17759
17760 There are various possibilities for compiling the units that make up the
17761 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17762 with a conventional script. For simple libraries, it is also possible to create
17763 a dummy main program which depends upon all the packages that comprise the
17764 interface of the library. This dummy main program can then be given to
17765 @command{gnatmake}, which will ensure that all necessary objects are built.
17766
17767 After this task is accomplished, you should follow the standard procedure
17768 of the underlying operating system to produce the static or shared library.
17769
17770 Here is an example of such a dummy program:
17771 @smallexample @c ada
17772 @group
17773 with My_Lib.Service1;
17774 with My_Lib.Service2;
17775 with My_Lib.Service3;
17776 procedure My_Lib_Dummy is
17777 begin
17778    null;
17779 end;
17780 @end group
17781 @end smallexample
17782
17783 @noindent
17784 Here are the generic commands that will build an archive or a shared library.
17785
17786 @smallexample
17787 # compiling the library
17788 $ gnatmake -c my_lib_dummy.adb
17789
17790 # we don't need the dummy object itself
17791 $ rm my_lib_dummy.o my_lib_dummy.ali
17792
17793 # create an archive with the remaining objects
17794 $ ar rc libmy_lib.a *.o
17795 # some systems may require "ranlib" to be run as well
17796
17797 # or create a shared library
17798 $ gcc -shared -o libmy_lib.so *.o
17799 # some systems may require the code to have been compiled with -fPIC
17800
17801 # remove the object files that are now in the library
17802 $ rm *.o
17803
17804 # Make the ALI files read-only so that gnatmake will not try to
17805 # regenerate the objects that are in the library
17806 $ chmod -w *.ali
17807 @end smallexample
17808
17809 @noindent
17810 Please note that the library must have a name of the form @file{libxxx.a} or
17811 @file{libxxx.so} (or @file{libxxx.dll} on Windows) in order to be accessed by
17812 the directive @option{-lxxx} at link time.
17813
17814 @node Installing a library
17815 @subsection Installing a library
17816 @cindex @code{ADA_PROJECT_PATH}
17817
17818 @noindent
17819 If you use project files, library installation is part of the library build
17820 process. Thus no further action is needed in order to make use of the
17821 libraries that are built as part of the general application build. A usable
17822 version of the library is installed in the directory specified by the
17823 @code{Library_Dir} attribute of the library project file.
17824
17825 You may want to install a library in a context different from where the library
17826 is built. This situation arises with third party suppliers, who may want
17827 to distribute a library in binary form where the user is not expected to be
17828 able to recompile the library. The simplest option in this case is to provide
17829 a project file slightly different from the one used to build the library, by
17830 using the @code{externally_built} attribute. For instance, the project
17831 file used to build the library in the previous section can be changed into the
17832 following one when the library is installed:
17833
17834 @smallexample @c projectfile
17835 project My_Lib is
17836    for Source_Dirs use ("src1", "src2");
17837    for Library_Name use "mylib";
17838    for Library_Dir use "lib";
17839    for Library_Kind use "dynamic";
17840    for Externally_Built use "true";
17841 end My_lib;
17842 @end smallexample
17843
17844 @noindent
17845 This project file assumes that the directories @file{src1},
17846 @file{src2}, and @file{lib} exist in
17847 the directory containing the project file. The @code{externally_built}
17848 attribute makes it clear to the GNAT builder that it should not attempt to
17849 recompile any of the units from this library. It allows the library provider to
17850 restrict the source set to the minimum necessary for clients to make use of the
17851 library as described in the first section of this chapter. It is the
17852 responsibility of the library provider to install the necessary sources, ALI
17853 files and libraries in the directories mentioned in the project file. For
17854 convenience, the user's library project file should be installed in a location
17855 that will be searched automatically by the GNAT
17856 builder. These are the directories referenced in the @code{ADA_PROJECT_PATH}
17857 environment variable (@pxref{Importing Projects}), and also the default GNAT
17858 library location that can be queried with @command{gnatls -v} and is usually of
17859 the form $gnat_install_root/lib/gnat.
17860
17861 When project files are not an option, it is also possible, but not recommended,
17862 to install the library so that the sources needed to use the library are on the
17863 Ada source path and the ALI files & libraries be on the Ada Object path (see
17864 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17865 administrator can place general-purpose libraries in the default compiler
17866 paths, by specifying the libraries' location in the configuration files
17867 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17868 must be located in the GNAT installation tree at the same place as the gcc spec
17869 file. The location of the gcc spec file can be determined as follows:
17870 @smallexample
17871 $ gcc -v
17872 @end smallexample
17873
17874 @noindent
17875 The configuration files mentioned above have a simple format: each line
17876 must contain one unique directory name.
17877 Those names are added to the corresponding path
17878 in their order of appearance in the file. The names can be either absolute
17879 or relative; in the latter case, they are relative to where theses files
17880 are located.
17881
17882 The files @file{ada_source_path} and @file{ada_object_path} might not be
17883 present in a
17884 GNAT installation, in which case, GNAT will look for its run-time library in
17885 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17886 objects and @file{ALI} files). When the files exist, the compiler does not
17887 look in @file{adainclude} and @file{adalib}, and thus the
17888 @file{ada_source_path} file
17889 must contain the location for the GNAT run-time sources (which can simply
17890 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17891 contain the location for the GNAT run-time objects (which can simply
17892 be @file{adalib}).
17893
17894 You can also specify a new default path to the run-time library at compilation
17895 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17896 the run-time library you want your program to be compiled with. This switch is
17897 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17898 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17899
17900 It is possible to install a library before or after the standard GNAT
17901 library, by reordering the lines in the configuration files. In general, a
17902 library must be installed before the GNAT library if it redefines
17903 any part of it.
17904
17905 @node Using a library
17906 @subsection Using a library
17907
17908 @noindent Once again, the project facility greatly simplifies the use of
17909 libraries. In this context, using a library is just a matter of adding a
17910 @code{with} clause in the user project. For instance, to make use of the
17911 library @code{My_Lib} shown in examples in earlier sections, you can
17912 write:
17913
17914 @smallexample @c projectfile
17915 with "my_lib";
17916 project My_Proj is
17917   ...
17918 end My_Proj;
17919 @end smallexample
17920
17921 Even if you have a third-party, non-Ada library, you can still use GNAT's
17922 Project Manager facility to provide a wrapper for it. For example, the
17923 following project, when @code{with}ed by your main project, will link with the
17924 third-party library @file{liba.a}:
17925
17926 @smallexample @c projectfile
17927 @group
17928 project Liba is
17929    for Externally_Built use "true";
17930    for Source_Files use ();
17931    for Library_Dir use "lib";
17932    for Library_Name use "a";
17933    for Library_Kind use "static";
17934 end Liba;
17935 @end group
17936 @end smallexample
17937 This is an alternative to the use of @code{pragma Linker_Options}. It is
17938 especially interesting in the context of systems with several interdependent
17939 static libraries where finding a proper linker order is not easy and best be
17940 left to the tools having visibility over project dependence information.
17941
17942 @noindent
17943 In order to use an Ada library manually, you need to make sure that this
17944 library is on both your source and object path
17945 (see @ref{Search Paths and the Run-Time Library (RTL)}
17946 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17947 in an archive or a shared library, you need to specify the desired
17948 library at link time.
17949
17950 For example, you can use the library @file{mylib} installed in
17951 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17952
17953 @smallexample
17954 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17955   -largs -lmy_lib
17956 @end smallexample
17957
17958 @noindent
17959 This can be expressed more simply:
17960 @smallexample
17961 $ gnatmake my_appl
17962 @end smallexample
17963 @noindent
17964 when the following conditions are met:
17965 @itemize @bullet
17966 @item
17967 @file{/dir/my_lib_src} has been added by the user to the environment
17968 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
17969 @file{ada_source_path}
17970 @item
17971 @file{/dir/my_lib_obj} has been added by the user to the environment
17972 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
17973 @file{ada_object_path}
17974 @item
17975 a pragma @code{Linker_Options} has been added to one of the sources.
17976 For example:
17977
17978 @smallexample @c ada
17979 pragma Linker_Options ("-lmy_lib");
17980 @end smallexample
17981 @end itemize
17982
17983 @node Stand-alone Ada Libraries
17984 @section Stand-alone Ada Libraries
17985 @cindex Stand-alone library, building, using
17986
17987 @menu
17988 * Introduction to Stand-alone Libraries::
17989 * Building a Stand-alone Library::
17990 * Creating a Stand-alone Library to be used in a non-Ada context::
17991 * Restrictions in Stand-alone Libraries::
17992 @end menu
17993
17994 @node Introduction to Stand-alone Libraries
17995 @subsection Introduction to Stand-alone Libraries
17996
17997 @noindent
17998 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17999 necessary code to
18000 elaborate the Ada units that are included in the library. In contrast with
18001 an ordinary library, which consists of all sources, objects and @file{ALI}
18002 files of the
18003 library, a SAL may specify a restricted subset of compilation units
18004 to serve as a library interface. In this case, the fully
18005 self-sufficient set of files will normally consist of an objects
18006 archive, the sources of interface units' specs, and the @file{ALI}
18007 files of interface units.
18008 If an interface spec contains a generic unit or an inlined subprogram,
18009 the body's
18010 source must also be provided; if the units that must be provided in the source
18011 form depend on other units, the source and @file{ALI} files of those must
18012 also be provided.
18013
18014 The main purpose of a SAL is to minimize the recompilation overhead of client
18015 applications when a new version of the library is installed. Specifically,
18016 if the interface sources have not changed, client applications do not need to
18017 be recompiled. If, furthermore, a SAL is provided in the shared form and its
18018 version, controlled by @code{Library_Version} attribute, is not changed,
18019 then the clients do not need to be relinked.
18020
18021 SALs also allow the library providers to minimize the amount of library source
18022 text exposed to the clients.  Such ``information hiding'' might be useful or
18023 necessary for various reasons.
18024
18025 Stand-alone libraries are also well suited to be used in an executable whose
18026 main routine is not written in Ada.
18027
18028 @node Building a Stand-alone Library
18029 @subsection Building a Stand-alone Library
18030
18031 @noindent
18032 GNAT's Project facility provides a simple way of building and installing
18033 stand-alone libraries; see @ref{Stand-alone Library Projects}.
18034 To be a Stand-alone Library Project, in addition to the two attributes
18035 that make a project a Library Project (@code{Library_Name} and
18036 @code{Library_Dir}; see @ref{Library Projects}), the attribute
18037 @code{Library_Interface} must be defined.  For example:
18038
18039 @smallexample @c projectfile
18040 @group
18041    for Library_Dir use "lib_dir";
18042    for Library_Name use "dummy";
18043    for Library_Interface use ("int1", "int1.child");
18044 @end group
18045 @end smallexample
18046
18047 @noindent
18048 Attribute @code{Library_Interface} has a non-empty string list value,
18049 each string in the list designating a unit contained in an immediate source
18050 of the project file.
18051
18052 When a Stand-alone Library is built, first the binder is invoked to build
18053 a package whose name depends on the library name
18054 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
18055 This binder-generated package includes initialization and
18056 finalization procedures whose
18057 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
18058 in the example
18059 above). The object corresponding to this package is included in the library.
18060
18061 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
18062 calling of these procedures if a static SAL is built, or if a shared SAL
18063 is built
18064 with the project-level attribute @code{Library_Auto_Init} set to
18065 @code{"false"}.
18066
18067 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
18068 (those that are listed in attribute @code{Library_Interface}) are copied to
18069 the Library Directory. As a consequence, only the Interface Units may be
18070 imported from Ada units outside of the library. If other units are imported,
18071 the binding phase will fail.
18072
18073 The attribute @code{Library_Src_Dir} may be specified for a
18074 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
18075 single string value. Its value must be the path (absolute or relative to the
18076 project directory) of an existing directory. This directory cannot be the
18077 object directory or one of the source directories, but it can be the same as
18078 the library directory. The sources of the Interface
18079 Units of the library that are needed by an Ada client of the library will be
18080 copied to the designated directory, called the Interface Copy directory.
18081 These sources include the specs of the Interface Units, but they may also
18082 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
18083 are used, or when there is a generic unit in the spec. Before the sources
18084 are copied to the Interface Copy directory, an attempt is made to delete all
18085 files in the Interface Copy directory.
18086
18087 Building stand-alone libraries by hand is somewhat tedious, but for those
18088 occasions when it is necessary here are the steps that you need to perform:
18089 @itemize @bullet
18090 @item
18091 Compile all library sources.
18092
18093 @item
18094 Invoke the binder with the switch @option{-n} (No Ada main program),
18095 with all the @file{ALI} files of the interfaces, and
18096 with the switch @option{-L} to give specific names to the @code{init}
18097 and @code{final} procedures.  For example:
18098 @smallexample
18099   gnatbind -n int1.ali int2.ali -Lsal1
18100 @end smallexample
18101
18102 @item
18103 Compile the binder generated file:
18104 @smallexample
18105   gcc -c b~int2.adb
18106 @end smallexample
18107
18108 @item
18109 Link the dynamic library with all the necessary object files,
18110 indicating to the linker the names of the @code{init} (and possibly
18111 @code{final}) procedures for automatic initialization (and finalization).
18112 The built library should be placed in a directory different from
18113 the object directory.
18114
18115 @item
18116 Copy the @code{ALI} files of the interface to the library directory,
18117 add in this copy an indication that it is an interface to a SAL
18118 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
18119 with letter ``P'') and make the modified copy of the @file{ALI} file
18120 read-only.
18121 @end itemize
18122
18123 @noindent
18124 Using SALs is not different from using other libraries
18125 (see @ref{Using a library}).
18126
18127 @node Creating a Stand-alone Library to be used in a non-Ada context
18128 @subsection Creating a Stand-alone Library to be used in a non-Ada context
18129
18130 @noindent
18131 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
18132 a non-Ada context.
18133
18134 The only extra step required is to ensure that library interface subprograms
18135 are compatible with the main program, by means of @code{pragma Export}
18136 or @code{pragma Convention}.
18137
18138 Here is an example of simple library interface for use with C main program:
18139
18140 @smallexample @c ada
18141 package Interface is
18142
18143    procedure Do_Something;
18144    pragma Export (C, Do_Something, "do_something");
18145
18146    procedure Do_Something_Else;
18147    pragma Export (C, Do_Something_Else, "do_something_else");
18148
18149 end Interface;
18150 @end smallexample
18151
18152 @noindent
18153 On the foreign language side, you must provide a ``foreign'' view of the
18154 library interface; remember that it should contain elaboration routines in
18155 addition to interface subprograms.
18156
18157 The example below shows the content of @code{mylib_interface.h} (note
18158 that there is no rule for the naming of this file, any name can be used)
18159 @smallexample
18160 /* the library elaboration procedure */
18161 extern void mylibinit (void);
18162
18163 /* the library finalization procedure */
18164 extern void mylibfinal (void);
18165
18166 /* the interface exported by the library */
18167 extern void do_something (void);
18168 extern void do_something_else (void);
18169 @end smallexample
18170
18171 @noindent
18172 Libraries built as explained above can be used from any program, provided
18173 that the elaboration procedures (named @code{mylibinit} in the previous
18174 example) are called before the library services are used. Any number of
18175 libraries can be used simultaneously, as long as the elaboration
18176 procedure of each library is called.
18177
18178 Below is an example of a C program that uses the @code{mylib} library.
18179
18180 @smallexample
18181 #include "mylib_interface.h"
18182
18183 int
18184 main (void)
18185 @{
18186    /* First, elaborate the library before using it */
18187    mylibinit ();
18188
18189    /* Main program, using the library exported entities */
18190    do_something ();
18191    do_something_else ();
18192
18193    /* Library finalization at the end of the program */
18194    mylibfinal ();
18195    return 0;
18196 @}
18197 @end smallexample
18198
18199 @noindent
18200 Note that invoking any library finalization procedure generated by
18201 @code{gnatbind} shuts down the Ada run-time environment.
18202 Consequently, the
18203 finalization of all Ada libraries must be performed at the end of the program.
18204 No call to these libraries or to the Ada run-time library should be made
18205 after the finalization phase.
18206
18207 @node Restrictions in Stand-alone Libraries
18208 @subsection Restrictions in Stand-alone Libraries
18209
18210 @noindent
18211 The pragmas listed below should be used with caution inside libraries,
18212 as they can create incompatibilities with other Ada libraries:
18213 @itemize @bullet
18214 @item pragma @code{Locking_Policy}
18215 @item pragma @code{Queuing_Policy}
18216 @item pragma @code{Task_Dispatching_Policy}
18217 @item pragma @code{Unreserve_All_Interrupts}
18218 @end itemize
18219
18220 @noindent
18221 When using a library that contains such pragmas, the user must make sure
18222 that all libraries use the same pragmas with the same values. Otherwise,
18223 @code{Program_Error} will
18224 be raised during the elaboration of the conflicting
18225 libraries. The usage of these pragmas and its consequences for the user
18226 should therefore be well documented.
18227
18228 Similarly, the traceback in the exception occurrence mechanism should be
18229 enabled or disabled in a consistent manner across all libraries.
18230 Otherwise, Program_Error will be raised during the elaboration of the
18231 conflicting libraries.
18232
18233 If the @code{Version} or @code{Body_Version}
18234 attributes are used inside a library, then you need to
18235 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
18236 libraries, so that version identifiers can be properly computed.
18237 In practice these attributes are rarely used, so this is unlikely
18238 to be a consideration.
18239
18240 @node  Rebuilding the GNAT Run-Time Library
18241 @section Rebuilding the GNAT Run-Time Library
18242 @cindex GNAT Run-Time Library, rebuilding
18243 @cindex Building the GNAT Run-Time Library
18244 @cindex Rebuilding the GNAT Run-Time Library
18245 @cindex Run-Time Library, rebuilding
18246
18247 @noindent
18248 It may be useful to recompile the GNAT library in various contexts, the
18249 most important one being the use of partition-wide configuration pragmas
18250 such as @code{Normalize_Scalars}. A special Makefile called
18251 @code{Makefile.adalib} is provided to that effect and can be found in
18252 the directory containing the GNAT library. The location of this
18253 directory depends on the way the GNAT environment has been installed and can
18254 be determined by means of the command:
18255
18256 @smallexample
18257 $ gnatls -v
18258 @end smallexample
18259
18260 @noindent
18261 The last entry in the object search path usually contains the
18262 gnat library. This Makefile contains its own documentation and in
18263 particular the set of instructions needed to rebuild a new library and
18264 to use it.
18265
18266 @node Using the GNU make Utility
18267 @chapter Using the GNU @code{make} Utility
18268 @findex make
18269
18270 @noindent
18271 This chapter offers some examples of makefiles that solve specific
18272 problems. It does not explain how to write a makefile (see the GNU make
18273 documentation), nor does it try to replace the @command{gnatmake} utility
18274 (@pxref{The GNAT Make Program gnatmake}).
18275
18276 All the examples in this section are specific to the GNU version of
18277 make. Although @code{make} is a standard utility, and the basic language
18278 is the same, these examples use some advanced features found only in
18279 @code{GNU make}.
18280
18281 @menu
18282 * Using gnatmake in a Makefile::
18283 * Automatically Creating a List of Directories::
18284 * Generating the Command Line Switches::
18285 * Overcoming Command Line Length Limits::
18286 @end menu
18287
18288 @node Using gnatmake in a Makefile
18289 @section Using gnatmake in a Makefile
18290 @findex makefile
18291 @cindex GNU make
18292
18293 @noindent
18294 Complex project organizations can be handled in a very powerful way by
18295 using GNU make combined with gnatmake. For instance, here is a Makefile
18296 which allows you to build each subsystem of a big project into a separate
18297 shared library. Such a makefile allows you to significantly reduce the link
18298 time of very big applications while maintaining full coherence at
18299 each step of the build process.
18300
18301 The list of dependencies are handled automatically by
18302 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
18303 the appropriate directories.
18304
18305 Note that you should also read the example on how to automatically
18306 create the list of directories
18307 (@pxref{Automatically Creating a List of Directories})
18308 which might help you in case your project has a lot of subdirectories.
18309
18310 @smallexample
18311 @iftex
18312 @leftskip=0cm
18313 @font@heightrm=cmr8
18314 @heightrm
18315 @end iftex
18316 ## This Makefile is intended to be used with the following directory
18317 ## configuration:
18318 ##  - The sources are split into a series of csc (computer software components)
18319 ##    Each of these csc is put in its own directory.
18320 ##    Their name are referenced by the directory names.
18321 ##    They will be compiled into shared library (although this would also work
18322 ##    with static libraries
18323 ##  - The main program (and possibly other packages that do not belong to any
18324 ##    csc is put in the top level directory (where the Makefile is).
18325 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
18326 ##                    \_ second_csc (sources) __ lib (will contain the library)
18327 ##                    \_ ...
18328 ## Although this Makefile is build for shared library, it is easy to modify
18329 ## to build partial link objects instead (modify the lines with -shared and
18330 ## gnatlink below)
18331 ##
18332 ## With this makefile, you can change any file in the system or add any new
18333 ## file, and everything will be recompiled correctly (only the relevant shared
18334 ## objects will be recompiled, and the main program will be re-linked).
18335
18336 # The list of computer software component for your project. This might be
18337 # generated automatically.
18338 CSC_LIST=aa bb cc
18339
18340 # Name of the main program (no extension)
18341 MAIN=main
18342
18343 # If we need to build objects with -fPIC, uncomment the following line
18344 #NEED_FPIC=-fPIC
18345
18346 # The following variable should give the directory containing libgnat.so
18347 # You can get this directory through 'gnatls -v'. This is usually the last
18348 # directory in the Object_Path.
18349 GLIB=...
18350
18351 # The directories for the libraries
18352 # (This macro expands the list of CSC to the list of shared libraries, you
18353 # could simply use the expanded form :
18354 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
18355 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
18356
18357 $@{MAIN@}: objects $@{LIB_DIR@}
18358     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
18359     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
18360
18361 objects::
18362     # recompile the sources
18363     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
18364
18365 # Note: In a future version of GNAT, the following commands will be simplified
18366 # by a new tool, gnatmlib
18367 $@{LIB_DIR@}:
18368     mkdir -p $@{dir $@@ @}
18369     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
18370     cd $@{dir $@@ @}; cp -f ../*.ali .
18371
18372 # The dependencies for the modules
18373 # Note that we have to force the expansion of *.o, since in some cases
18374 # make won't be able to do it itself.
18375 aa/lib/libaa.so: $@{wildcard aa/*.o@}
18376 bb/lib/libbb.so: $@{wildcard bb/*.o@}
18377 cc/lib/libcc.so: $@{wildcard cc/*.o@}
18378
18379 # Make sure all of the shared libraries are in the path before starting the
18380 # program
18381 run::
18382     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
18383
18384 clean::
18385     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
18386     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
18387     $@{RM@} $@{CSC_LIST:%=%/*.o@}
18388     $@{RM@} *.o *.ali $@{MAIN@}
18389 @end smallexample
18390
18391 @node Automatically Creating a List of Directories
18392 @section Automatically Creating a List of Directories
18393
18394 @noindent
18395 In most makefiles, you will have to specify a list of directories, and
18396 store it in a variable. For small projects, it is often easier to
18397 specify each of them by hand, since you then have full control over what
18398 is the proper order for these directories, which ones should be
18399 included...
18400
18401 However, in larger projects, which might involve hundreds of
18402 subdirectories, it might be more convenient to generate this list
18403 automatically.
18404
18405 The example below presents two methods. The first one, although less
18406 general, gives you more control over the list. It involves wildcard
18407 characters, that are automatically expanded by @code{make}. Its
18408 shortcoming is that you need to explicitly specify some of the
18409 organization of your project, such as for instance the directory tree
18410 depth, whether some directories are found in a separate tree,...
18411
18412 The second method is the most general one. It requires an external
18413 program, called @code{find}, which is standard on all Unix systems. All
18414 the directories found under a given root directory will be added to the
18415 list.
18416
18417 @smallexample
18418 @iftex
18419 @leftskip=0cm
18420 @font@heightrm=cmr8
18421 @heightrm
18422 @end iftex
18423 # The examples below are based on the following directory hierarchy:
18424 # All the directories can contain any number of files
18425 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
18426 #                       ->  ab
18427 #                       ->  ac
18428 #                ->  b  ->  ba  ->  baa
18429 #                       ->  bb
18430 #                       ->  bc
18431 # This Makefile creates a variable called DIRS, that can be reused any time
18432 # you need this list (see the other examples in this section)
18433
18434 # The root of your project's directory hierarchy
18435 ROOT_DIRECTORY=.
18436
18437 ####
18438 # First method: specify explicitly the list of directories
18439 # This allows you to specify any subset of all the directories you need.
18440 ####
18441
18442 DIRS := a/aa/ a/ab/ b/ba/
18443
18444 ####
18445 # Second method: use wildcards
18446 # Note that the argument(s) to wildcard below should end with a '/'.
18447 # Since wildcards also return file names, we have to filter them out
18448 # to avoid duplicate directory names.
18449 # We thus use make's @code{dir} and @code{sort} functions.
18450 # It sets DIRs to the following value (note that the directories aaa and baa
18451 # are not given, unless you change the arguments to wildcard).
18452 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18453 ####
18454
18455 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18456                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18457
18458 ####
18459 # Third method: use an external program
18460 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18461 # This is the most complete command: it sets DIRs to the following value:
18462 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18463 ####
18464
18465 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18466
18467 @end smallexample
18468
18469 @node Generating the Command Line Switches
18470 @section Generating the Command Line Switches
18471
18472 @noindent
18473 Once you have created the list of directories as explained in the
18474 previous section (@pxref{Automatically Creating a List of Directories}),
18475 you can easily generate the command line arguments to pass to gnatmake.
18476
18477 For the sake of completeness, this example assumes that the source path
18478 is not the same as the object path, and that you have two separate lists
18479 of directories.
18480
18481 @smallexample
18482 # see "Automatically creating a list of directories" to create
18483 # these variables
18484 SOURCE_DIRS=
18485 OBJECT_DIRS=
18486
18487 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18488 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18489
18490 all:
18491         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18492 @end smallexample
18493
18494 @node Overcoming Command Line Length Limits
18495 @section Overcoming Command Line Length Limits
18496
18497 @noindent
18498 One problem that might be encountered on big projects is that many
18499 operating systems limit the length of the command line. It is thus hard to give
18500 gnatmake the list of source and object directories.
18501
18502 This example shows how you can set up environment variables, which will
18503 make @command{gnatmake} behave exactly as if the directories had been
18504 specified on the command line, but have a much higher length limit (or
18505 even none on most systems).
18506
18507 It assumes that you have created a list of directories in your Makefile,
18508 using one of the methods presented in
18509 @ref{Automatically Creating a List of Directories}.
18510 For the sake of completeness, we assume that the object
18511 path (where the ALI files are found) is different from the sources patch.
18512
18513 Note a small trick in the Makefile below: for efficiency reasons, we
18514 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18515 expanded immediately by @code{make}. This way we overcome the standard
18516 make behavior which is to expand the variables only when they are
18517 actually used.
18518
18519 On Windows, if you are using the standard Windows command shell, you must
18520 replace colons with semicolons in the assignments to these variables.
18521
18522 @smallexample
18523 @iftex
18524 @leftskip=0cm
18525 @font@heightrm=cmr8
18526 @heightrm
18527 @end iftex
18528 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
18529 # This is the same thing as putting the -I arguments on the command line.
18530 # (the equivalent of using -aI on the command line would be to define
18531 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
18532 # You can of course have different values for these variables.
18533 #
18534 # Note also that we need to keep the previous values of these variables, since
18535 # they might have been set before running 'make' to specify where the GNAT
18536 # library is installed.
18537
18538 # see "Automatically creating a list of directories" to create these
18539 # variables
18540 SOURCE_DIRS=
18541 OBJECT_DIRS=
18542
18543 empty:=
18544 space:=$@{empty@} $@{empty@}
18545 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18546 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18547 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18548 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
18549 export ADA_INCLUDE_PATH
18550 export ADA_OBJECT_PATH
18551
18552 all:
18553         gnatmake main_unit
18554 @end smallexample
18555 @end ifclear
18556
18557 @node Memory Management Issues
18558 @chapter Memory Management Issues
18559
18560 @noindent
18561 This chapter describes some useful memory pools provided in the GNAT library
18562 and in particular the GNAT Debug Pool facility, which can be used to detect
18563 incorrect uses of access values (including ``dangling references'').
18564 @ifclear vms
18565 It also describes the @command{gnatmem} tool, which can be used to track down
18566 ``memory leaks''.
18567 @end ifclear
18568
18569 @menu
18570 * Some Useful Memory Pools::
18571 * The GNAT Debug Pool Facility::
18572 @ifclear vms
18573 * The gnatmem Tool::
18574 @end ifclear
18575 @end menu
18576
18577 @node Some Useful Memory Pools
18578 @section Some Useful Memory Pools
18579 @findex Memory Pool
18580 @cindex storage, pool
18581
18582 @noindent
18583 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18584 storage pool. Allocations use the standard system call @code{malloc} while
18585 deallocations use the standard system call @code{free}. No reclamation is
18586 performed when the pool goes out of scope. For performance reasons, the
18587 standard default Ada allocators/deallocators do not use any explicit storage
18588 pools but if they did, they could use this storage pool without any change in
18589 behavior. That is why this storage pool is used  when the user
18590 manages to make the default implicit allocator explicit as in this example:
18591 @smallexample @c ada
18592    type T1 is access Something;
18593     -- no Storage pool is defined for T2
18594    type T2 is access Something_Else;
18595    for T2'Storage_Pool use T1'Storage_Pool;
18596    -- the above is equivalent to
18597    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18598 @end smallexample
18599
18600 @noindent
18601 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18602 pool. The allocation strategy is similar to @code{Pool_Local}'s
18603 except that the all
18604 storage allocated with this pool is reclaimed when the pool object goes out of
18605 scope. This pool provides a explicit mechanism similar to the implicit one
18606 provided by several Ada 83 compilers for allocations performed through a local
18607 access type and whose purpose was to reclaim memory when exiting the
18608 scope of a given local access. As an example, the following program does not
18609 leak memory even though it does not perform explicit deallocation:
18610
18611 @smallexample @c ada
18612 with System.Pool_Local;
18613 procedure Pooloc1 is
18614    procedure Internal is
18615       type A is access Integer;
18616       X : System.Pool_Local.Unbounded_Reclaim_Pool;
18617       for A'Storage_Pool use X;
18618       v : A;
18619    begin
18620       for I in  1 .. 50 loop
18621          v := new Integer;
18622       end loop;
18623    end Internal;
18624 begin
18625    for I in  1 .. 100 loop
18626       Internal;
18627    end loop;
18628 end Pooloc1;
18629 @end smallexample
18630
18631 @noindent
18632 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18633 @code{Storage_Size} is specified for an access type.
18634 The whole storage for the pool is
18635 allocated at once, usually on the stack at the point where the access type is
18636 elaborated. It is automatically reclaimed when exiting the scope where the
18637 access type is defined. This package is not intended to be used directly by the
18638 user and it is implicitly used for each such declaration:
18639
18640 @smallexample @c ada
18641    type T1 is access Something;
18642    for T1'Storage_Size use 10_000;
18643 @end smallexample
18644
18645 @node The GNAT Debug Pool Facility
18646 @section The GNAT Debug Pool Facility
18647 @findex Debug Pool
18648 @cindex storage, pool, memory corruption
18649
18650 @noindent
18651 The use of unchecked deallocation and unchecked conversion can easily
18652 lead to incorrect memory references. The problems generated by such
18653 references are usually difficult to tackle because the symptoms can be
18654 very remote from the origin of the problem. In such cases, it is
18655 very helpful to detect the problem as early as possible. This is the
18656 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18657
18658 In order to use the GNAT specific debugging pool, the user must
18659 associate a debug pool object with each of the access types that may be
18660 related to suspected memory problems. See Ada Reference Manual 13.11.
18661 @smallexample @c ada
18662 type Ptr is access Some_Type;
18663 Pool : GNAT.Debug_Pools.Debug_Pool;
18664 for Ptr'Storage_Pool use Pool;
18665 @end smallexample
18666
18667 @noindent
18668 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18669 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18670 allow the user to redefine allocation and deallocation strategies. They
18671 also provide a checkpoint for each dereference, through the use of
18672 the primitive operation @code{Dereference} which is implicitly called at
18673 each dereference of an access value.
18674
18675 Once an access type has been associated with a debug pool, operations on
18676 values of the type may raise four distinct exceptions,
18677 which correspond to four potential kinds of memory corruption:
18678 @itemize @bullet
18679 @item
18680 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18681 @item
18682 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18683 @item
18684 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18685 @item
18686 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18687 @end itemize
18688
18689 @noindent
18690 For types associated with a Debug_Pool, dynamic allocation is performed using
18691 the standard GNAT allocation routine. References to all allocated chunks of
18692 memory are kept in an internal dictionary. Several deallocation strategies are
18693 provided, whereupon the user can choose to release the memory to the system,
18694 keep it allocated for further invalid access checks, or fill it with an easily
18695 recognizable pattern for debug sessions. The memory pattern is the old IBM
18696 hexadecimal convention: @code{16#DEADBEEF#}.
18697
18698 See the documentation in the file g-debpoo.ads for more information on the
18699 various strategies.
18700
18701 Upon each dereference, a check is made that the access value denotes a
18702 properly allocated memory location. Here is a complete example of use of
18703 @code{Debug_Pools}, that includes typical instances of  memory corruption:
18704 @smallexample @c ada
18705 @iftex
18706 @leftskip=0cm
18707 @end iftex
18708 with Gnat.Io; use Gnat.Io;
18709 with Unchecked_Deallocation;
18710 with Unchecked_Conversion;
18711 with GNAT.Debug_Pools;
18712 with System.Storage_Elements;
18713 with Ada.Exceptions; use Ada.Exceptions;
18714 procedure Debug_Pool_Test is
18715
18716    type T is access Integer;
18717    type U is access all T;
18718
18719    P : GNAT.Debug_Pools.Debug_Pool;
18720    for T'Storage_Pool use P;
18721
18722    procedure Free is new Unchecked_Deallocation (Integer, T);
18723    function UC is new Unchecked_Conversion (U, T);
18724    A, B : aliased T;
18725
18726    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18727
18728 begin
18729    Info (P);
18730    A := new Integer;
18731    B := new Integer;
18732    B := A;
18733    Info (P);
18734    Free (A);
18735    begin
18736       Put_Line (Integer'Image(B.all));
18737    exception
18738       when E : others => Put_Line ("raised: " & Exception_Name (E));
18739    end;
18740    begin
18741       Free (B);
18742    exception
18743       when E : others => Put_Line ("raised: " & Exception_Name (E));
18744    end;
18745    B := UC(A'Access);
18746    begin
18747       Put_Line (Integer'Image(B.all));
18748    exception
18749       when E : others => Put_Line ("raised: " & Exception_Name (E));
18750    end;
18751    begin
18752       Free (B);
18753    exception
18754       when E : others => Put_Line ("raised: " & Exception_Name (E));
18755    end;
18756    Info (P);
18757 end Debug_Pool_Test;
18758 @end smallexample
18759
18760 @noindent
18761 The debug pool mechanism provides the following precise diagnostics on the
18762 execution of this erroneous program:
18763 @smallexample
18764 Debug Pool info:
18765   Total allocated bytes :  0
18766   Total deallocated bytes :  0
18767   Current Water Mark:  0
18768   High Water Mark:  0
18769
18770 Debug Pool info:
18771   Total allocated bytes :  8
18772   Total deallocated bytes :  0
18773   Current Water Mark:  8
18774   High Water Mark:  8
18775
18776 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18777 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18778 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18779 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18780 Debug Pool info:
18781   Total allocated bytes :  8
18782   Total deallocated bytes :  4
18783   Current Water Mark:  4
18784   High Water Mark:  8
18785 @end smallexample
18786
18787 @ifclear vms
18788 @node The gnatmem Tool
18789 @section The @command{gnatmem} Tool
18790 @findex gnatmem
18791
18792 @noindent
18793 The @code{gnatmem} utility monitors dynamic allocation and
18794 deallocation activity in a program, and displays information about
18795 incorrect deallocations and possible sources of memory leaks.
18796 It provides three type of information:
18797 @itemize @bullet
18798 @item
18799 General information concerning memory management, such as the total
18800 number of allocations and deallocations, the amount of allocated
18801 memory and the high water mark, i.e. the largest amount of allocated
18802 memory in the course of program execution.
18803
18804 @item
18805 Backtraces for all incorrect deallocations, that is to say deallocations
18806 which do not correspond to a valid allocation.
18807
18808 @item
18809 Information on each allocation that is potentially the origin of a memory
18810 leak.
18811 @end itemize
18812
18813 @menu
18814 * Running gnatmem::
18815 * Switches for gnatmem::
18816 * Example of gnatmem Usage::
18817 @end menu
18818
18819 @node Running gnatmem
18820 @subsection Running @code{gnatmem}
18821
18822 @noindent
18823 @code{gnatmem} makes use of the output created by the special version of
18824 allocation and deallocation routines that record call information. This
18825 allows to obtain accurate dynamic memory usage history at a minimal cost to
18826 the execution speed. Note however, that @code{gnatmem} is not supported on
18827 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
18828 Solaris and Windows NT/2000/XP (x86).
18829
18830 @noindent
18831 The @code{gnatmem} command has the form
18832
18833 @smallexample
18834    $ gnatmem [switches] user_program
18835 @end smallexample
18836
18837 @noindent
18838 The program must have been linked with the instrumented version of the
18839 allocation and deallocation routines. This is done by linking with the
18840 @file{libgmem.a} library. For correct symbolic backtrace information,
18841 the user program should be compiled with debugging options
18842 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18843
18844 @smallexample
18845 $ gnatmake -g my_program -largs -lgmem
18846 @end smallexample
18847
18848 @noindent
18849 As library @file{libgmem.a} contains an alternate body for package
18850 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18851 when an executable is linked with library @file{libgmem.a}. It is then not
18852 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
18853
18854 @noindent
18855 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18856 This file contains information about all allocations and deallocations
18857 performed by the program. It is produced by the instrumented allocations and
18858 deallocations routines and will be used by @code{gnatmem}.
18859
18860 In order to produce symbolic backtrace information for allocations and
18861 deallocations performed by the GNAT run-time library, you need to use a
18862 version of that library that has been compiled with the @option{-g} switch
18863 (see @ref{Rebuilding the GNAT Run-Time Library}).
18864
18865 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18866 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18867 @code{-i} switch, gnatmem will assume that this file can be found in the
18868 current directory. For example, after you have executed @file{my_program},
18869 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18870
18871 @smallexample
18872 $ gnatmem my_program
18873 @end smallexample
18874
18875 @noindent
18876 This will produce the output with the following format:
18877
18878 *************** debut cc
18879 @smallexample
18880 $ gnatmem my_program
18881
18882 Global information
18883 ------------------
18884    Total number of allocations        :  45
18885    Total number of deallocations      :   6
18886    Final Water Mark (non freed mem)   :  11.29 Kilobytes
18887    High Water Mark                    :  11.40 Kilobytes
18888
18889 .
18890 .
18891 .
18892 Allocation Root # 2
18893 -------------------
18894  Number of non freed allocations    :  11
18895  Final Water Mark (non freed mem)   :   1.16 Kilobytes
18896  High Water Mark                    :   1.27 Kilobytes
18897  Backtrace                          :
18898    my_program.adb:23 my_program.alloc
18899 .
18900 .
18901 .
18902 @end smallexample
18903
18904 The first block of output gives general information. In this case, the
18905 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18906 Unchecked_Deallocation routine occurred.
18907
18908 @noindent
18909 Subsequent paragraphs display  information on all allocation roots.
18910 An allocation root is a specific point in the execution of the program
18911 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18912 construct. This root is represented by an execution backtrace (or subprogram
18913 call stack). By default the backtrace depth for allocations roots is 1, so
18914 that a root corresponds exactly to a source location. The backtrace can
18915 be made deeper, to make the root more specific.
18916
18917 @node Switches for gnatmem
18918 @subsection Switches for @code{gnatmem}
18919
18920 @noindent
18921 @code{gnatmem} recognizes the following switches:
18922
18923 @table @option
18924
18925 @item -q
18926 @cindex @option{-q} (@code{gnatmem})
18927 Quiet. Gives the minimum output needed to identify the origin of the
18928 memory leaks. Omits statistical information.
18929
18930 @item @var{N}
18931 @cindex @var{N} (@code{gnatmem})
18932 N is an integer literal (usually between 1 and 10) which controls the
18933 depth of the backtraces defining allocation root. The default value for
18934 N is 1. The deeper the backtrace, the more precise the localization of
18935 the root. Note that the total number of roots can depend on this
18936 parameter. This parameter must be specified @emph{before} the name of the
18937 executable to be analyzed, to avoid ambiguity.
18938
18939 @item -b n
18940 @cindex @option{-b} (@code{gnatmem})
18941 This switch has the same effect as just depth parameter.
18942
18943 @item -i @var{file}
18944 @cindex @option{-i} (@code{gnatmem})
18945 Do the @code{gnatmem} processing starting from @file{file}, rather than
18946 @file{gmem.out} in the current directory.
18947
18948 @item -m n
18949 @cindex @option{-m} (@code{gnatmem})
18950 This switch causes @code{gnatmem} to mask the allocation roots that have less
18951 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18952 examine even the roots that didn't result in leaks.
18953
18954 @item -s order
18955 @cindex @option{-s} (@code{gnatmem})
18956 This switch causes @code{gnatmem} to sort the allocation roots according to the
18957 specified order of sort criteria, each identified by a single letter. The
18958 currently supported criteria are @code{n, h, w} standing respectively for
18959 number of unfreed allocations, high watermark, and final watermark
18960 corresponding to a specific root. The default order is @code{nwh}.
18961
18962 @end table
18963
18964 @node Example of gnatmem Usage
18965 @subsection Example of @code{gnatmem} Usage
18966
18967 @noindent
18968 The following example shows the use of @code{gnatmem}
18969 on a simple memory-leaking program.
18970 Suppose that we have the following Ada program:
18971
18972 @smallexample @c ada
18973 @group
18974 @cartouche
18975 with Unchecked_Deallocation;
18976 procedure Test_Gm is
18977
18978    type T is array (1..1000) of Integer;
18979    type Ptr is access T;
18980    procedure Free is new Unchecked_Deallocation (T, Ptr);
18981    A : Ptr;
18982
18983    procedure My_Alloc is
18984    begin
18985       A := new T;
18986    end My_Alloc;
18987
18988    procedure My_DeAlloc is
18989       B : Ptr := A;
18990    begin
18991       Free (B);
18992    end My_DeAlloc;
18993
18994 begin
18995    My_Alloc;
18996    for I in 1 .. 5 loop
18997       for J in I .. 5 loop
18998          My_Alloc;
18999       end loop;
19000       My_Dealloc;
19001    end loop;
19002 end;
19003 @end cartouche
19004 @end group
19005 @end smallexample
19006
19007 @noindent
19008 The program needs to be compiled with debugging option and linked with
19009 @code{gmem} library:
19010
19011 @smallexample
19012 $ gnatmake -g test_gm -largs -lgmem
19013 @end smallexample
19014
19015 @noindent
19016 Then we execute the program as usual:
19017
19018 @smallexample
19019 $ test_gm
19020 @end smallexample
19021
19022 @noindent
19023 Then @code{gnatmem} is invoked simply with
19024 @smallexample
19025 $ gnatmem test_gm
19026 @end smallexample
19027
19028 @noindent
19029 which produces the following output (result may vary on different platforms):
19030
19031 @smallexample
19032 Global information
19033 ------------------
19034    Total number of allocations        :  18
19035    Total number of deallocations      :   5
19036    Final Water Mark (non freed mem)   :  53.00 Kilobytes
19037    High Water Mark                    :  56.90 Kilobytes
19038
19039 Allocation Root # 1
19040 -------------------
19041  Number of non freed allocations    :  11
19042  Final Water Mark (non freed mem)   :  42.97 Kilobytes
19043  High Water Mark                    :  46.88 Kilobytes
19044  Backtrace                          :
19045    test_gm.adb:11 test_gm.my_alloc
19046
19047 Allocation Root # 2
19048 -------------------
19049  Number of non freed allocations    :   1
19050  Final Water Mark (non freed mem)   :  10.02 Kilobytes
19051  High Water Mark                    :  10.02 Kilobytes
19052  Backtrace                          :
19053    s-secsta.adb:81 system.secondary_stack.ss_init
19054
19055 Allocation Root # 3
19056 -------------------
19057  Number of non freed allocations    :   1
19058  Final Water Mark (non freed mem)   :  12 Bytes
19059  High Water Mark                    :  12 Bytes
19060  Backtrace                          :
19061    s-secsta.adb:181 system.secondary_stack.ss_init
19062 @end smallexample
19063
19064 @noindent
19065 Note that the GNAT run time contains itself a certain number of
19066 allocations that have no  corresponding deallocation,
19067 as shown here for root #2 and root
19068 #3. This is a normal behavior when the number of non freed allocations
19069 is one, it allocates dynamic data structures that the run time needs for
19070 the complete lifetime of the program. Note also that there is only one
19071 allocation root in the user program with a single line back trace:
19072 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
19073 program shows that 'My_Alloc' is called at 2 different points in the
19074 source (line 21 and line 24). If those two allocation roots need to be
19075 distinguished, the backtrace depth parameter can be used:
19076
19077 @smallexample
19078 $ gnatmem 3 test_gm
19079 @end smallexample
19080
19081 @noindent
19082 which will give the following output:
19083
19084 @smallexample
19085 Global information
19086 ------------------
19087    Total number of allocations        :  18
19088    Total number of deallocations      :   5
19089    Final Water Mark (non freed mem)   :  53.00 Kilobytes
19090    High Water Mark                    :  56.90 Kilobytes
19091
19092 Allocation Root # 1
19093 -------------------
19094  Number of non freed allocations    :  10
19095  Final Water Mark (non freed mem)   :  39.06 Kilobytes
19096  High Water Mark                    :  42.97 Kilobytes
19097  Backtrace                          :
19098    test_gm.adb:11 test_gm.my_alloc
19099    test_gm.adb:24 test_gm
19100    b_test_gm.c:52 main
19101
19102 Allocation Root # 2
19103 -------------------
19104  Number of non freed allocations    :   1
19105  Final Water Mark (non freed mem)   :  10.02 Kilobytes
19106  High Water Mark                    :  10.02 Kilobytes
19107  Backtrace                          :
19108    s-secsta.adb:81  system.secondary_stack.ss_init
19109    s-secsta.adb:283 <system__secondary_stack___elabb>
19110    b_test_gm.c:33   adainit
19111
19112 Allocation Root # 3
19113 -------------------
19114  Number of non freed allocations    :   1
19115  Final Water Mark (non freed mem)   :   3.91 Kilobytes
19116  High Water Mark                    :   3.91 Kilobytes
19117  Backtrace                          :
19118    test_gm.adb:11 test_gm.my_alloc
19119    test_gm.adb:21 test_gm
19120    b_test_gm.c:52 main
19121
19122 Allocation Root # 4
19123 -------------------
19124  Number of non freed allocations    :   1
19125  Final Water Mark (non freed mem)   :  12 Bytes
19126  High Water Mark                    :  12 Bytes
19127  Backtrace                          :
19128    s-secsta.adb:181 system.secondary_stack.ss_init
19129    s-secsta.adb:283 <system__secondary_stack___elabb>
19130    b_test_gm.c:33   adainit
19131 @end smallexample
19132
19133 @noindent
19134 The allocation root #1 of the first example has been split in 2 roots #1
19135 and #3 thanks to the more precise associated backtrace.
19136
19137 @end ifclear
19138
19139 @node Stack Related Facilities
19140 @chapter Stack Related Facilities
19141
19142 @noindent
19143 This chapter describes some useful tools associated with stack
19144 checking and analysis. In
19145 particular, it deals with dynamic and static stack usage measurements.
19146
19147 @menu
19148 * Stack Overflow Checking::
19149 * Static Stack Usage Analysis::
19150 * Dynamic Stack Usage Analysis::
19151 @end menu
19152
19153 @node Stack Overflow Checking
19154 @section Stack Overflow Checking
19155 @cindex Stack Overflow Checking
19156 @cindex -fstack-check
19157
19158 @noindent
19159 For most operating systems, @command{gcc} does not perform stack overflow
19160 checking by default. This means that if the main environment task or
19161 some other task exceeds the available stack space, then unpredictable
19162 behavior will occur. Most native systems offer some level of protection by
19163 adding a guard page at the end of each task stack. This mechanism is usually
19164 not enough for dealing properly with stack overflow situations because
19165 a large local variable could ``jump'' above the guard page.
19166 Furthermore, when the
19167 guard page is hit, there may not be any space left on the stack for executing
19168 the exception propagation code. Enabling stack checking avoids
19169 such situations.
19170
19171 To activate stack checking, compile all units with the gcc option
19172 @option{-fstack-check}. For example:
19173
19174 @smallexample
19175 gcc -c -fstack-check package1.adb
19176 @end smallexample
19177
19178 @noindent
19179 Units compiled with this option will generate extra instructions to check
19180 that any use of the stack (for procedure calls or for declaring local
19181 variables in declare blocks) does not exceed the available stack space.
19182 If the space is exceeded, then a @code{Storage_Error} exception is raised.
19183
19184 For declared tasks, the stack size is controlled by the size
19185 given in an applicable @code{Storage_Size} pragma or by the value specified
19186 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
19187 the default size as defined in the GNAT runtime otherwise.
19188
19189 For the environment task, the stack size depends on
19190 system defaults and is unknown to the compiler. Stack checking
19191 may still work correctly if a fixed
19192 size stack is allocated, but this cannot be guaranteed.
19193 To ensure that a clean exception is signalled for stack
19194 overflow, set the environment variable
19195 @code{GNAT_STACK_LIMIT} to indicate the maximum
19196 stack area that can be used, as in:
19197 @cindex GNAT_STACK_LIMIT
19198
19199 @smallexample
19200 SET GNAT_STACK_LIMIT 1600
19201 @end smallexample
19202
19203 @noindent
19204 The limit is given in kilobytes, so the above declaration would
19205 set the stack limit of the environment task to 1.6 megabytes.
19206 Note that the only purpose of this usage is to limit the amount
19207 of stack used by the environment task. If it is necessary to
19208 increase the amount of stack for the environment task, then this
19209 is an operating systems issue, and must be addressed with the
19210 appropriate operating systems commands.
19211
19212 @node Static Stack Usage Analysis
19213 @section Static Stack Usage Analysis
19214 @cindex Static Stack Usage Analysis
19215 @cindex -fstack-usage
19216
19217 @noindent
19218 A unit compiled with @option{-fstack-usage} will generate an extra file
19219 that specifies
19220 the maximum amount of stack used, on a per-function basis.
19221 The file has the same
19222 basename as the target object file with a @file{.su} extension.
19223 Each line of this file is made up of three fields:
19224
19225 @itemize
19226 @item
19227 The name of the function.
19228 @item
19229 A number of bytes.
19230 @item
19231 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
19232 @end itemize
19233
19234 The second field corresponds to the size of the known part of the function
19235 frame.
19236
19237 The qualifier @code{static} means that the function frame size
19238 is purely static.
19239 It usually means that all local variables have a static size.
19240 In this case, the second field is a reliable measure of the function stack
19241 utilization.
19242
19243 The qualifier @code{dynamic} means that the function frame size is not static.
19244 It happens mainly when some local variables have a dynamic size. When this
19245 qualifier appears alone, the second field is not a reliable measure
19246 of the function stack analysis. When it is qualified with  @code{bounded}, it
19247 means that the second field is a reliable maximum of the function stack
19248 utilization.
19249
19250 @node Dynamic Stack Usage Analysis
19251 @section Dynamic Stack Usage Analysis
19252
19253 @noindent
19254 It is possible to measure the maximum amount of stack used by a task, by
19255 adding a switch to @command{gnatbind}, as:
19256
19257 @smallexample
19258 $ gnatbind -u0 file
19259 @end smallexample
19260
19261 @noindent
19262 With this option, at each task termination, its stack usage is  output on
19263 @file{stderr}.
19264 It is not always convenient to output the stack usage when the program
19265 is still running. Hence, it is possible to delay this output until program
19266 termination. for a given number of tasks specified as the argument of the
19267 @code{-u} option. For instance:
19268
19269 @smallexample
19270 $ gnatbind -u100 file
19271 @end smallexample
19272
19273 @noindent
19274 will buffer the stack usage information of the first 100 tasks to terminate and
19275 output this info at program termination. Results are displayed in four
19276 columns:
19277
19278 @noindent
19279 Index | Task Name | Stack Size | Actual Use [min - max]
19280
19281 @noindent
19282 where:
19283
19284 @table @emph
19285 @item Index
19286 is a number associated with each task.
19287
19288 @item Task Name
19289 is the name of the task analyzed.
19290
19291 @item Stack Size
19292 is the maximum size for the stack.
19293
19294 @item Actual Use
19295 is the measure done by the stack analyzer. In order to prevent overflow,
19296 the stack is not entirely analyzed, and it's not possible to know exactly how
19297 much has actually been used. The real amount of stack used is between the min
19298 and max values.
19299
19300 @end table
19301
19302 @noindent
19303 The environment task stack, e.g. the stack that contains the main unit, is
19304 only processed when the environment variable GNAT_STACK_LIMIT is set.
19305
19306
19307 @c *********************************
19308 @c *            GNATCHECK          *
19309 @c *********************************
19310 @node Verifying Properties Using gnatcheck
19311 @chapter Verifying Properties Using @command{gnatcheck}
19312 @findex gnatcheck
19313 @cindex @command{gnatcheck}
19314
19315 @noindent
19316 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
19317 of Ada source files according to a given set of semantic rules.
19318 @cindex ASIS
19319
19320 In order to check compliance with a given rule, @command{gnatcheck} has to
19321 semantically analyze the Ada sources.
19322 Therefore, checks can only be performed on
19323 legal Ada units. Moreover, when a unit depends semantically upon units located
19324 outside the current directory, the source search path has to be provided when
19325 calling @command{gnatcheck}, either through a specified project file or
19326 through @command{gnatcheck} switches as described below.
19327
19328 A number of rules are predefined in @command{gnatcheck} and are described
19329 later in this chapter.
19330 You can also add new rules, by modifying the @command{gnatcheck} code and
19331 rebuilding the tool. In order to add a simple rule making some local checks,
19332 a small amount of straightforward ASIS-based programming is usually needed.
19333
19334 Project support for @command{gnatcheck} is provided by the GNAT
19335 driver (see @ref{The GNAT Driver and Project Files}).
19336
19337 Invoking @command{gnatcheck} on the command line has the form:
19338
19339 @smallexample
19340 $ gnatcheck [@i{switches}]  @{@i{filename}@}
19341       [^-files^/FILES^=@{@i{arg_list_filename}@}]
19342       [-cargs @i{gcc_switches}] [-rules @i{rule_options}]
19343 @end smallexample
19344
19345 @noindent
19346 where
19347 @itemize @bullet
19348 @item
19349 @i{switches} specify the general tool options
19350
19351 @item
19352 Each @i{filename} is the name (including the extension) of a source
19353 file to process. ``Wildcards'' are allowed, and
19354 the file name may contain path information.
19355
19356 @item
19357 Each @i{arg_list_filename} is the name (including the extension) of a text
19358 file containing the names of the source files to process, separated by spaces
19359 or line breaks.
19360
19361 @item
19362 @i{gcc_switches} is a list of switches for
19363 @command{gcc}. They will be passed on to all compiler invocations made by
19364 @command{gnatcheck} to generate the ASIS trees. Here you can provide
19365 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19366 and use the @option{-gnatec} switch to set the configuration file.
19367
19368 @item
19369 @i{rule_options} is a list of options for controlling a set of
19370 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
19371 @end itemize
19372
19373 @noindent
19374 Either a @i{filename} or an @i{arg_list_filename} must be supplied.
19375
19376 @menu
19377 * Format of the Report File::
19378 * General gnatcheck Switches::
19379 * gnatcheck Rule Options::
19380 * Adding the Results of Compiler Checks to gnatcheck Output::
19381 * Project-Wide Checks::
19382 * Predefined Rules::
19383 @end menu
19384
19385 @node Format of the Report File
19386 @section Format of the Report File
19387 @cindex Report file (for @code{gnatcheck})
19388
19389 @noindent
19390 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
19391 rule violations.
19392 It also creates, in the current
19393 directory, a text file named @file{^gnatcheck.out^GNATCHECK.OUT^} that
19394 contains the complete report of the last gnatcheck run. This report contains:
19395 @itemize @bullet
19396 @item a list of the Ada source files being checked,
19397 @item a list of enabled and disabled rules,
19398 @item a list of the diagnostic messages, ordered in three different ways
19399 and collected in three separate
19400 sections. Section 1 contains the raw list of diagnostic messages. It
19401 corresponds to the output going to @file{stdout}. Section 2 contains
19402 messages ordered by rules.
19403 Section 3 contains messages ordered by source files.
19404 @end itemize
19405
19406 @node General gnatcheck Switches
19407 @section General @command{gnatcheck} Switches
19408
19409 @noindent
19410 The following switches control the general @command{gnatcheck} behavior
19411
19412 @table @option
19413 @c !sort!
19414 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
19415 @item ^-a^/ALL^
19416 Process all units including those with read-only ALI files such as
19417 those from GNAT Run-Time library.
19418
19419 @ifclear vms
19420 @ignore
19421 @cindex @option{-d} (@command{gnatcheck})
19422 @item -d
19423 Debug mode
19424 @end ignore
19425
19426 @cindex @option{-dd} (@command{gnatcheck})
19427 @item -dd
19428 Progress indicator mode (for use in GPS)
19429 @end ifclear
19430
19431 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
19432 @item ^-h^/HELP^
19433 List the predefined and user-defined rules. For more details see
19434 @ref{Predefined Rules}.
19435
19436 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
19437 @item ^-l^/LOCS^
19438 Use full source locations references in the report file. For a construct from
19439 a generic instantiation a full source location is a chain from the location
19440 of this construct in the generic unit to the place where this unit is
19441 instantiated.
19442
19443 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
19444 @item ^-q^/QUIET^
19445 Quiet mode. All the diagnoses about rule violations are placed in the
19446 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
19447
19448 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
19449 @item ^-s^/SHORT^
19450 Short format of the report file (no version information, no list of applied
19451 rules, no list of checked sources is included)
19452
19453 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
19454 @item ^-s1^/COMPILER_STYLE^
19455 Include the compiler-style section in the report file
19456
19457 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
19458 @item ^-s2^/BY_RULES^
19459 Include the section containing diagnoses ordered by rules in the report file
19460
19461 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
19462 @item ^-s3^/BY_FILES_BY_RULES^
19463 Include the section containing diagnoses ordered by files and then by rules
19464 in the report file
19465
19466 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
19467 @item ^-v^/VERBOSE^
19468 Verbose mode; @command{gnatcheck} generates version information and then
19469 a trace of sources being processed.
19470
19471 @end table
19472
19473 @noindent
19474 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
19475 @option{^-s2^/BY_RULES^} or
19476 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
19477 then the  @command{gnatcheck} report file will only contain sections
19478 explicitly denoted by these options.
19479
19480 @node gnatcheck Rule Options
19481 @section @command{gnatcheck} Rule Options
19482
19483 @noindent
19484 The following options control the processing performed by
19485 @command{gnatcheck}.
19486
19487 @table @option
19488 @cindex @option{+ALL} (@command{gnatcheck})
19489 @item +ALL
19490 Turn all the rule checks ON.
19491
19492 @cindex @option{-ALL} (@command{gnatcheck})
19493 @item -ALL
19494 Turn all the rule checks OFF.
19495
19496 @cindex @option{+R} (@command{gnatcheck})
19497 @item +R@i{rule_id[:param]}
19498 Turn on the check for a specified rule with the specified parameter, if any.
19499 @i{rule_id} must be the identifier of one of the currently implemented rules
19500 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
19501 are not case-sensitive. The @i{param} item must
19502 be a string representing a valid parameter(s) for the specified rule.
19503 If it contains any space characters then this string must be enclosed in
19504 quotation marks.
19505
19506 @cindex @option{-R} (@command{gnatcheck})
19507 @item -R@i{rule_id[:param]}
19508 Turn off the check for a specified rule with the specified parameter, if any.
19509
19510 @cindex @option{-from} (@command{gnatcheck})
19511 @item -from=@i{rule_option_filename}
19512 Read the rule options from the text file @i{rule_option_filename}, referred as
19513 ``rule file'' below.
19514
19515 @end table
19516
19517 @noindent
19518 The default behavior is that all the rule checks are enabled, except for
19519 the checks performed by the compiler.
19520 @ignore
19521 and the checks associated with the
19522 global rules.
19523 @end ignore
19524
19525 A rule file is a text file containing a set of rule options.
19526 @cindex Rule file (for @code{gnatcheck})
19527 The file may contain empty lines and Ada-style comments (comment
19528 lines and end-of-line comments). The rule file has free format; that is,
19529 you do not have to start a new rule option on a new line.
19530
19531 A rule file may contain other @option{-from=@i{rule_option_filename}}
19532 options, each such option being replaced with the content of the
19533 corresponding rule file during the rule files processing. In case a
19534 cycle is detected (that is, @i{rule_file_1} reads rule options from
19535 @i{rule_file_2}, and  @i{rule_file_2} reads (directly or indirectly)
19536 rule options from @i{rule_file_1}), the processing
19537 of rule files is interrupted and a part of their content is ignored.
19538
19539
19540 @node Adding the Results of Compiler Checks to gnatcheck Output
19541 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
19542
19543 @noindent
19544 The @command{gnatcheck} tool can include in the generated diagnostic messages
19545 and in
19546 the report file the results of the checks performed by the compiler. Though
19547 disabled by default, this effect may be obtained by using @option{+R} with
19548 the following rule identifiers and parameters:
19549
19550 @table @option
19551 @item Restrictions
19552 To record restrictions violations (that are performed by the compiler if the
19553 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
19554 use the rule named
19555 @code{Restrictions} with the same parameters as pragma
19556 @code{Restrictions} or @code{Restriction_Warnings}.
19557
19558 @item Style_Checks
19559 To record compiler style checks, use the rule named
19560 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
19561 which enables all the style checks, or a string that has exactly the same
19562 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
19563 @code{Style_Checks} (for further information about this pragma, please
19564 refer to the @cite{@value{EDITION} Reference Manual}).
19565
19566 @item Warnings
19567 To record compiler warnings (@pxref{Warning Message Control}), use the rule
19568 named @code{Warnings} with a parameter that is a valid
19569 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
19570 (for further information about this pragma, please
19571 refer to the @cite{@value{EDITION} Reference Manual}).
19572
19573 @end table
19574
19575 @node Project-Wide Checks
19576 @section Project-Wide Checks
19577 @cindex Project-wide checks (for @command{gnatcheck})
19578
19579 @noindent
19580 In order to perform checks on all units of a given project, you can use
19581 the GNAT driver along with the @option{-P} option:
19582 @smallexample
19583    gnat check -Pproj -rules -from=my_rules
19584 @end smallexample
19585
19586 @noindent
19587 If the project @code{proj} depends upon other projects, you can perform
19588 checks on the project closure using the @option{-U} option:
19589 @smallexample
19590    gnat check -Pproj -U -rules -from=my_rules
19591 @end smallexample
19592
19593 @noindent
19594 Finally, if not all the units are relevant to a particular main
19595 program in the project closure, you can perform checks for the set
19596 of units needed to create a given main program (unit closure) using
19597 the @option{-U} option followed by the name of the main unit:
19598 @smallexample
19599    gnat check -Pproj -U main -rules -from=my_rules
19600 @end smallexample
19601
19602
19603 @node Predefined Rules
19604 @section Predefined Rules
19605 @cindex Predefined rules (for @command{gnatcheck})
19606
19607 @ignore
19608 @c (Jan 2007) Since the global rules are still under development and are not
19609 @c documented, there is no point in explaining the difference between
19610 @c global and local rules
19611 @noindent
19612 A rule in @command{gnatcheck} is either local or global.
19613 A @emph{local rule} is a rule that applies to a well-defined section
19614 of a program and that can be checked by analyzing only this section.
19615 A @emph{global rule} requires analysis of some global properties of the
19616 whole program (mostly related to the program call graph).
19617 As of @value{NOW}, the implementation of global rules should be
19618 considered to be at a preliminary stage. You can use the
19619 @option{+GLOBAL} option to enable all the global rules, and the
19620 @option{-GLOBAL} rule option to disable all the global rules.
19621
19622 All the global rules in the list below are
19623 so indicated by marking them ``GLOBAL''.
19624 This +GLOBAL and -GLOBAL options are not
19625 included in the list of gnatcheck options above, because at the moment they
19626 are considered as a temporary debug options.
19627
19628 @command{gnatcheck} performs rule checks for generic
19629 instances only for global rules.  This limitation may be relaxed in a later
19630 release.
19631 @end ignore
19632
19633 @noindent
19634 The following subsections document the rules implemented in
19635 @command{gnatcheck}.
19636 The subsection title is the same as the rule identifier, which may be
19637 used as a parameter of the @option{+R} or @option{-R} options.
19638
19639
19640 @menu
19641 * Abstract_Type_Declarations::
19642 * Anonymous_Arrays::
19643 * Anonymous_Subtypes::
19644 * Blocks::
19645 * Boolean_Relational_Operators::
19646 @ignore
19647 * Ceiling_Violations::
19648 @end ignore
19649 * Controlled_Type_Declarations::
19650 * Declarations_In_Blocks::
19651 * Default_Parameters::
19652 * Discriminated_Records::
19653 * Enumeration_Ranges_In_CASE_Statements::
19654 * Exceptions_As_Control_Flow::
19655 * EXIT_Statements_With_No_Loop_Name::
19656 * Expanded_Loop_Exit_Names::
19657 * Explicit_Full_Discrete_Ranges::
19658 * Float_Equality_Checks::
19659 * Forbidden_Pragmas::
19660 * Function_Style_Procedures::
19661 * Generics_In_Subprograms::
19662 * GOTO_Statements::
19663 * Implicit_IN_Mode_Parameters::
19664 * Implicit_SMALL_For_Fixed_Point_Types::
19665 * Improperly_Located_Instantiations::
19666 * Improper_Returns::
19667 * Library_Level_Subprograms::
19668 * Local_Packages::
19669 @ignore
19670 * Improperly_Called_Protected_Entries::
19671 @end ignore
19672 * Misnamed_Identifiers::
19673 * Multiple_Entries_In_Protected_Definitions::
19674 * Name_Clashes::
19675 * Non_Qualified_Aggregates::
19676 * Non_Short_Circuit_Operators::
19677 * Non_SPARK_Attributes::
19678 * Non_Tagged_Derived_Types::
19679 * Non_Visible_Exceptions::
19680 * Numeric_Literals::
19681 * OTHERS_In_Aggregates::
19682 * OTHERS_In_CASE_Statements::
19683 * OTHERS_In_Exception_Handlers::
19684 * Outer_Loop_Exits::
19685 * Overloaded_Operators::
19686 * Overly_Nested_Control_Structures::
19687 * Parameters_Out_Of_Order::
19688 * Positional_Actuals_For_Defaulted_Generic_Parameters::
19689 * Positional_Actuals_For_Defaulted_Parameters::
19690 * Positional_Components::
19691 * Positional_Generic_Parameters::
19692 * Positional_Parameters::
19693 * Predefined_Numeric_Types::
19694 * Raising_External_Exceptions::
19695 * Raising_Predefined_Exceptions::
19696 @ignore
19697 * Recursion::
19698 * Side_Effect_Functions::
19699 @end ignore
19700 * Slices::
19701 * Unassigned_OUT_Parameters::
19702 * Uncommented_BEGIN_In_Package_Bodies::
19703 * Unconstrained_Array_Returns::
19704 * Universal_Ranges::
19705 * Unnamed_Blocks_And_Loops::
19706 @ignore
19707 * Unused_Subprograms::
19708 @end ignore
19709 * USE_PACKAGE_Clauses::
19710 * Volatile_Objects_Without_Address_Clauses::
19711 @end menu
19712
19713
19714 @node Abstract_Type_Declarations
19715 @subsection @code{Abstract_Type_Declarations}
19716 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
19717
19718 @noindent
19719 Flag all declarations of abstract types. For an abstract private
19720 type, both the private and full type declarations are flagged.
19721
19722 This rule has no parameters.
19723
19724
19725 @node Anonymous_Arrays
19726 @subsection @code{Anonymous_Arrays}
19727 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
19728
19729 @noindent
19730 Flag all anonymous array type definitions (by Ada semantics these can only
19731 occur in object declarations).
19732
19733 This rule has no parameters.
19734
19735 @node Anonymous_Subtypes
19736 @subsection @code{Anonymous_Subtypes}
19737 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
19738
19739 @noindent
19740 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
19741 any instance of a subtype indication with a constraint, other than one
19742 that occurs immediately within a subtype declaration. Any use of a range
19743 other than as a constraint used immediately within a subtype declaration
19744 is considered as an anonymous subtype.
19745
19746 An effect of this rule is that @code{for} loops such as the following are
19747 flagged (since @code{1..N} is formally a ``range''):
19748
19749 @smallexample @c ada
19750 for I in 1 .. N loop
19751    ...
19752 end loop;
19753 @end smallexample
19754
19755 @noindent
19756 Declaring an explicit subtype solves the problem:
19757
19758 @smallexample @c ada
19759 subtype S is Integer range 1..N;
19760 ...
19761 for I in S loop
19762    ...
19763 end loop;
19764 @end smallexample
19765
19766 @noindent
19767 This rule has no parameters.
19768
19769 @node Blocks
19770 @subsection @code{Blocks}
19771 @cindex @code{Blocks} rule (for @command{gnatcheck})
19772
19773 @noindent
19774 Flag each block statement.
19775
19776 This rule has no parameters.
19777
19778 @node Boolean_Relational_Operators
19779 @subsection @code{Boolean_Relational_Operators}
19780 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
19781
19782 @noindent
19783 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
19784 ``>='', ``='' and ``/='') for the predefined @code{Boolean} type.
19785 (This rule is useful in enforcing the SPARK language restrictions.)
19786
19787 Calls to predefined relational operators of any type derived from
19788 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
19789 with these designators, and uses of operators that are renamings
19790 of the predefined relational operators for @code{Standard.Boolean},
19791 are likewise not detected.
19792
19793 This rule has no parameters.
19794
19795 @ignore
19796 @node Ceiling_Violations
19797 @subsection @code{Ceiling_Violations} (under construction, GLOBAL)
19798 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
19799
19800 @noindent
19801 Flag invocations of a protected operation by a task whose priority exceeds
19802 the protected object's ceiling.
19803
19804 As of @value{NOW}, this rule has the following limitations:
19805
19806 @itemize @bullet
19807
19808 @item
19809  We consider only pragmas Priority and Interrupt_Priority as means to define
19810   a task/protected operation priority. We do not consider the effect of using
19811   Ada.Dynamic_Priorities.Set_Priority procedure;
19812
19813 @item
19814  We consider only base task priorities, and no priority inheritance. That is,
19815   we do not make a difference between calls issued during task activation and
19816   execution of the sequence of statements from task body;
19817
19818 @item
19819  Any situation when the priority of protected operation caller is set by a
19820   dynamic expression (that is, the corresponding Priority or
19821   Interrupt_Priority pragma has a non-static expression as an argument) we
19822   treat as a priority inconsistency (and, therefore, detect this situation).
19823 @end itemize
19824
19825 @noindent
19826 At the moment the notion of the main subprogram is not implemented in
19827 gnatcheck, so any pragma Priority in a library level subprogram body (in case
19828 if this subprogram can be a main subprogram of a partition) changes the
19829 priority of an environment task. So if we have more then one such pragma in
19830 the set of processed sources, the pragma that is processed last, defines the
19831 priority of an environment task.
19832
19833 This rule has no parameters.
19834 @end ignore
19835
19836 @node Controlled_Type_Declarations
19837 @subsection @code{Controlled_Type_Declarations}
19838 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
19839
19840 @noindent
19841 Flag all declarations of controlled types. A declaration of a private type
19842 is flagged if its full declaration declares a controlled type. A declaration
19843 of a derived type is flagged if its ancestor type is controlled. Subtype
19844 declarations are not checked. A declaration of a type that itself is not a
19845 descendant of a type declared in @code{Ada.Finalization} but has a controlled
19846 component is not checked.
19847
19848 This rule has no parameters.
19849
19850
19851
19852 @node Declarations_In_Blocks
19853 @subsection @code{Declarations_In_Blocks}
19854 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
19855
19856 @noindent
19857 Flag all block statements containing local declarations. A @code{declare}
19858 block with an empty @i{declarative_part} or with a @i{declarative part}
19859 containing only pragmas and/or @code{use} clauses is not flagged.
19860
19861 This rule has no parameters.
19862
19863
19864 @node Default_Parameters
19865 @subsection @code{Default_Parameters}
19866 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
19867
19868 @noindent
19869 Flag all default expressions for subprogram parameters. Parameter
19870 declarations of formal and generic subprograms are also checked.
19871
19872 This rule has no parameters.
19873
19874
19875 @node Discriminated_Records
19876 @subsection @code{Discriminated_Records}
19877 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
19878
19879 @noindent
19880 Flag all declarations of record types with discriminants. Only the
19881 declarations of record and record extension types are checked. Incomplete,
19882 formal, private, derived and private extension type declarations are not
19883 checked. Task and protected type declarations also are not checked.
19884
19885 This rule has no parameters.
19886
19887
19888 @node Enumeration_Ranges_In_CASE_Statements
19889 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
19890 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
19891
19892 @noindent
19893 Flag each use of a range of enumeration literals as a choice in a
19894 @code{case} statement.
19895 All forms for specifying a range (explicit ranges
19896 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
19897 An enumeration range is
19898 flagged even if contains exactly one enumeration value or no values at all. A
19899 type derived fom an enumeration type is considered as an enumeration type.
19900
19901 This rule helps prevent maintenance problems arising from adding an
19902 enumeration value to a type and having it implicitly handled by an existing
19903 @code{case} statement with an enumeration range that includes the new literal.
19904
19905 This rule has no parameters.
19906
19907
19908 @node Exceptions_As_Control_Flow
19909 @subsection @code{Exceptions_As_Control_Flow}
19910 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
19911
19912 @noindent
19913 Flag each place where an exception is explictly raised and handled in the
19914 same subprogram body. A @code{raise} statement in an exception handler,
19915 package body, task body or entry body is not flagged.
19916
19917 The rule has no parameters.
19918
19919 @node EXIT_Statements_With_No_Loop_Name
19920 @subsection @code{EXIT_Statements_With_No_Loop_Name}
19921 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
19922
19923 @noindent
19924 Flag each @code{exit} statement that does not specify the name of the loop
19925 being exited.
19926
19927 The rule has no parameters.
19928
19929
19930 @node Expanded_Loop_Exit_Names
19931 @subsection @code{Expanded_Loop_Exit_Names}
19932 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
19933
19934 @noindent
19935 Flag all expanded loop names in @code{exit} statements.
19936
19937 This rule has no parameters.
19938
19939 @node Explicit_Full_Discrete_Ranges
19940 @subsection @code{Explicit_Full_Discrete_Ranges}
19941 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
19942
19943 @noindent
19944 Flag each discrete range that has the form @code{A'First .. A'Last}.
19945
19946 This rule has no parameters.
19947
19948 @node Float_Equality_Checks
19949 @subsection @code{Float_Equality_Checks}
19950 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
19951
19952 @noindent
19953 Flag all calls to the predefined equality operations for floating-point types.
19954 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
19955 User-defined equality operations are not flagged, nor are ``@code{=}''
19956 and ``@code{/=}'' operations for fixed-point types.
19957
19958 This rule has no parameters.
19959
19960
19961 @node Forbidden_Pragmas
19962 @subsection @code{Forbidden_Pragmas}
19963 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
19964
19965 @noindent
19966 Flag each use of the specified pragmas.  The pragmas to be detected
19967 are named in the rule's  parameters.
19968
19969 This rule has the following parameters:
19970
19971 @itemize @bullet
19972 @item For the @option{+R} option
19973
19974 @table @asis
19975 @item @emph{Pragma_Name}
19976 Adds the specified pragma to the set of pragmas to be
19977 checked and sets the checks for all the specified pragmas
19978 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
19979 does not correspond to any pragma name defined in the Ada
19980 standard or to the name of a GNAT-specific pragma defined
19981 in the GNAT Reference Manual, it is treated as the name of
19982 unknown pragma.
19983
19984 @item @code{GNAT}
19985 All the GNAT-specific pragmas are detected; this sets
19986 the checks for all the specified pragmas ON.
19987
19988 @item @code{ALL}
19989 All pragmas are detected; this sets the rule ON.
19990 @end table
19991
19992 @item For the @option{-R} option
19993 @table @asis
19994 @item @emph{Pragma_Name}
19995 Removes the specified pragma from the set of pragmas to be
19996 checked without affecting checks for
19997 other pragmas. @emph{Pragma_Name} is treated as a name
19998 of a pragma. If it does not correspond to any pragma
19999 defined in the Ada standard or to any name defined in the
20000 GNAT Reference Manual,
20001 this option is treated as turning OFF detection of all
20002 unknown pragmas.
20003
20004 @item GNAT
20005 Turn OFF detection of all GNAT-specific pragmas
20006
20007 @item ALL
20008 Clear the list of the pragmas to be detected and
20009 turn the rule OFF.
20010 @end table
20011 @end itemize
20012
20013 @noindent
20014 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
20015 the syntax of an Ada identifier and therefore can not be considered
20016 as a pragma name, a diagnostic message is generated and the corresponding
20017 parameter is ignored.
20018
20019 When more then one parameter is given in the same rule option, the parameters
20020 must be separated by a comma.
20021
20022 If more then one option for this rule is specified for the @command{gnatcheck}
20023 call, a new option overrides the previous one(s).
20024
20025 The @option{+R} option with no parameters turns the rule ON with the set of
20026 pragmas to be detected defined by the previous rule options.
20027 (By default this set is empty, so if the only option specified for the rule is
20028 @option{+RForbidden_Pragmas} (with
20029 no parameter), then the rule is enabled, but it does not detect anything).
20030 The @option{-R} option with no parameter turns the rule OFF, but it does not
20031 affect the set of pragmas to be detected.
20032
20033
20034
20035
20036 @node Function_Style_Procedures
20037 @subsection @code{Function_Style_Procedures}
20038 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
20039
20040 @noindent
20041 Flag each procedure that can be rewritten as a function. A procedure can be
20042 converted into a function if it has exactly one parameter of mode @code{out}
20043 and no parameters of mode @code{in out}. Procedure declarations,
20044 formal procedure declarations. and generic procedure declarations are always
20045 checked. Procedure
20046 bodies and body stubs are flagged only if they do not have corresponding
20047 separate declarations. Procedure renamings and procedure instantiations are
20048 not flagged.
20049
20050 If a procedure can be rewritten as a fucntion, but its @code{out} parameter is
20051 of a limited type, it is not flagged.
20052
20053 Protected procedures are not flagged. Null procedures also are not flagged.
20054
20055 This rule has no parameters.
20056
20057
20058 @node Generics_In_Subprograms
20059 @subsection @code{Generics_In_Subprograms}
20060 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
20061
20062 @noindent
20063 Flag each declaration of a generic unit in a supbrogram. Generic
20064 declarations in the bodies of generic subprograms are also flagged.
20065 A generic unit nested in another generic unit is not flagged.
20066 If a generic unit is
20067 declared in a local package that is declared in a subprogram body, the
20068 generic unit is flagged.
20069
20070 This rule has no parameters.
20071
20072
20073 @node GOTO_Statements
20074 @subsection @code{GOTO_Statements}
20075 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
20076
20077 @noindent
20078 Flag each occurrence of a @code{goto} statement.
20079
20080 This rule has no parameters.
20081
20082
20083 @node Implicit_IN_Mode_Parameters
20084 @subsection @code{Implicit_IN_Mode_Parameters}
20085 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
20086
20087 @noindent
20088 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
20089 Note that @code{access} parameters, although they technically behave
20090 like @code{in} parameters, are not flagged.
20091
20092 This rule has no parameters.
20093
20094
20095 @node Implicit_SMALL_For_Fixed_Point_Types
20096 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
20097 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
20098
20099 @noindent
20100 Flag each fixed point type declaration that lacks an explicit
20101 representation  clause to define its @code{'Small} value.
20102 Since @code{'Small} can be  defined only for ordinary fixed point types,
20103 decimal fixed point type declarations are not checked.
20104
20105 This rule has no parameters.
20106
20107
20108 @node Improperly_Located_Instantiations
20109 @subsection @code{Improperly_Located_Instantiations}
20110 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
20111
20112 @noindent
20113 Flag all generic instantiations in library-level package specifications
20114 (including library generic packages) and in all subprogram bodies.
20115
20116 Instantiations in task and entry bodies are not flagged. Instantiations in the
20117 bodies of protected subprograms are flagged.
20118
20119 This rule has no parameters.
20120
20121
20122
20123 @node Improper_Returns
20124 @subsection @code{Improper_Returns}
20125 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
20126
20127 @noindent
20128 Flag each explicit @code{return} statement in procedures, and
20129 multiple @code{return} statements in functions.
20130 Diagnostic messages are generated for all @code{return} statements
20131 in a procedure (thus each procedure must be written so that it
20132 returns implicitly at the end of its statement part),
20133 and for all @code{return} statements in a function after the first one.
20134 This rule supports the stylistic convention that each subprogram
20135 should have no more than one point of normal return.
20136
20137 This rule has no parameters.
20138
20139
20140 @node Library_Level_Subprograms
20141 @subsection @code{Library_Level_Subprograms}
20142 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
20143
20144 @noindent
20145 Flag all library-level subprograms (including generic subprogram instantiations).
20146
20147 This rule has no parameters.
20148
20149
20150 @node Local_Packages
20151 @subsection @code{Local_Packages}
20152 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
20153
20154 @noindent
20155 Flag all local packages declared in package and generic package
20156 specifications.
20157 Local packages in bodies are not flagged.
20158
20159 This rule has no parameters.
20160
20161 @ignore
20162 @node Improperly_Called_Protected_Entries
20163 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
20164 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
20165
20166 @noindent
20167 Flag each protected entry that can be called from more than one task.
20168
20169 This rule has no parameters.
20170 @end ignore
20171
20172
20173 @node Misnamed_Identifiers
20174 @subsection @code{Misnamed_Identifiers}
20175 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
20176
20177 @noindent
20178 Flag the declaration of each identifier that does not have a suffix
20179 corresponding to the kind of entity being declared.
20180 The following declarations are checked:
20181
20182 @itemize @bullet
20183 @item
20184  type declarations
20185
20186 @item
20187  constant declarations (but not number declarations)
20188
20189 @item
20190  package renaming declarations (but not generic package renaming
20191     declarations)
20192 @end itemize
20193
20194 @noindent
20195 This rule may have parameters. When used without parameters, the rule enforces
20196 the following checks:
20197
20198 @itemize @bullet
20199 @item
20200    type-defining names end with @code{_T}, unless the type is an access type,
20201     in which case the suffix must be @code{_A}
20202 @item
20203    constant names end with @code{_C}
20204 @item
20205    names defining package renamings end with @code{_R}
20206 @end itemize
20207
20208 @noindent
20209 For a private or incomplete type declaration the following checks are
20210 made for the defining name suffix:
20211
20212 @itemize @bullet
20213 @item
20214  For an incomplete type declaration: if the corresponding full type
20215   declaration is available, the defining identifier from the full type
20216   declaration is checked, but the defining identifier from the incomplete type
20217   declaration is not; otherwise the defining identifier from the incomplete
20218   type declaration is checked against the suffix specified for type
20219   declarations.
20220
20221 @item
20222  For a private type declaration (including private extensions),  the defining
20223   identifier from the private type declaration is checked against the type
20224   suffix (even if the corresponding full declaration is an access type
20225   declaration), and the defining identifier from the corresponding full type
20226   declaration is not checked.
20227 @end itemize
20228
20229 @noindent
20230 For a deferred constant, the defining name in the corresponding full constant
20231 declaration is not checked.
20232
20233 Defining names of formal types are not checked.
20234
20235 The rule may have the following parameters:
20236
20237 @itemize @bullet
20238 @item
20239 For the @option{+R} option:
20240 @table @code
20241 @item Default
20242 Sets the default listed above for all the names to be checked.
20243
20244 @item Type_Suffix=@emph{string}
20245 Specifies the suffix for a type name.
20246
20247 @item Access_Suffix=@emph{string}
20248 Specifies the suffix for an access type name. If
20249 this parameter is set, it overrides for access
20250 types the suffix set by the @code{Type_Suffix} parameter.
20251
20252 @item Constant_Suffix=@emph{string}
20253 Specifies the suffix for a constant name.
20254
20255 @item Renaming_Suffix=@emph{string}
20256 Specifies the suffix for a package renaming name.
20257 @end table
20258
20259 @item
20260 For the @option{-R} option:
20261 @table @code
20262 @item All_Suffixes
20263 Remove all the suffixes specified for the
20264 identifier suffix checks, whether by default or
20265 as specified by other rule parameters. All the
20266 checks for this rule are disabled as a result.
20267
20268 @item Type_Suffix
20269 Removes the suffix specified for types. This
20270 disables checks for types but does not disable
20271 any other checks for this rule (including the
20272 check for access type names if @code{Access_Suffix} is
20273 set).
20274
20275 @item Access_Suffix
20276 Removes the suffix specified for access types.
20277 This disables checks for access type names but
20278 does not disable any other checks for this rule.
20279 If @code{Type_Suffix} is set, access type names are
20280 checked as ordinary type names.
20281
20282 @item Constant_Suffix
20283 Removes the suffix specified for constants. This
20284 disables checks for constant names but does not
20285 disable any other checks for this rule.
20286
20287 @item Renaming_Suffix
20288 Removes the suffix specified for package
20289 renamings. This disables checks for package
20290 renamings but does not disable any other checks
20291 for this rule.
20292 @end table
20293 @end itemize
20294
20295 @noindent
20296 If more than one parameter is used, parameters must be separated by commas.
20297
20298 If more than one  option is specified for the @command{gnatcheck} invocation,
20299 a new option overrides the previous one(s).
20300
20301 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
20302 checks for all the
20303 name suffixes specified by previous options used for this rule.
20304
20305 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
20306 all the checks but keeps
20307 all the suffixes specified by previous options used for this rule.
20308
20309 The @emph{string} value must be a valid suffix for an Ada identifier (after
20310 trimming all the leading and trailing space characters, if any).
20311 Parameters are not case sensitive, except the @emph{string} part.
20312
20313 If any error is detected in a rule parameter, the parameter is ignored.
20314 In such a case the options that are set for the rule are not
20315 specified.
20316
20317
20318
20319 @node Multiple_Entries_In_Protected_Definitions
20320 @subsection @code{Multiple_Entries_In_Protected_Definitions}
20321 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
20322
20323 @noindent
20324 Flag each protected definition (i.e., each protected object/type declaration)
20325 that defines more than one entry.
20326 Diagnostic messages are generated for all the entry declarations
20327 except the first one. An entry family is counted as one entry. Entries from
20328 the private part of the protected definition are also checked.
20329
20330 This rule has no parameters.
20331
20332 @node Name_Clashes
20333 @subsection @code{Name_Clashes}
20334 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
20335
20336 @noindent
20337 Check that certain names are not used as defining identifiers. To activate
20338 this rule, you need to supply a reference to the dictionary file(s) as a rule
20339 parameter(s) (more then one dictionary file can be specified). If no
20340 dictionary file is set, this rule will not cause anything to be flagged.
20341 Only defining occurrences, not references, are checked.
20342 The check is not case-sensitive.
20343
20344 This rule is enabled by default, but without setting any corresponding
20345 dictionary file(s); thus the default effect is to do no checks.
20346
20347 A dictionary file is a plain text file. The maximum line length for this file
20348 is 1024 characters.  If the line is longer then this limit, extra characters
20349 are ignored.
20350
20351 Each line can be either an empty line, a comment line, or a line containing
20352 a list of identifiers separated by space or HT characters.
20353 A comment is an Ada-style comment (from @code{--} to end-of-line).
20354 Identifiers must follow the Ada syntax for identifiers.
20355 A line containing one or more identifiers may end with a comment.
20356
20357 @node Non_Qualified_Aggregates
20358 @subsection @code{Non_Qualified_Aggregates}
20359 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
20360
20361 @noindent
20362 Flag each non-qualified aggregate.
20363 A non-qualified aggregate is an
20364 aggregate that is not the expression of a qualified expression. A
20365 string literal is not considered an aggregate, but an array
20366 aggregate of a string type is considered as a normal aggregate.
20367
20368 This rule has no parameters.
20369
20370
20371 @node Non_Short_Circuit_Operators
20372 @subsection @code{Non_Short_Circuit_Operators}
20373 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
20374
20375 @noindent
20376 Flag all calls to predefined @code{and} and @code{or} operators for
20377 any boolean type. Calls to
20378 user-defined @code{and} and @code{or} and to operators defined by renaming
20379 declarations are not flagged. Calls to predefined @code{and} and @code{or}
20380 operators for modular types or boolean array types are not flagged.
20381
20382 This rule has no parameters.
20383
20384
20385
20386 @node Non_SPARK_Attributes
20387 @subsection @code{Non_SPARK_Attributes}
20388 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
20389
20390 @noindent
20391 The SPARK language defines the following subset of Ada 95 attribute
20392 designators as those that can be used in SPARK programs. The use of
20393 any other attribute is flagged.
20394
20395 @itemize @bullet
20396 @item @code{'Adjacent}
20397 @item @code{'Aft}
20398 @item @code{'Base}
20399 @item @code{'Ceiling}
20400 @item @code{'Component_Size}
20401 @item @code{'Compose}
20402 @item @code{'Copy_Sign}
20403 @item @code{'Delta}
20404 @item @code{'Denorm}
20405 @item @code{'Digits}
20406 @item @code{'Exponent}
20407 @item @code{'First}
20408 @item @code{'Floor}
20409 @item @code{'Fore}
20410 @item @code{'Fraction}
20411 @item @code{'Last}
20412 @item @code{'Leading_Part}
20413 @item @code{'Length}
20414 @item @code{'Machine}
20415 @item @code{'Machine_Emax}
20416 @item @code{'Machine_Emin}
20417 @item @code{'Machine_Mantissa}
20418 @item @code{'Machine_Overflows}
20419 @item @code{'Machine_Radix}
20420 @item @code{'Machine_Rounds}
20421 @item @code{'Max}
20422 @item @code{'Min}
20423 @item @code{'Model}
20424 @item @code{'Model_Emin}
20425 @item @code{'Model_Epsilon}
20426 @item @code{'Model_Mantissa}
20427 @item @code{'Model_Small}
20428 @item @code{'Modulus}
20429 @item @code{'Pos}
20430 @item @code{'Pred}
20431 @item @code{'Range}
20432 @item @code{'Remainder}
20433 @item @code{'Rounding}
20434 @item @code{'Safe_First}
20435 @item @code{'Safe_Last}
20436 @item @code{'Scaling}
20437 @item @code{'Signed_Zeros}
20438 @item @code{'Size}
20439 @item @code{'Small}
20440 @item @code{'Succ}
20441 @item @code{'Truncation}
20442 @item @code{'Unbiased_Rounding}
20443 @item @code{'Val}
20444 @item @code{'Valid}
20445 @end itemize
20446
20447 @noindent
20448 This rule has no parameters.
20449
20450
20451 @node Non_Tagged_Derived_Types
20452 @subsection @code{Non_Tagged_Derived_Types}
20453 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
20454
20455 @noindent
20456 Flag all derived type declarations that do not have a record extension part.
20457
20458 This rule has no parameters.
20459
20460
20461
20462 @node Non_Visible_Exceptions
20463 @subsection @code{Non_Visible_Exceptions}
20464 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
20465
20466 @noindent
20467 Flag constructs leading to the possibility of propagating an exception
20468 out of the scope in which the exception is declared.
20469 Two cases are detected:
20470
20471 @itemize @bullet
20472 @item
20473 An exception declaration in a subprogram body, task body or block
20474 statement is flagged if the body or statement does not contain a handler for
20475 that exception or a handler with an @code{others} choice.
20476
20477 @item
20478 A @code{raise} statement in an exception handler of a subprogram body,
20479 task body or block statement is flagged if it (re)raises a locally
20480 declared exception.  This may occur under the following circumstances:
20481 @itemize @minus
20482 @item
20483 it explicitly raises a locally declared exception, or
20484 @item
20485 it does not specify an exception name (i.e., it is simply @code{raise;})
20486 and the enclosing handler contains a locally declared exception in its
20487 exception choices.
20488 @end itemize
20489 @end itemize
20490
20491 @noindent
20492 Renamings of local exceptions are not flagged.
20493
20494 This rule has no parameters.
20495
20496
20497 @node Numeric_Literals
20498 @subsection @code{Numeric_Literals}
20499 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
20500
20501 @noindent
20502 Flag each use of a numeric literal in an index expression, and in any
20503 circumstance except for the following:
20504
20505 @itemize @bullet
20506 @item
20507 a literal occurring in the initialization expression for a constant
20508 declaration or a named number declaration, or
20509
20510 @item
20511 an integer literal that is less than or equal to a value
20512 specified by the @option{N} rule parameter.
20513 @end itemize
20514
20515 @noindent
20516 This rule may have the following parameters for the @option{+R} option:
20517
20518 @table @asis
20519 @item @emph{N}
20520 @emph{N} is an integer literal used as the maximal value that is not flagged
20521 (i.e., integer literals not exceeding this value are allowed)
20522
20523 @item @code{ALL}
20524 All integer literals are flagged
20525 @end table
20526
20527 @noindent
20528 If no parameters are set, the maximum unflagged value is 1.
20529
20530 The last specified check limit (or the fact that there is no limit at
20531 all) is used when multiple @option{+R} options appear.
20532
20533 The @option{-R} option for this rule has no parameters.
20534 It disables the rule but retains the last specified maximum unflagged value.
20535 If the @option{+R} option subsequently appears, this value is used as the
20536 threshold for the check.
20537
20538
20539 @node OTHERS_In_Aggregates
20540 @subsection @code{OTHERS_In_Aggregates}
20541 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
20542
20543 @noindent
20544 Flag each use of an @code{others} choice in extension aggregates.
20545 In record and array aggregates, an @code{others} choice is flagged unless
20546 it is used to refer to all components, or to all but one component.
20547
20548 If, in case of a named array aggregate, there are two associations, one
20549 with an @code{others} choice and another with a discrete range, the
20550 @code{others} choice is flagged even if the discrete range specifies
20551 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
20552
20553 This rule has no parameters.
20554
20555 @node OTHERS_In_CASE_Statements
20556 @subsection @code{OTHERS_In_CASE_Statements}
20557 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
20558
20559 @noindent
20560 Flag any use of an @code{others} choice in a @code{case} statement.
20561
20562 This rule has no parameters.
20563
20564 @node OTHERS_In_Exception_Handlers
20565 @subsection @code{OTHERS_In_Exception_Handlers}
20566 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
20567
20568 @noindent
20569 Flag any use of an @code{others} choice in an exception handler.
20570
20571 This rule has no parameters.
20572
20573
20574 @node Outer_Loop_Exits
20575 @subsection @code{Outer_Loop_Exits}
20576 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
20577
20578 @noindent
20579 Flag each @code{exit} statement containing a loop name that is not the name
20580 of the immediately enclosing @code{loop} statement.
20581
20582 This rule has no parameters.
20583
20584
20585 @node Overloaded_Operators
20586 @subsection @code{Overloaded_Operators}
20587 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
20588
20589 @noindent
20590 Flag each function declaration that overloads an operator symbol.
20591 A function body is checked only if the body does not have a
20592 separate spec. Formal functions are also checked. For a
20593 renaming declaration, only renaming-as-declaration is checked
20594
20595 This rule has no parameters.
20596
20597
20598 @node Overly_Nested_Control_Structures
20599 @subsection @code{Overly_Nested_Control_Structures}
20600 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
20601
20602 @noindent
20603 Flag each control structure whose nesting level exceeds the value provided
20604 in the rule parameter.
20605
20606 The control structures checked are the following:
20607
20608 @itemize @bullet
20609 @item    @code{if} statement
20610 @item    @code{case} statement
20611 @item    @code{loop} statement
20612 @item    Selective accept statement
20613 @item    Timed entry call statement
20614 @item    Conditional entry call
20615 @item    Asynchronous select statement
20616 @end itemize
20617
20618 @noindent
20619 The rule may have the following parameter for the @option{+R} option:
20620
20621 @table @emph
20622 @item N
20623 Positive integer specifying the maximal control structure nesting
20624 level that is not flagged
20625 @end table
20626
20627 @noindent
20628 If the parameter for the @option{+R} option is not a positive integer,
20629 the parameter is ignored and the rule is turned ON with the most recently
20630 specified maximal non-flagged nesting level.
20631
20632 If more then one  option is specified for the gnatcheck call, the later option and
20633 new parameter override the previous one(s).
20634
20635 A @option{+R} option with no parameter turns the rule ON using the maximal
20636 non-flagged nesting level specified by the most recent @option{+R} option with
20637 a parameter, or the value 4 if there is no such previous @option{+R} option.
20638
20639
20640
20641 @node Parameters_Out_Of_Order
20642 @subsection @code{Parameters_Out_Of_Order}
20643 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
20644
20645 @noindent
20646 Flag each subprogram and entry declaration whose formal parameters are not
20647 ordered according to the following scheme:
20648
20649 @itemize @bullet
20650
20651 @item @code{in} and @code{access} parameters first,
20652 then @code{in out} parameters,
20653 and then @code{out} parameters;
20654
20655 @item for @code{in} mode, parameters with default initialization expressions
20656 occur last
20657 @end itemize
20658
20659 @noindent
20660 Only the first violation of the described order is flagged.
20661
20662 The following constructs are checked:
20663
20664 @itemize @bullet
20665 @item   subprogram declarations (including null procedures);
20666 @item   generic subprogram declarations;
20667 @item   formal subprogram declarations;
20668 @item   entry declarations;
20669 @item   subprogram bodies and subprogram body stubs that do not
20670 have separate specifications
20671 @end itemize
20672
20673 @noindent
20674 Subprogram renamings are not checked.
20675
20676 This rule has no parameters.
20677
20678
20679 @node Positional_Actuals_For_Defaulted_Generic_Parameters
20680 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
20681 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
20682
20683 @noindent
20684 Flag each generic actual parameter corresponding to a generic formal
20685 parameter with a default initialization, if positional notation is used.
20686
20687 This rule has no parameters.
20688
20689 @node Positional_Actuals_For_Defaulted_Parameters
20690 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
20691 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
20692
20693 @noindent
20694 Flag each actual parameter to a subprogram or entry call where the
20695 corresponding formal parameter has a default expression, if positional
20696 notation is used.
20697
20698 This rule has no parameters.
20699
20700 @node Positional_Components
20701 @subsection @code{Positional_Components}
20702 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
20703
20704 @noindent
20705 Flag each array, record and extension aggregate that includes positional
20706 notation.
20707
20708 This rule has no parameters.
20709
20710
20711 @node Positional_Generic_Parameters
20712 @subsection @code{Positional_Generic_Parameters}
20713 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
20714
20715 @noindent
20716 Flag each instantiation using positional parameter notation.
20717
20718 This rule has no parameters.
20719
20720
20721 @node Positional_Parameters
20722 @subsection @code{Positional_Parameters}
20723 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
20724
20725 @noindent
20726 Flag each subprogram or entry call using positional parameter notation,
20727 except for the following:
20728
20729 @itemize @bullet
20730 @item
20731 Invocations of prefix or infix operators are not flagged
20732 @item
20733 If the called subprogram or entry has only one formal parameter,
20734 the call is not flagged;
20735 @item
20736 If a subprogram call uses the @emph{Object.Operation} notation, then
20737 @itemize @minus
20738 @item
20739 the first parameter (that is, @emph{Object}) is not flagged;
20740 @item
20741 if the called subprogram has only two parameters, the second parameter
20742 of the call is not flagged;
20743 @end itemize
20744 @end itemize
20745
20746 @noindent
20747 This rule has no parameters.
20748
20749
20750
20751
20752 @node Predefined_Numeric_Types
20753 @subsection @code{Predefined_Numeric_Types}
20754 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
20755
20756 @noindent
20757 Flag each explicit use of the name of any numeric type or subtype defined
20758 in package @code{Standard}.
20759
20760 The rationale for this rule is to detect when the
20761 program may depend on platform-specific characteristics of the implementation
20762 of the predefined numeric types. Note that this rule is over-pessimistic;
20763 for example, a program that uses @code{String} indexing
20764 likely needs a variable of type @code{Integer}.
20765 Another example is the flagging of predefined numeric types with explicit
20766 constraints:
20767
20768 @smallexample @c ada
20769     subtype My_Integer is Integer range Left .. Right;
20770     Vy_Var : My_Integer;
20771 @end smallexample
20772
20773 @noindent
20774 This rule detects only numeric types and subtypes defined in
20775 @code{Standard}. The use of numeric types and subtypes defined in other
20776 predefined packages (such as @code{System.Any_Priority} or
20777 @code{Ada.Text_IO.Count}) is not flagged
20778
20779 This rule has no parameters.
20780
20781
20782
20783 @node Raising_External_Exceptions
20784 @subsection @code{Raising_External_Exceptions}
20785 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
20786
20787 @noindent
20788 Flag any @code{raise} statement, in a program unit declared in a library
20789 package or in a generic library package, for an exception that is
20790 neither a predefined exception nor an exception that is also declared (or
20791 renamed) in the visible part of the package.
20792
20793 This rule has no parameters.
20794
20795
20796
20797 @node Raising_Predefined_Exceptions
20798 @subsection @code{Raising_Predefined_Exceptions}
20799 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
20800
20801 @noindent
20802 Flag each @code{raise} statement that raises a predefined exception
20803 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
20804 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
20805
20806 This rule has no parameters.
20807
20808
20809 @ignore
20810 @node Recursion
20811 @subsection @code{Recursion} (under construction, GLOBAL)
20812 @cindex @code{Recursion} rule (for @command{gnatcheck})
20813
20814 @noindent
20815 Flag recursive subprograms (cycles in the call graph). Declarations, and not
20816 calls, of recursive subprograms are detected.
20817
20818 This rule has no parameters.
20819 @end ignore
20820
20821 @ignore
20822 @node Side_Effect_Functions
20823 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
20824 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
20825
20826 @noindent
20827 Flag functions with side effects.
20828
20829 We define a side effect as changing any data object that is not local for the
20830 body of this function.
20831
20832 At the moment, we do NOT consider a side effect any input-output operations
20833 (changing a state or a content of any file).
20834
20835 We do not consider protected functions for this rule (???)
20836
20837 There are the following sources of side effect:
20838
20839 @enumerate
20840 @item Explicit (or direct) side-effect:
20841
20842 @itemize @bullet
20843 @item
20844 direct assignment to a non-local variable;
20845
20846 @item
20847 direct call to an entity that is known to change some data object that is
20848      not local for the body of this function (Note, that if F1 calls F2 and F2
20849      does have a side effect, this does not automatically mean that F1 also
20850      have a side effect, because it may be the case that F2 is declared in
20851      F1's body and it changes some data object that is global for F2, but
20852      local for F1);
20853 @end itemize
20854
20855 @item Indirect side-effect:
20856 @itemize @bullet
20857 @item
20858 Subprogram calls implicitly issued by:
20859 @itemize @bullet
20860 @item
20861 computing initialization expressions from type declarations as a part
20862          of object elaboration or allocator evaluation;
20863 @item
20864 computing implicit parameters of subprogram or entry calls or generic
20865          instantiations;
20866 @end itemize
20867
20868 @item
20869 activation of a task that change some non-local data object (directly or
20870      indirectly);
20871
20872 @item
20873 elaboration code of a package that is a result of a package instantiation;
20874
20875 @item
20876 controlled objects;
20877 @end itemize
20878
20879 @item Situations when we can suspect a side-effect, but the full static check
20880 is either impossible or too hard:
20881 @itemize @bullet
20882 @item
20883 assignment to access variables or to the objects pointed by access
20884      variables;
20885
20886 @item
20887 call to a subprogram pointed by access-to-subprogram value
20888
20889 @item
20890 dispatching calls;
20891 @end itemize
20892 @end enumerate
20893
20894 @noindent
20895 This rule has no parameters.
20896 @end ignore
20897
20898 @node Slices
20899 @subsection @code{Slices}
20900 @cindex @code{Slices} rule (for @command{gnatcheck})
20901
20902 @noindent
20903 Flag all uses of array slicing
20904
20905 This rule has no parameters.
20906
20907
20908 @node Unassigned_OUT_Parameters
20909 @subsection @code{Unassigned_OUT_Parameters}
20910 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
20911
20912 @noindent
20913 Flags procedures' @code{out} parameters that are not assigned, and
20914 identifies the contexts in which the assignments are missing.
20915
20916 An @code{out} parameter is flagged in the statements in the procedure
20917 body's handled sequence of statements (before the procedure body's
20918 @code{exception} part, if any) if this sequence of statements contains
20919 no assignments to the parameter.
20920
20921 An @code{out} parameter is flagged in an exception handler in the exception
20922 part of the procedure body's handled sequence of statements if the handler
20923 contains no assignment to the parameter.
20924
20925 Bodies of generic procedures are also considered.
20926
20927 The following are treated as assignments to an @code{out} parameter:
20928
20929 @itemize @bullet
20930 @item
20931 an assignment statement, with the parameter or some component as the target;
20932
20933 @item
20934 passing the parameter (or one of its components) as an @code{out} or
20935 @code{in out} parameter.
20936 @end itemize
20937
20938 @noindent
20939 This rule does not have any parameters.
20940
20941
20942
20943 @node Uncommented_BEGIN_In_Package_Bodies
20944 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
20945 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
20946
20947 @noindent
20948 Flags each package body with declarations and a statement part that does not
20949 include a trailing comment on the line containing the @code{begin} keyword;
20950 this trailing comment needs to specify the package name and nothing else.
20951 The @code{begin} is not flagged if the package body does not
20952 contain any declarations.
20953
20954 If the @code{begin} keyword is placed on the
20955 same line as the last declaration or the first statement, it is flagged
20956 independently of whether the line contains a trailing comment. The
20957 diagnostic message is attached to the line containing the first statement.
20958
20959 This rule has no parameters.
20960
20961
20962 @node Unconstrained_Array_Returns
20963 @subsection @code{Unconstrained_Array_Returns}
20964 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
20965
20966 @noindent
20967 Flag each function returning an unconstrained array. Function declarations,
20968 function bodies (and body stubs) having no separate specifications,
20969 and generic function instantiations are checked.
20970 Generic function declarations, function calls and function renamings are
20971 not checked.
20972
20973 This rule has no parameters.
20974
20975 @node Universal_Ranges
20976 @subsection @code{Universal_Ranges}
20977 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
20978
20979 @noindent
20980 Flag discrete ranges that are a part of an index constraint, constrained
20981 array definition, or @code{for}-loop parameter specification, and whose bounds
20982 are both of type @i{universal_integer}. Ranges that have at least one
20983 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
20984 or an expression of non-universal type) are not flagged.
20985
20986 This rule has no parameters.
20987
20988
20989 @node Unnamed_Blocks_And_Loops
20990 @subsection @code{Unnamed_Blocks_And_Loops}
20991 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
20992
20993 @noindent
20994 Flag each unnamed block statement and loop statement.
20995
20996 The rule has no parameters.
20997
20998
20999
21000 @ignore
21001 @node Unused_Subprograms
21002 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
21003 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
21004
21005 @noindent
21006 Flag all unused subprograms.
21007
21008 This rule has no parameters.
21009 @end ignore
21010
21011
21012
21013
21014 @node USE_PACKAGE_Clauses
21015 @subsection @code{USE_PACKAGE_Clauses}
21016 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
21017
21018 @noindent
21019 Flag all @code{use} clauses for packages; @code{use type} clauses are
21020 not flagged.
21021
21022 This rule has no parameters.
21023
21024
21025
21026 @node Volatile_Objects_Without_Address_Clauses
21027 @subsection @code{Volatile_Objects_Without_Address_Clauses}
21028 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
21029
21030 @noindent
21031 Flag each volatile object that does not have an address clause.
21032
21033 The following check is made: if the pragma @code{Volatile} is applied to a
21034 data object or to its type, then an address clause must
21035 be supplied for this object.
21036
21037 This rule does not check the components of data objects,
21038 array components that are volatile as a result of the pragma
21039 @code{Volatile_Components}, or objects that are volatile because
21040 they are atomic as a result of pragmas @code{Atomic} or
21041 @code{Atomic_Components}.
21042
21043 Only variable declarations, and not constant declarations, are checked.
21044
21045 This rule has no parameters.
21046
21047
21048 @c *********************************
21049 @node Creating Sample Bodies Using gnatstub
21050 @chapter Creating Sample Bodies Using @command{gnatstub}
21051 @findex gnatstub
21052
21053 @noindent
21054 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
21055 for library unit declarations.
21056
21057 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
21058 driver (see @ref{The GNAT Driver and Project Files}).
21059
21060 To create a body stub, @command{gnatstub} has to compile the library
21061 unit declaration. Therefore, bodies can be created only for legal
21062 library units. Moreover, if a library unit depends semantically upon
21063 units located outside the current directory, you have to provide
21064 the source search path when calling @command{gnatstub}, see the description
21065 of @command{gnatstub} switches below.
21066
21067 @menu
21068 * Running gnatstub::
21069 * Switches for gnatstub::
21070 @end menu
21071
21072 @node Running gnatstub
21073 @section Running @command{gnatstub}
21074
21075 @noindent
21076 @command{gnatstub} has the command-line interface of the form
21077
21078 @smallexample
21079 $ gnatstub [switches] filename [directory]
21080 @end smallexample
21081
21082 @noindent
21083 where
21084 @table @emph
21085 @item filename
21086 is the name of the source file that contains a library unit declaration
21087 for which a body must be created. The file name may contain the path
21088 information.
21089 The file name does not have to follow the GNAT file name conventions. If the
21090 name
21091 does not follow GNAT file naming conventions, the name of the body file must
21092 be provided
21093 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
21094 If the file name follows the GNAT file naming
21095 conventions and the name of the body file is not provided,
21096 @command{gnatstub}
21097 creates the name
21098 of the body file from the argument file name by replacing the @file{.ads}
21099 suffix
21100 with the @file{.adb} suffix.
21101
21102 @item directory
21103 indicates the directory in which the body stub is to be placed (the default
21104 is the
21105 current directory)
21106
21107 @item switches
21108 is an optional sequence of switches as described in the next section
21109 @end table
21110
21111 @node Switches for gnatstub
21112 @section Switches for @command{gnatstub}
21113
21114 @table @option
21115 @c !sort!
21116
21117 @item ^-f^/FULL^
21118 @cindex @option{^-f^/FULL^} (@command{gnatstub})
21119 If the destination directory already contains a file with the name of the
21120 body file
21121 for the argument spec file, replace it with the generated body stub.
21122
21123 @item ^-hs^/HEADER=SPEC^
21124 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
21125 Put the comment header (i.e., all the comments preceding the
21126 compilation unit) from the source of the library unit declaration
21127 into the body stub.
21128
21129 @item ^-hg^/HEADER=GENERAL^
21130 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
21131 Put a sample comment header into the body stub.
21132
21133 @ifclear vms
21134 @item -IDIR
21135 @cindex @option{-IDIR} (@command{gnatstub})
21136 @itemx -I-
21137 @cindex @option{-I-} (@command{gnatstub})
21138 @end ifclear
21139 @ifset vms
21140 @item /NOCURRENT_DIRECTORY
21141 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
21142 @end ifset
21143 ^These switches have ^This switch has^ the same meaning as in calls to
21144 @command{gcc}.
21145 ^They define ^It defines ^ the source search path in the call to
21146 @command{gcc} issued
21147 by @command{gnatstub} to compile an argument source file.
21148
21149 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
21150 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
21151 This switch has the same meaning as in calls to @command{gcc}.
21152 It defines the additional configuration file to be passed to the call to
21153 @command{gcc} issued
21154 by @command{gnatstub} to compile an argument source file.
21155
21156 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
21157 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
21158 (@var{n} is a non-negative integer). Set the maximum line length in the
21159 body stub to @var{n}; the default is 79. The maximum value that can be
21160 specified is 32767. Note that in the special case of configuration
21161 pragma files, the maximum is always 32767 regardless of whether or
21162 not this switch appears.
21163
21164 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
21165 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
21166 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
21167 the generated body sample to @var{n}.
21168 The default indentation is 3.
21169
21170 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
21171 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
21172 Order local bodies alphabetically. (By default local bodies are ordered
21173 in the same way as the corresponding local specs in the argument spec file.)
21174
21175 @item ^-i^/INDENTATION=^@var{n}
21176 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
21177 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
21178
21179 @item ^-k^/TREE_FILE=SAVE^
21180 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
21181 Do not remove the tree file (i.e., the snapshot of the compiler internal
21182 structures used by @command{gnatstub}) after creating the body stub.
21183
21184 @item ^-l^/LINE_LENGTH=^@var{n}
21185 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
21186 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
21187
21188 @item ^-o^/BODY=^@var{body-name}
21189 @cindex @option{^-o^/BODY^} (@command{gnatstub})
21190 Body file name.  This should be set if the argument file name does not
21191 follow
21192 the GNAT file naming
21193 conventions. If this switch is omitted the default name for the body will be
21194 obtained
21195 from the argument file name according to the GNAT file naming conventions.
21196
21197 @item ^-q^/QUIET^
21198 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
21199 Quiet mode: do not generate a confirmation when a body is
21200 successfully created, and do not generate a message when a body is not
21201 required for an
21202 argument unit.
21203
21204 @item ^-r^/TREE_FILE=REUSE^
21205 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
21206 Reuse the tree file (if it exists) instead of creating it.  Instead of
21207 creating the tree file for the library unit declaration, @command{gnatstub}
21208 tries to find it in the current directory and use it for creating
21209 a body. If the tree file is not found, no body is created. This option
21210 also implies @option{^-k^/SAVE^}, whether or not
21211 the latter is set explicitly.
21212
21213 @item ^-t^/TREE_FILE=OVERWRITE^
21214 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
21215 Overwrite the existing tree file.  If the current directory already
21216 contains the file which, according to the GNAT file naming rules should
21217 be considered as a tree file for the argument source file,
21218 @command{gnatstub}
21219 will refuse to create the tree file needed to create a sample body
21220 unless this option is set.
21221
21222 @item ^-v^/VERBOSE^
21223 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
21224 Verbose mode: generate version information.
21225
21226 @end table
21227
21228 @node Other Utility Programs
21229 @chapter Other Utility Programs
21230
21231 @noindent
21232 This chapter discusses some other utility programs available in the Ada
21233 environment.
21234
21235 @menu
21236 * Using Other Utility Programs with GNAT::
21237 * The External Symbol Naming Scheme of GNAT::
21238 * Converting Ada Files to html with gnathtml::
21239 * Installing gnathtml::
21240 @ifset vms
21241 * LSE::
21242 * Profiling::
21243 @end ifset
21244 @end menu
21245
21246 @node Using Other Utility Programs with GNAT
21247 @section Using Other Utility Programs with GNAT
21248
21249 @noindent
21250 The object files generated by GNAT are in standard system format and in
21251 particular the debugging information uses this format. This means
21252 programs generated by GNAT can be used with existing utilities that
21253 depend on these formats.
21254
21255 @ifclear vms
21256 In general, any utility program that works with C will also often work with
21257 Ada programs generated by GNAT. This includes software utilities such as
21258 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
21259 as Purify.
21260 @end ifclear
21261
21262 @node The External Symbol Naming Scheme of GNAT
21263 @section The External Symbol Naming Scheme of GNAT
21264
21265 @noindent
21266 In order to interpret the output from GNAT, when using tools that are
21267 originally intended for use with other languages, it is useful to
21268 understand the conventions used to generate link names from the Ada
21269 entity names.
21270
21271 All link names are in all lowercase letters. With the exception of library
21272 procedure names, the mechanism used is simply to use the full expanded
21273 Ada name with dots replaced by double underscores. For example, suppose
21274 we have the following package spec:
21275
21276 @smallexample @c ada
21277 @group
21278 @cartouche
21279 package QRS is
21280    MN : Integer;
21281 end QRS;
21282 @end cartouche
21283 @end group
21284 @end smallexample
21285
21286 @noindent
21287 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
21288 the corresponding link name is @code{qrs__mn}.
21289 @findex Export
21290 Of course if a @code{pragma Export} is used this may be overridden:
21291
21292 @smallexample @c ada
21293 @group
21294 @cartouche
21295 package Exports is
21296    Var1 : Integer;
21297    pragma Export (Var1, C, External_Name => "var1_name");
21298    Var2 : Integer;
21299    pragma Export (Var2, C, Link_Name => "var2_link_name");
21300 end Exports;
21301 @end cartouche
21302 @end group
21303 @end smallexample
21304
21305 @noindent
21306 In this case, the link name for @var{Var1} is whatever link name the
21307 C compiler would assign for the C function @var{var1_name}. This typically
21308 would be either @var{var1_name} or @var{_var1_name}, depending on operating
21309 system conventions, but other possibilities exist. The link name for
21310 @var{Var2} is @var{var2_link_name}, and this is not operating system
21311 dependent.
21312
21313 @findex _main
21314 One exception occurs for library level procedures. A potential ambiguity
21315 arises between the required name @code{_main} for the C main program,
21316 and the name we would otherwise assign to an Ada library level procedure
21317 called @code{Main} (which might well not be the main program).
21318
21319 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
21320 names. So if we have a library level procedure such as
21321
21322 @smallexample @c ada
21323 @group
21324 @cartouche
21325 procedure Hello (S : String);
21326 @end cartouche
21327 @end group
21328 @end smallexample
21329
21330 @noindent
21331 the external name of this procedure will be @var{_ada_hello}.
21332
21333
21334 @node Converting Ada Files to html with gnathtml
21335 @section Converting Ada Files to HTML with @code{gnathtml}
21336
21337 @noindent
21338 This @code{Perl} script allows Ada source files to be browsed using
21339 standard Web browsers. For installation procedure, see the section
21340 @xref{Installing gnathtml}.
21341
21342 Ada reserved keywords are highlighted in a bold font and Ada comments in
21343 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
21344 switch to suppress the generation of cross-referencing information, user
21345 defined variables and types will appear in a different color; you will
21346 be able to click on any identifier and go to its declaration.
21347
21348 The command line is as follow:
21349 @smallexample
21350 $ perl gnathtml.pl [^switches^options^] ada-files
21351 @end smallexample
21352
21353 @noindent
21354 You can pass it as many Ada files as you want. @code{gnathtml} will generate
21355 an html file for every ada file, and a global file called @file{index.htm}.
21356 This file is an index of every identifier defined in the files.
21357
21358 The available ^switches^options^ are the following ones :
21359
21360 @table @option
21361 @item -83
21362 @cindex @option{-83} (@code{gnathtml})
21363 Only the Ada 83 subset of keywords will be highlighted.
21364
21365 @item -cc @var{color}
21366 @cindex @option{-cc} (@code{gnathtml})
21367 This option allows you to change the color used for comments. The default
21368 value is green. The color argument can be any name accepted by html.
21369
21370 @item -d
21371 @cindex @option{-d} (@code{gnathtml})
21372 If the Ada files depend on some other files (for instance through
21373 @code{with} clauses, the latter files will also be converted to html.
21374 Only the files in the user project will be converted to html, not the files
21375 in the run-time library itself.
21376
21377 @item -D
21378 @cindex @option{-D} (@code{gnathtml})
21379 This command is the same as @option{-d} above, but @command{gnathtml} will
21380 also look for files in the run-time library, and generate html files for them.
21381
21382 @item -ext @var{extension}
21383 @cindex @option{-ext} (@code{gnathtml})
21384 This option allows you to change the extension of the generated HTML files.
21385 If you do not specify an extension, it will default to @file{htm}.
21386
21387 @item -f
21388 @cindex @option{-f} (@code{gnathtml})
21389 By default, gnathtml will generate html links only for global entities
21390 ('with'ed units, global variables and types,...). If you specify
21391 @option{-f} on the command line, then links will be generated for local
21392 entities too.
21393
21394 @item -l @var{number}
21395 @cindex @option{-l} (@code{gnathtml})
21396 If this ^switch^option^ is provided and @var{number} is not 0, then
21397 @code{gnathtml} will number the html files every @var{number} line.
21398
21399 @item -I @var{dir}
21400 @cindex @option{-I} (@code{gnathtml})
21401 Specify a directory to search for library files (@file{.ALI} files) and
21402 source files. You can provide several -I switches on the command line,
21403 and the directories will be parsed in the order of the command line.
21404
21405 @item -o @var{dir}
21406 @cindex @option{-o} (@code{gnathtml})
21407 Specify the output directory for html files. By default, gnathtml will
21408 saved the generated html files in a subdirectory named @file{html/}.
21409
21410 @item -p @var{file}
21411 @cindex @option{-p} (@code{gnathtml})
21412 If you are using Emacs and the most recent Emacs Ada mode, which provides
21413 a full Integrated Development Environment for compiling, checking,
21414 running and debugging applications, you may use @file{.gpr} files
21415 to give the directories where Emacs can find sources and object files.
21416
21417 Using this ^switch^option^, you can tell gnathtml to use these files.
21418 This allows you to get an html version of your application, even if it
21419 is spread over multiple directories.
21420
21421 @item -sc @var{color}
21422 @cindex @option{-sc} (@code{gnathtml})
21423 This ^switch^option^ allows you to change the color used for symbol
21424 definitions.
21425 The default value is red. The color argument can be any name accepted by html.
21426
21427 @item -t @var{file}
21428 @cindex @option{-t} (@code{gnathtml})
21429 This ^switch^option^ provides the name of a file. This file contains a list of
21430 file names to be converted, and the effect is exactly as though they had
21431 appeared explicitly on the command line. This
21432 is the recommended way to work around the command line length limit on some
21433 systems.
21434
21435 @end table
21436
21437 @node Installing gnathtml
21438 @section Installing @code{gnathtml}
21439
21440 @noindent
21441 @code{Perl} needs to be installed on your machine to run this script.
21442 @code{Perl} is freely available for almost every architecture and
21443 Operating System via the Internet.
21444
21445 On Unix systems, you  may want to modify  the  first line of  the script
21446 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
21447 is. The syntax of this line is :
21448 @smallexample
21449 #!full_path_name_to_perl
21450 @end smallexample
21451
21452 @noindent
21453 Alternatively, you may run the script using the following command line:
21454
21455 @smallexample
21456 $ perl gnathtml.pl [switches] files
21457 @end smallexample
21458
21459 @ifset vms
21460 @node LSE
21461 @section LSE
21462 @findex LSE
21463
21464 @noindent
21465 The GNAT distribution provides an Ada 95 template for the HP Language
21466 Sensitive Editor (LSE), a component of DECset. In order to
21467 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
21468
21469 @node Profiling
21470 @section Profiling
21471 @findex PCA
21472
21473 @noindent
21474 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
21475 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
21476 the collection phase with the /DEBUG qualifier.
21477
21478 @smallexample
21479 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
21480 $ DEFINE LIB$DEBUG PCA$COLLECTOR
21481 $ RUN/DEBUG <PROGRAM_NAME>
21482 @end smallexample
21483 @noindent
21484 @end ifset
21485
21486 @node Running and Debugging Ada Programs
21487 @chapter Running and Debugging Ada Programs
21488 @cindex Debugging
21489
21490 @noindent
21491 This chapter discusses how to debug Ada programs.
21492 @ifset vms
21493 It applies to GNAT on the Alpha OpenVMS platform;
21494 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
21495 since HP has implemented Ada support in the OpenVMS debugger on I64.
21496 @end ifset
21497
21498 An incorrect Ada program may be handled in three ways by the GNAT compiler:
21499
21500 @enumerate
21501 @item
21502 The illegality may be a violation of the static semantics of Ada. In
21503 that case GNAT diagnoses the constructs in the program that are illegal.
21504 It is then a straightforward matter for the user to modify those parts of
21505 the program.
21506
21507 @item
21508 The illegality may be a violation of the dynamic semantics of Ada. In
21509 that case the program compiles and executes, but may generate incorrect
21510 results, or may terminate abnormally with some exception.
21511
21512 @item
21513 When presented with a program that contains convoluted errors, GNAT
21514 itself may terminate abnormally without providing full diagnostics on
21515 the incorrect user program.
21516 @end enumerate
21517
21518 @menu
21519 * The GNAT Debugger GDB::
21520 * Running GDB::
21521 * Introduction to GDB Commands::
21522 * Using Ada Expressions::
21523 * Calling User-Defined Subprograms::
21524 * Using the Next Command in a Function::
21525 * Ada Exceptions::
21526 * Ada Tasks::
21527 * Debugging Generic Units::
21528 * GNAT Abnormal Termination or Failure to Terminate::
21529 * Naming Conventions for GNAT Source Files::
21530 * Getting Internal Debugging Information::
21531 * Stack Traceback::
21532 @end menu
21533
21534 @cindex Debugger
21535 @findex gdb
21536
21537 @node The GNAT Debugger GDB
21538 @section The GNAT Debugger GDB
21539
21540 @noindent
21541 @code{GDB} is a general purpose, platform-independent debugger that
21542 can be used to debug mixed-language programs compiled with @command{gcc},
21543 and in particular is capable of debugging Ada programs compiled with
21544 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
21545 complex Ada data structures.
21546
21547 The manual @cite{Debugging with GDB}
21548 @ifset vms
21549 , located in the GNU:[DOCS] directory,
21550 @end ifset
21551 contains full details on the usage of @code{GDB}, including a section on
21552 its usage on programs. This manual should be consulted for full
21553 details. The section that follows is a brief introduction to the
21554 philosophy and use of @code{GDB}.
21555
21556 When GNAT programs are compiled, the compiler optionally writes debugging
21557 information into the generated object file, including information on
21558 line numbers, and on declared types and variables. This information is
21559 separate from the generated code. It makes the object files considerably
21560 larger, but it does not add to the size of the actual executable that
21561 will be loaded into memory, and has no impact on run-time performance. The
21562 generation of debug information is triggered by the use of the
21563 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
21564 the compilations. It is important to emphasize that the use of these
21565 options does not change the generated code.
21566
21567 The debugging information is written in standard system formats that
21568 are used by many tools, including debuggers and profilers. The format
21569 of the information is typically designed to describe C types and
21570 semantics, but GNAT implements a translation scheme which allows full
21571 details about Ada types and variables to be encoded into these
21572 standard C formats. Details of this encoding scheme may be found in
21573 the file exp_dbug.ads in the GNAT source distribution. However, the
21574 details of this encoding are, in general, of no interest to a user,
21575 since @code{GDB} automatically performs the necessary decoding.
21576
21577 When a program is bound and linked, the debugging information is
21578 collected from the object files, and stored in the executable image of
21579 the program. Again, this process significantly increases the size of
21580 the generated executable file, but it does not increase the size of
21581 the executable program itself. Furthermore, if this program is run in
21582 the normal manner, it runs exactly as if the debug information were
21583 not present, and takes no more actual memory.
21584
21585 However, if the program is run under control of @code{GDB}, the
21586 debugger is activated.  The image of the program is loaded, at which
21587 point it is ready to run.  If a run command is given, then the program
21588 will run exactly as it would have if @code{GDB} were not present. This
21589 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
21590 entirely non-intrusive until a breakpoint is encountered.  If no
21591 breakpoint is ever hit, the program will run exactly as it would if no
21592 debugger were present. When a breakpoint is hit, @code{GDB} accesses
21593 the debugging information and can respond to user commands to inspect
21594 variables, and more generally to report on the state of execution.
21595
21596 @c **************
21597 @node Running GDB
21598 @section Running GDB
21599
21600 @noindent
21601 This section describes how to initiate the debugger.
21602 @c The above sentence is really just filler, but it was otherwise
21603 @c clumsy to get the first paragraph nonindented given the conditional
21604 @c nature of the description
21605
21606 @ifclear vms
21607 The debugger can be launched from a @code{GPS} menu or
21608 directly from the command line. The description below covers the latter use.
21609 All the commands shown can be used in the @code{GPS} debug console window,
21610 but there are usually more GUI-based ways to achieve the same effect.
21611 @end ifclear
21612
21613 The command to run @code{GDB} is
21614
21615 @smallexample
21616 $ ^gdb program^GDB PROGRAM^
21617 @end smallexample
21618
21619 @noindent
21620 where @code{^program^PROGRAM^} is the name of the executable file. This
21621 activates the debugger and results in a prompt for debugger commands.
21622 The simplest command is simply @code{run}, which causes the program to run
21623 exactly as if the debugger were not present. The following section
21624 describes some of the additional commands that can be given to @code{GDB}.
21625
21626 @c *******************************
21627 @node Introduction to GDB Commands
21628 @section Introduction to GDB Commands
21629
21630 @noindent
21631 @code{GDB} contains a large repertoire of commands. The manual
21632 @cite{Debugging with GDB}
21633 @ifset vms
21634 (located in the GNU:[DOCS] directory)
21635 @end ifset
21636 includes extensive documentation on the use
21637 of these commands, together with examples of their use. Furthermore,
21638 the command @var{help} invoked from within @code{GDB} activates a simple help
21639 facility which summarizes the available commands and their options.
21640 In this section we summarize a few of the most commonly
21641 used commands to give an idea of what @code{GDB} is about. You should create
21642 a simple program with debugging information and experiment with the use of
21643 these @code{GDB} commands on the program as you read through the
21644 following section.
21645
21646 @table @code
21647 @item set args @var{arguments}
21648 The @var{arguments} list above is a list of arguments to be passed to
21649 the program on a subsequent run command, just as though the arguments
21650 had been entered on a normal invocation of the program. The @code{set args}
21651 command is not needed if the program does not require arguments.
21652
21653 @item run
21654 The @code{run} command causes execution of the program to start from
21655 the beginning. If the program is already running, that is to say if
21656 you are currently positioned at a breakpoint, then a prompt will ask
21657 for confirmation that you want to abandon the current execution and
21658 restart.
21659
21660 @item breakpoint @var{location}
21661 The breakpoint command sets a breakpoint, that is to say a point at which
21662 execution will halt and @code{GDB} will await further
21663 commands. @var{location} is
21664 either a line number within a file, given in the format @code{file:linenumber},
21665 or it is the name of a subprogram. If you request that a breakpoint be set on
21666 a subprogram that is overloaded, a prompt will ask you to specify on which of
21667 those subprograms you want to breakpoint. You can also
21668 specify that all of them should be breakpointed. If the program is run
21669 and execution encounters the breakpoint, then the program
21670 stops and @code{GDB} signals that the breakpoint was encountered by
21671 printing the line of code before which the program is halted.
21672
21673 @item breakpoint exception @var{name}
21674 A special form of the breakpoint command which breakpoints whenever
21675 exception @var{name} is raised.
21676 If @var{name} is omitted,
21677 then a breakpoint will occur when any exception is raised.
21678
21679 @item print @var{expression}
21680 This will print the value of the given expression. Most simple
21681 Ada expression formats are properly handled by @code{GDB}, so the expression
21682 can contain function calls, variables, operators, and attribute references.
21683
21684 @item continue
21685 Continues execution following a breakpoint, until the next breakpoint or the
21686 termination of the program.
21687
21688 @item step
21689 Executes a single line after a breakpoint. If the next statement
21690 is a subprogram call, execution continues into (the first statement of)
21691 the called subprogram.
21692
21693 @item next
21694 Executes a single line. If this line is a subprogram call, executes and
21695 returns from the call.
21696
21697 @item list
21698 Lists a few lines around the current source location. In practice, it
21699 is usually more convenient to have a separate edit window open with the
21700 relevant source file displayed. Successive applications of this command
21701 print subsequent lines. The command can be given an argument which is a
21702 line number, in which case it displays a few lines around the specified one.
21703
21704 @item backtrace
21705 Displays a backtrace of the call chain. This command is typically
21706 used after a breakpoint has occurred, to examine the sequence of calls that
21707 leads to the current breakpoint. The display includes one line for each
21708 activation record (frame) corresponding to an active subprogram.
21709
21710 @item up
21711 At a breakpoint, @code{GDB} can display the values of variables local
21712 to the current frame. The command @code{up} can be used to
21713 examine the contents of other active frames, by moving the focus up
21714 the stack, that is to say from callee to caller, one frame at a time.
21715
21716 @item down
21717 Moves the focus of @code{GDB} down from the frame currently being
21718 examined to the frame of its callee (the reverse of the previous command),
21719
21720 @item frame @var{n}
21721 Inspect the frame with the given number. The value 0 denotes the frame
21722 of the current breakpoint, that is to say the top of the call stack.
21723
21724 @end table
21725
21726 @noindent
21727 The above list is a very short introduction to the commands that
21728 @code{GDB} provides. Important additional capabilities, including conditional
21729 breakpoints, the ability to execute command sequences on a breakpoint,
21730 the ability to debug at the machine instruction level and many other
21731 features are described in detail in @cite{Debugging with GDB}.
21732 Note that most commands can be abbreviated
21733 (for example, c for continue, bt for backtrace).
21734
21735 @node Using Ada Expressions
21736 @section Using Ada Expressions
21737 @cindex Ada expressions
21738
21739 @noindent
21740 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
21741 extensions. The philosophy behind the design of this subset is
21742
21743 @itemize @bullet
21744 @item
21745 That @code{GDB} should provide basic literals and access to operations for
21746 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
21747 leaving more sophisticated computations to subprograms written into the
21748 program (which therefore may be called from @code{GDB}).
21749
21750 @item
21751 That type safety and strict adherence to Ada language restrictions
21752 are not particularly important to the @code{GDB} user.
21753
21754 @item
21755 That brevity is important to the @code{GDB} user.
21756 @end itemize
21757
21758 @noindent
21759 Thus, for brevity, the debugger acts as if there were
21760 implicit @code{with} and @code{use} clauses in effect for all user-written
21761 packages, thus making it unnecessary to fully qualify most names with
21762 their packages, regardless of context. Where this causes ambiguity,
21763 @code{GDB} asks the user's intent.
21764
21765 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
21766
21767 @node Calling User-Defined Subprograms
21768 @section Calling User-Defined Subprograms
21769
21770 @noindent
21771 An important capability of @code{GDB} is the ability to call user-defined
21772 subprograms while debugging. This is achieved simply by entering
21773 a subprogram call statement in the form:
21774
21775 @smallexample
21776 call subprogram-name (parameters)
21777 @end smallexample
21778
21779 @noindent
21780 The keyword @code{call} can be omitted in the normal case where the
21781 @code{subprogram-name} does not coincide with any of the predefined
21782 @code{GDB} commands.
21783
21784 The effect is to invoke the given subprogram, passing it the
21785 list of parameters that is supplied. The parameters can be expressions and
21786 can include variables from the program being debugged. The
21787 subprogram must be defined
21788 at the library level within your program, and @code{GDB} will call the
21789 subprogram within the environment of your program execution (which
21790 means that the subprogram is free to access or even modify variables
21791 within your program).
21792
21793 The most important use of this facility is in allowing the inclusion of
21794 debugging routines that are tailored to particular data structures
21795 in your program. Such debugging routines can be written to provide a suitably
21796 high-level description of an abstract type, rather than a low-level dump
21797 of its physical layout. After all, the standard
21798 @code{GDB print} command only knows the physical layout of your
21799 types, not their abstract meaning. Debugging routines can provide information
21800 at the desired semantic level and are thus enormously useful.
21801
21802 For example, when debugging GNAT itself, it is crucial to have access to
21803 the contents of the tree nodes used to represent the program internally.
21804 But tree nodes are represented simply by an integer value (which in turn
21805 is an index into a table of nodes).
21806 Using the @code{print} command on a tree node would simply print this integer
21807 value, which is not very useful. But the PN routine (defined in file
21808 treepr.adb in the GNAT sources) takes a tree node as input, and displays
21809 a useful high level representation of the tree node, which includes the
21810 syntactic category of the node, its position in the source, the integers
21811 that denote descendant nodes and parent node, as well as varied
21812 semantic information. To study this example in more detail, you might want to
21813 look at the body of the PN procedure in the stated file.
21814
21815 @node Using the Next Command in a Function
21816 @section Using the Next Command in a Function
21817
21818 @noindent
21819 When you use the @code{next} command in a function, the current source
21820 location will advance to the next statement as usual. A special case
21821 arises in the case of a @code{return} statement.
21822
21823 Part of the code for a return statement is the ``epilog'' of the function.
21824 This is the code that returns to the caller. There is only one copy of
21825 this epilog code, and it is typically associated with the last return
21826 statement in the function if there is more than one return. In some
21827 implementations, this epilog is associated with the first statement
21828 of the function.
21829
21830 The result is that if you use the @code{next} command from a return
21831 statement that is not the last return statement of the function you
21832 may see a strange apparent jump to the last return statement or to
21833 the start of the function. You should simply ignore this odd jump.
21834 The value returned is always that from the first return statement
21835 that was stepped through.
21836
21837 @node Ada Exceptions
21838 @section Breaking on Ada Exceptions
21839 @cindex Exceptions
21840
21841 @noindent
21842 You can set breakpoints that trip when your program raises
21843 selected exceptions.
21844
21845 @table @code
21846 @item break exception
21847 Set a breakpoint that trips whenever (any task in the) program raises
21848 any exception.
21849
21850 @item break exception @var{name}
21851 Set a breakpoint that trips whenever (any task in the) program raises
21852 the exception @var{name}.
21853
21854 @item break exception unhandled
21855 Set a breakpoint that trips whenever (any task in the) program raises an
21856 exception for which there is no handler.
21857
21858 @item info exceptions
21859 @itemx info exceptions @var{regexp}
21860 The @code{info exceptions} command permits the user to examine all defined
21861 exceptions within Ada programs. With a regular expression, @var{regexp}, as
21862 argument, prints out only those exceptions whose name matches @var{regexp}.
21863 @end table
21864
21865 @node Ada Tasks
21866 @section Ada Tasks
21867 @cindex Tasks
21868
21869 @noindent
21870 @code{GDB} allows the following task-related commands:
21871
21872 @table @code
21873 @item info tasks
21874 This command shows a list of current Ada tasks, as in the following example:
21875
21876 @smallexample
21877 @iftex
21878 @leftskip=0cm
21879 @end iftex
21880 (gdb) info tasks
21881   ID       TID P-ID   Thread Pri State                 Name
21882    1   8088000   0   807e000  15 Child Activation Wait main_task
21883    2   80a4000   1   80ae000  15 Accept/Select Wait    b
21884    3   809a800   1   80a4800  15 Child Activation Wait a
21885 *  4   80ae800   3   80b8000  15 Running               c
21886 @end smallexample
21887
21888 @noindent
21889 In this listing, the asterisk before the first task indicates it to be the
21890 currently running task. The first column lists the task ID that is used
21891 to refer to tasks in the following commands.
21892
21893 @item break @var{linespec} task @var{taskid}
21894 @itemx break @var{linespec} task @var{taskid} if @dots{}
21895 @cindex Breakpoints and tasks
21896 These commands are like the @code{break @dots{} thread @dots{}}.
21897 @var{linespec} specifies source lines.
21898
21899 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
21900 to specify that you only want @code{GDB} to stop the program when a
21901 particular Ada task reaches this breakpoint. @var{taskid} is one of the
21902 numeric task identifiers assigned by @code{GDB}, shown in the first
21903 column of the @samp{info tasks} display.
21904
21905 If you do not specify @samp{task @var{taskid}} when you set a
21906 breakpoint, the breakpoint applies to @emph{all} tasks of your
21907 program.
21908
21909 You can use the @code{task} qualifier on conditional breakpoints as
21910 well; in this case, place @samp{task @var{taskid}} before the
21911 breakpoint condition (before the @code{if}).
21912
21913 @item task @var{taskno}
21914 @cindex Task switching
21915
21916 This command allows to switch to the task referred by @var{taskno}. In
21917 particular, This allows to browse the backtrace of the specified
21918 task. It is advised to switch back to the original task before
21919 continuing execution otherwise the scheduling of the program may be
21920 perturbed.
21921 @end table
21922
21923 @noindent
21924 For more detailed information on the tasking support,
21925 see @cite{Debugging with GDB}.
21926
21927 @node Debugging Generic Units
21928 @section Debugging Generic Units
21929 @cindex Debugging Generic Units
21930 @cindex Generics
21931
21932 @noindent
21933 GNAT always uses code expansion for generic instantiation. This means that
21934 each time an instantiation occurs, a complete copy of the original code is
21935 made, with appropriate substitutions of formals by actuals.
21936
21937 It is not possible to refer to the original generic entities in
21938 @code{GDB}, but it is always possible to debug a particular instance of
21939 a generic, by using the appropriate expanded names. For example, if we have
21940
21941 @smallexample @c ada
21942 @group
21943 @cartouche
21944 procedure g is
21945
21946    generic package k is
21947       procedure kp (v1 : in out integer);
21948    end k;
21949
21950    package body k is
21951       procedure kp (v1 : in out integer) is
21952       begin
21953          v1 := v1 + 1;
21954       end kp;
21955    end k;
21956
21957    package k1 is new k;
21958    package k2 is new k;
21959
21960    var : integer := 1;
21961
21962 begin
21963    k1.kp (var);
21964    k2.kp (var);
21965    k1.kp (var);
21966    k2.kp (var);
21967 end;
21968 @end cartouche
21969 @end group
21970 @end smallexample
21971
21972 @noindent
21973 Then to break on a call to procedure kp in the k2 instance, simply
21974 use the command:
21975
21976 @smallexample
21977 (gdb) break g.k2.kp
21978 @end smallexample
21979
21980 @noindent
21981 When the breakpoint occurs, you can step through the code of the
21982 instance in the normal manner and examine the values of local variables, as for
21983 other units.
21984
21985 @node GNAT Abnormal Termination or Failure to Terminate
21986 @section GNAT Abnormal Termination or Failure to Terminate
21987 @cindex GNAT Abnormal Termination or Failure to Terminate
21988
21989 @noindent
21990 When presented with programs that contain serious errors in syntax
21991 or semantics,
21992 GNAT may on rare occasions  experience problems in operation, such
21993 as aborting with a
21994 segmentation fault or illegal memory access, raising an internal
21995 exception, terminating abnormally, or failing to terminate at all.
21996 In such cases, you can activate
21997 various features of GNAT that can help you pinpoint the construct in your
21998 program that is the likely source of the problem.
21999
22000 The following strategies are presented in increasing order of
22001 difficulty, corresponding to your experience in using GNAT and your
22002 familiarity with compiler internals.
22003
22004 @enumerate
22005 @item
22006 Run @command{gcc} with the @option{-gnatf}. This first
22007 switch causes all errors on a given line to be reported. In its absence,
22008 only the first error on a line is displayed.
22009
22010 The @option{-gnatdO} switch causes errors to be displayed as soon as they
22011 are encountered, rather than after compilation is terminated. If GNAT
22012 terminates prematurely or goes into an infinite loop, the last error
22013 message displayed may help to pinpoint the culprit.
22014
22015 @item
22016 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
22017 mode, @command{gcc} produces ongoing information about the progress of the
22018 compilation and provides the name of each procedure as code is
22019 generated. This switch allows you to find which Ada procedure was being
22020 compiled when it encountered a code generation problem.
22021
22022 @item
22023 @cindex @option{-gnatdc} switch
22024 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
22025 switch that does for the front-end what @option{^-v^VERBOSE^} does
22026 for the back end. The system prints the name of each unit,
22027 either a compilation unit or nested unit, as it is being analyzed.
22028 @item
22029 Finally, you can start
22030 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
22031 front-end of GNAT, and can be run independently (normally it is just
22032 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
22033 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
22034 @code{where} command is the first line of attack; the variable
22035 @code{lineno} (seen by @code{print lineno}), used by the second phase of
22036 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
22037 which the execution stopped, and @code{input_file name} indicates the name of
22038 the source file.
22039 @end enumerate
22040
22041 @node Naming Conventions for GNAT Source Files
22042 @section Naming Conventions for GNAT Source Files
22043
22044 @noindent
22045 In order to examine the workings of the GNAT system, the following
22046 brief description of its organization may be helpful:
22047
22048 @itemize @bullet
22049 @item
22050 Files with prefix @file{^sc^SC^} contain the lexical scanner.
22051
22052 @item
22053 All files prefixed with @file{^par^PAR^} are components of the parser. The
22054 numbers correspond to chapters of the Ada Reference Manual. For example,
22055 parsing of select statements can be found in @file{par-ch9.adb}.
22056
22057 @item
22058 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
22059 numbers correspond to chapters of the Ada standard. For example, all
22060 issues involving context clauses can be found in @file{sem_ch10.adb}. In
22061 addition, some features of the language require sufficient special processing
22062 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
22063 dynamic dispatching, etc.
22064
22065 @item
22066 All files prefixed with @file{^exp^EXP^} perform normalization and
22067 expansion of the intermediate representation (abstract syntax tree, or AST).
22068 these files use the same numbering scheme as the parser and semantics files.
22069 For example, the construction of record initialization procedures is done in
22070 @file{exp_ch3.adb}.
22071
22072 @item
22073 The files prefixed with @file{^bind^BIND^} implement the binder, which
22074 verifies the consistency of the compilation, determines an order of
22075 elaboration, and generates the bind file.
22076
22077 @item
22078 The files @file{atree.ads} and @file{atree.adb} detail the low-level
22079 data structures used by the front-end.
22080
22081 @item
22082 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
22083 the abstract syntax tree as produced by the parser.
22084
22085 @item
22086 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
22087 all entities, computed during semantic analysis.
22088
22089 @item
22090 Library management issues are dealt with in files with prefix
22091 @file{^lib^LIB^}.
22092
22093 @item
22094 @findex Ada
22095 @cindex Annex A
22096 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
22097 defined in Annex A.
22098
22099 @item
22100 @findex Interfaces
22101 @cindex Annex B
22102 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
22103 defined in Annex B.
22104
22105 @item
22106 @findex System
22107 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
22108 both language-defined children and GNAT run-time routines.
22109
22110 @item
22111 @findex GNAT
22112 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
22113 general-purpose packages, fully documented in their specifications. All
22114 the other @file{.c} files are modifications of common @command{gcc} files.
22115 @end itemize
22116
22117 @node Getting Internal Debugging Information
22118 @section Getting Internal Debugging Information
22119
22120 @noindent
22121 Most compilers have internal debugging switches and modes. GNAT
22122 does also, except GNAT internal debugging switches and modes are not
22123 secret. A summary and full description of all the compiler and binder
22124 debug flags are in the file @file{debug.adb}. You must obtain the
22125 sources of the compiler to see the full detailed effects of these flags.
22126
22127 The switches that print the source of the program (reconstructed from
22128 the internal tree) are of general interest for user programs, as are the
22129 options to print
22130 the full internal tree, and the entity table (the symbol table
22131 information). The reconstructed source provides a readable version of the
22132 program after the front-end has completed analysis and  expansion,
22133 and is useful when studying the performance of specific constructs.
22134 For example, constraint checks are indicated, complex aggregates
22135 are replaced with loops and assignments, and tasking primitives
22136 are replaced with run-time calls.
22137
22138 @node Stack Traceback
22139 @section Stack Traceback
22140 @cindex traceback
22141 @cindex stack traceback
22142 @cindex stack unwinding
22143
22144 @noindent
22145 Traceback is a mechanism to display the sequence of subprogram calls that
22146 leads to a specified execution point in a program. Often (but not always)
22147 the execution point is an instruction at which an exception has been raised.
22148 This mechanism is also known as @i{stack unwinding} because it obtains
22149 its information by scanning the run-time stack and recovering the activation
22150 records of all active subprograms. Stack unwinding is one of the most
22151 important tools for program debugging.
22152
22153 The first entry stored in traceback corresponds to the deepest calling level,
22154 that is to say the subprogram currently executing the instruction
22155 from which we want to obtain the traceback.
22156
22157 Note that there is no runtime performance penalty when stack traceback
22158 is enabled, and no exception is raised during program execution.
22159
22160 @menu
22161 * Non-Symbolic Traceback::
22162 * Symbolic Traceback::
22163 @end menu
22164
22165 @node Non-Symbolic Traceback
22166 @subsection Non-Symbolic Traceback
22167 @cindex traceback, non-symbolic
22168
22169 @noindent
22170 Note: this feature is not supported on all platforms. See
22171 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
22172 platforms.
22173
22174 @menu
22175 * Tracebacks From an Unhandled Exception::
22176 * Tracebacks From Exception Occurrences (non-symbolic)::
22177 * Tracebacks From Anywhere in a Program (non-symbolic)::
22178 @end menu
22179
22180 @node Tracebacks From an Unhandled Exception
22181 @subsubsection Tracebacks From an Unhandled Exception
22182
22183 @noindent
22184 A runtime non-symbolic traceback is a list of addresses of call instructions.
22185 To enable this feature you must use the @option{-E}
22186 @code{gnatbind}'s option. With this option a stack traceback is stored as part
22187 of exception information. You can retrieve this information using the
22188 @code{addr2line} tool.
22189
22190 Here is a simple example:
22191
22192 @smallexample @c ada
22193 @cartouche
22194 procedure STB is
22195
22196    procedure P1 is
22197    begin
22198       raise Constraint_Error;
22199    end P1;
22200
22201    procedure P2 is
22202    begin
22203       P1;
22204    end P2;
22205
22206 begin
22207    P2;
22208 end STB;
22209 @end cartouche
22210 @end smallexample
22211
22212 @smallexample
22213 $ gnatmake stb -bargs -E
22214 $ stb
22215
22216 Execution terminated by unhandled exception
22217 Exception name: CONSTRAINT_ERROR
22218 Message: stb.adb:5
22219 Call stack traceback locations:
22220 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
22221 @end smallexample
22222
22223 @noindent
22224 As we see the traceback lists a sequence of addresses for the unhandled
22225 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
22226 guess that this exception come from procedure P1. To translate these
22227 addresses into the source lines where the calls appear, the
22228 @code{addr2line} tool, described below, is invaluable. The use of this tool
22229 requires the program to be compiled with debug information.
22230
22231 @smallexample
22232 $ gnatmake -g stb -bargs -E
22233 $ stb
22234
22235 Execution terminated by unhandled exception
22236 Exception name: CONSTRAINT_ERROR
22237 Message: stb.adb:5
22238 Call stack traceback locations:
22239 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
22240
22241 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
22242    0x4011f1 0x77e892a4
22243
22244 00401373 at d:/stb/stb.adb:5
22245 0040138B at d:/stb/stb.adb:10
22246 0040139C at d:/stb/stb.adb:14
22247 00401335 at d:/stb/b~stb.adb:104
22248 004011C4 at /build/.../crt1.c:200
22249 004011F1 at /build/.../crt1.c:222
22250 77E892A4 in ?? at ??:0
22251 @end smallexample
22252
22253 @noindent
22254 The @code{addr2line} tool has several other useful options:
22255
22256 @table @code
22257 @item --functions
22258 to get the function name corresponding to any location
22259
22260 @item --demangle=gnat
22261 to use the gnat decoding mode for the function names. Note that
22262 for binutils version 2.9.x the option is simply @option{--demangle}.
22263 @end table
22264
22265 @smallexample
22266 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
22267    0x40139c 0x401335 0x4011c4 0x4011f1
22268
22269 00401373 in stb.p1 at d:/stb/stb.adb:5
22270 0040138B in stb.p2 at d:/stb/stb.adb:10
22271 0040139C in stb at d:/stb/stb.adb:14
22272 00401335 in main at d:/stb/b~stb.adb:104
22273 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
22274 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
22275 @end smallexample
22276
22277 @noindent
22278 From this traceback we can see that the exception was raised in
22279 @file{stb.adb} at line 5, which was reached from a procedure call in
22280 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
22281 which contains the call to the main program.
22282 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
22283 and the output will vary from platform to platform.
22284
22285 It is also possible to use @code{GDB} with these traceback addresses to debug
22286 the program. For example, we can break at a given code location, as reported
22287 in the stack traceback:
22288
22289 @smallexample
22290 $ gdb -nw stb
22291 @ifclear vms
22292 @noindent
22293 Furthermore, this feature is not implemented inside Windows DLL. Only
22294 the non-symbolic traceback is reported in this case.
22295 @end ifclear
22296
22297 (gdb) break *0x401373
22298 Breakpoint 1 at 0x401373: file stb.adb, line 5.
22299 @end smallexample
22300
22301 @noindent
22302 It is important to note that the stack traceback addresses
22303 do not change when debug information is included. This is particularly useful
22304 because it makes it possible to release software without debug information (to
22305 minimize object size), get a field report that includes a stack traceback
22306 whenever an internal bug occurs, and then be able to retrieve the sequence
22307 of calls with the same program compiled with debug information.
22308
22309 @node Tracebacks From Exception Occurrences (non-symbolic)
22310 @subsubsection Tracebacks From Exception Occurrences
22311
22312 @noindent
22313 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
22314 The stack traceback is attached to the exception information string, and can
22315 be retrieved in an exception handler within the Ada program, by means of the
22316 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
22317
22318 @smallexample @c ada
22319 with Ada.Text_IO;
22320 with Ada.Exceptions;
22321
22322 procedure STB is
22323
22324    use Ada;
22325    use Ada.Exceptions;
22326
22327    procedure P1 is
22328       K : Positive := 1;
22329    begin
22330       K := K - 1;
22331    exception
22332       when E : others =>
22333          Text_IO.Put_Line (Exception_Information (E));
22334    end P1;
22335
22336    procedure P2 is
22337    begin
22338       P1;
22339    end P2;
22340
22341 begin
22342    P2;
22343 end STB;
22344 @end smallexample
22345
22346 @noindent
22347 This program will output:
22348
22349 @smallexample
22350 $ stb
22351
22352 Exception name: CONSTRAINT_ERROR
22353 Message: stb.adb:12
22354 Call stack traceback locations:
22355 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
22356 @end smallexample
22357
22358 @node Tracebacks From Anywhere in a Program (non-symbolic)
22359 @subsubsection Tracebacks From Anywhere in a Program
22360
22361 @noindent
22362 It is also possible to retrieve a stack traceback from anywhere in a
22363 program. For this you need to
22364 use the @code{GNAT.Traceback} API. This package includes a procedure called
22365 @code{Call_Chain} that computes a complete stack traceback, as well as useful
22366 display procedures described below. It is not necessary to use the
22367 @option{-E gnatbind} option in this case, because the stack traceback mechanism
22368 is invoked explicitly.
22369
22370 @noindent
22371 In the following example we compute a traceback at a specific location in
22372 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
22373 convert addresses to strings:
22374
22375 @smallexample @c ada
22376 with Ada.Text_IO;
22377 with GNAT.Traceback;
22378 with GNAT.Debug_Utilities;
22379
22380 procedure STB is
22381
22382    use Ada;
22383    use GNAT;
22384    use GNAT.Traceback;
22385
22386    procedure P1 is
22387       TB  : Tracebacks_Array (1 .. 10);
22388       --  We are asking for a maximum of 10 stack frames.
22389       Len : Natural;
22390       --  Len will receive the actual number of stack frames returned.
22391    begin
22392       Call_Chain (TB, Len);
22393
22394       Text_IO.Put ("In STB.P1 : ");
22395
22396       for K in 1 .. Len loop
22397          Text_IO.Put (Debug_Utilities.Image (TB (K)));
22398          Text_IO.Put (' ');
22399       end loop;
22400
22401       Text_IO.New_Line;
22402    end P1;
22403
22404    procedure P2 is
22405    begin
22406       P1;
22407    end P2;
22408
22409 begin
22410    P2;
22411 end STB;
22412 @end smallexample
22413
22414 @smallexample
22415 $ gnatmake -g stb
22416 $ stb
22417
22418 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
22419 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
22420 @end smallexample
22421
22422 @noindent
22423 You can then get further information by invoking the @code{addr2line}
22424 tool as described earlier (note that the hexadecimal addresses
22425 need to be specified in C format, with a leading ``0x'').
22426
22427 @node Symbolic Traceback
22428 @subsection Symbolic Traceback
22429 @cindex traceback, symbolic
22430
22431 @noindent
22432 A symbolic traceback is a stack traceback in which procedure names are
22433 associated with each code location.
22434
22435 @noindent
22436 Note that this feature is not supported on all platforms. See
22437 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
22438 list of currently supported platforms.
22439
22440 @noindent
22441 Note that the symbolic traceback requires that the program be compiled
22442 with debug information. If it is not compiled with debug information
22443 only the non-symbolic information will be valid.
22444
22445 @menu
22446 * Tracebacks From Exception Occurrences (symbolic)::
22447 * Tracebacks From Anywhere in a Program (symbolic)::
22448 @end menu
22449
22450 @node Tracebacks From Exception Occurrences (symbolic)
22451 @subsubsection Tracebacks From Exception Occurrences
22452
22453 @smallexample @c ada
22454 with Ada.Text_IO;
22455 with GNAT.Traceback.Symbolic;
22456
22457 procedure STB is
22458
22459    procedure P1 is
22460    begin
22461       raise Constraint_Error;
22462    end P1;
22463
22464    procedure P2 is
22465    begin
22466       P1;
22467    end P2;
22468
22469    procedure P3 is
22470    begin
22471       P2;
22472    end P3;
22473
22474 begin
22475    P3;
22476 exception
22477    when E : others =>
22478       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
22479 end STB;
22480 @end smallexample
22481
22482 @smallexample
22483 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
22484 $ stb
22485
22486 0040149F in stb.p1 at stb.adb:8
22487 004014B7 in stb.p2 at stb.adb:13
22488 004014CF in stb.p3 at stb.adb:18
22489 004015DD in ada.stb at stb.adb:22
22490 00401461 in main at b~stb.adb:168
22491 004011C4 in __mingw_CRTStartup at crt1.c:200
22492 004011F1 in mainCRTStartup at crt1.c:222
22493 77E892A4 in ?? at ??:0
22494 @end smallexample
22495
22496 @noindent
22497 In the above example the ``.\'' syntax in the @command{gnatmake} command
22498 is currently required by @command{addr2line} for files that are in
22499 the current working directory.
22500 Moreover, the exact sequence of linker options may vary from platform
22501 to platform.
22502 The above @option{-largs} section is for Windows platforms. By contrast,
22503 under Unix there is no need for the @option{-largs} section.
22504 Differences across platforms are due to details of linker implementation.
22505
22506 @node Tracebacks From Anywhere in a Program (symbolic)
22507 @subsubsection Tracebacks From Anywhere in a Program
22508
22509 @noindent
22510 It is possible to get a symbolic stack traceback
22511 from anywhere in a program, just as for non-symbolic tracebacks.
22512 The first step is to obtain a non-symbolic
22513 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
22514 information. Here is an example:
22515
22516 @smallexample @c ada
22517 with Ada.Text_IO;
22518 with GNAT.Traceback;
22519 with GNAT.Traceback.Symbolic;
22520
22521 procedure STB is
22522
22523    use Ada;
22524    use GNAT.Traceback;
22525    use GNAT.Traceback.Symbolic;
22526
22527    procedure P1 is
22528       TB  : Tracebacks_Array (1 .. 10);
22529       --  We are asking for a maximum of 10 stack frames.
22530       Len : Natural;
22531       --  Len will receive the actual number of stack frames returned.
22532    begin
22533       Call_Chain (TB, Len);
22534       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
22535    end P1;
22536
22537    procedure P2 is
22538    begin
22539       P1;
22540    end P2;
22541
22542 begin
22543    P2;
22544 end STB;
22545 @end smallexample
22546
22547 @c ******************************
22548 @ifset vms
22549 @node Compatibility with HP Ada
22550 @chapter Compatibility with HP Ada
22551 @cindex Compatibility
22552
22553 @noindent
22554 @cindex DEC Ada
22555 @cindex HP Ada
22556 @cindex Compatibility between GNAT and HP Ada
22557 This chapter compares HP Ada (formerly known as ``DEC Ada'')
22558 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
22559 GNAT is highly compatible
22560 with HP Ada, and it should generally be straightforward to port code
22561 from the HP Ada environment to GNAT. However, there are a few language
22562 and implementation differences of which the user must be aware. These
22563 differences are discussed in this chapter. In
22564 addition, the operating environment and command structure for the
22565 compiler are different, and these differences are also discussed.
22566
22567 For further details on these and other compatibility issues,
22568 see Appendix E of the HP publication
22569 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
22570
22571 Except where otherwise indicated, the description of GNAT for OpenVMS
22572 applies to both the Alpha and I64 platforms.
22573
22574 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
22575 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22576
22577 The discussion in this chapter addresses specifically the implementation
22578 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
22579 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
22580 GNAT always follows the Alpha implementation.
22581
22582 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
22583 attributes are recognized, although only a subset of them can sensibly
22584 be implemented.  The description of pragmas in the
22585 @cite{GNAT Reference Manual} indicates whether or not they are applicable
22586 to non-VMS systems.
22587
22588 @menu
22589 * Ada Language Compatibility::
22590 * Differences in the Definition of Package System::
22591 * Language-Related Features::
22592 * The Package STANDARD::
22593 * The Package SYSTEM::
22594 * Tasking and Task-Related Features::
22595 * Pragmas and Pragma-Related Features::
22596 * Library of Predefined Units::
22597 * Bindings::
22598 * Main Program Definition::
22599 * Implementation-Defined Attributes::
22600 * Compiler and Run-Time Interfacing::
22601 * Program Compilation and Library Management::
22602 * Input-Output::
22603 * Implementation Limits::
22604 * Tools and Utilities::
22605 @end menu
22606
22607 @node Ada Language Compatibility
22608 @section Ada Language Compatibility
22609
22610 @noindent
22611 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
22612 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
22613 with Ada 83, and therefore Ada 83 programs will compile
22614 and run under GNAT with
22615 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
22616 provides details on specific incompatibilities.
22617
22618 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
22619 as well as the pragma @code{ADA_83}, to force the compiler to
22620 operate in Ada 83 mode. This mode does not guarantee complete
22621 conformance to Ada 83, but in practice is sufficient to
22622 eliminate most sources of incompatibilities.
22623 In particular, it eliminates the recognition of the
22624 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
22625 in Ada 83 programs is legal, and handles the cases of packages
22626 with optional bodies, and generics that instantiate unconstrained
22627 types without the use of @code{(<>)}.
22628
22629 @node Differences in the Definition of Package System
22630 @section Differences in the Definition of Package @code{System}
22631
22632 @noindent
22633 An Ada compiler is allowed to add
22634 implementation-dependent declarations to package @code{System}.
22635 In normal mode,
22636 GNAT does not take advantage of this permission, and the version of
22637 @code{System} provided by GNAT exactly matches that defined in the Ada
22638 Reference Manual.
22639
22640 However, HP Ada adds an extensive set of declarations to package
22641 @code{System},
22642 as fully documented in the HP Ada manuals. To minimize changes required
22643 for programs that make use of these extensions, GNAT provides the pragma
22644 @code{Extend_System} for extending the definition of package System. By using:
22645 @cindex pragma @code{Extend_System}
22646 @cindex @code{Extend_System} pragma
22647
22648 @smallexample @c ada
22649 @group
22650 @cartouche
22651 pragma Extend_System (Aux_DEC);
22652 @end cartouche
22653 @end group
22654 @end smallexample
22655
22656 @noindent
22657 the set of definitions in @code{System} is extended to include those in
22658 package @code{System.Aux_DEC}.
22659 @cindex @code{System.Aux_DEC} package
22660 @cindex @code{Aux_DEC} package (child of @code{System})
22661 These definitions are incorporated directly into package @code{System},
22662 as though they had been declared there. For a
22663 list of the declarations added, see the specification of this package,
22664 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
22665 @cindex @file{s-auxdec.ads} file
22666 The pragma @code{Extend_System} is a configuration pragma, which means that
22667 it can be placed in the file @file{gnat.adc}, so that it will automatically
22668 apply to all subsequent compilations. See @ref{Configuration Pragmas},
22669 for further details.
22670
22671 An alternative approach that avoids the use of the non-standard
22672 @code{Extend_System} pragma is to add a context clause to the unit that
22673 references these facilities:
22674
22675 @smallexample @c ada
22676 @cartouche
22677 with System.Aux_DEC;
22678 use  System.Aux_DEC;
22679 @end cartouche
22680 @end smallexample
22681
22682 @noindent
22683 The effect is not quite semantically identical to incorporating
22684 the declarations directly into package @code{System},
22685 but most programs will not notice a difference
22686 unless they use prefix notation (e.g. @code{System.Integer_8})
22687 to reference the entities directly in package @code{System}.
22688 For units containing such references,
22689 the prefixes must either be removed, or the pragma @code{Extend_System}
22690 must be used.
22691
22692 @node Language-Related Features
22693 @section Language-Related Features
22694
22695 @noindent
22696 The following sections highlight differences in types,
22697 representations of types, operations, alignment, and
22698 related topics.
22699
22700 @menu
22701 * Integer Types and Representations::
22702 * Floating-Point Types and Representations::
22703 * Pragmas Float_Representation and Long_Float::
22704 * Fixed-Point Types and Representations::
22705 * Record and Array Component Alignment::
22706 * Address Clauses::
22707 * Other Representation Clauses::
22708 @end menu
22709
22710 @node Integer Types and Representations
22711 @subsection Integer Types and Representations
22712
22713 @noindent
22714 The set of predefined integer types is identical in HP Ada and GNAT.
22715 Furthermore the representation of these integer types is also identical,
22716 including the capability of size clauses forcing biased representation.
22717
22718 In addition,
22719 HP Ada for OpenVMS Alpha systems has defined the
22720 following additional integer types in package @code{System}:
22721
22722 @itemize @bullet
22723
22724 @item
22725 @code{INTEGER_8}
22726
22727 @item
22728 @code{INTEGER_16}
22729
22730 @item
22731 @code{INTEGER_32}
22732
22733 @item
22734 @code{INTEGER_64}
22735
22736 @item
22737 @code{LARGEST_INTEGER}
22738 @end itemize
22739
22740 @noindent
22741 In GNAT, the first four of these types may be obtained from the
22742 standard Ada package @code{Interfaces}.
22743 Alternatively, by use of the pragma @code{Extend_System}, identical
22744 declarations can be referenced directly in package @code{System}.
22745 On both GNAT and HP Ada, the maximum integer size is 64 bits.
22746
22747 @node Floating-Point Types and Representations
22748 @subsection Floating-Point Types and Representations
22749 @cindex Floating-Point types
22750
22751 @noindent
22752 The set of predefined floating-point types is identical in HP Ada and GNAT.
22753 Furthermore the representation of these floating-point
22754 types is also identical. One important difference is that the default
22755 representation for HP Ada is @code{VAX_Float}, but the default representation
22756 for GNAT is IEEE.
22757
22758 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
22759 pragma @code{Float_Representation} as described in the HP Ada
22760 documentation.
22761 For example, the declarations:
22762
22763 @smallexample @c ada
22764 @cartouche
22765 type F_Float is digits 6;
22766 pragma Float_Representation (VAX_Float, F_Float);
22767 @end cartouche
22768 @end smallexample
22769
22770 @noindent
22771 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
22772 format.
22773 This set of declarations actually appears in @code{System.Aux_DEC},
22774 which contains
22775 the full set of additional floating-point declarations provided in
22776 the HP Ada version of package @code{System}.
22777 This and similar declarations may be accessed in a user program
22778 by using pragma @code{Extend_System}. The use of this
22779 pragma, and the related pragma @code{Long_Float} is described in further
22780 detail in the following section.
22781
22782 @node Pragmas Float_Representation and Long_Float
22783 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
22784
22785 @noindent
22786 HP Ada provides the pragma @code{Float_Representation}, which
22787 acts as a program library switch to allow control over
22788 the internal representation chosen for the predefined
22789 floating-point types declared in the package @code{Standard}.
22790 The format of this pragma is as follows:
22791
22792 @smallexample @c ada
22793 @cartouche
22794 pragma Float_Representation(VAX_Float | IEEE_Float);
22795 @end cartouche
22796 @end smallexample
22797
22798 @noindent
22799 This pragma controls the representation of floating-point
22800 types as follows:
22801
22802 @itemize @bullet
22803 @item
22804 @code{VAX_Float} specifies that floating-point
22805 types are represented by default with the VAX system hardware types
22806 @code{F-floating}, @code{D-floating}, @code{G-floating}.
22807 Note that the @code{H-floating}
22808 type was available only on VAX systems, and is not available
22809 in either HP Ada or GNAT.
22810
22811 @item
22812 @code{IEEE_Float} specifies that floating-point
22813 types are represented by default with the IEEE single and
22814 double floating-point types.
22815 @end itemize
22816
22817 @noindent
22818 GNAT provides an identical implementation of the pragma
22819 @code{Float_Representation}, except that it functions as a
22820 configuration pragma. Note that the
22821 notion of configuration pragma corresponds closely to the
22822 HP Ada notion of a program library switch.
22823
22824 When no pragma is used in GNAT, the default is @code{IEEE_Float},
22825 which is different
22826 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
22827 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
22828 advisable to change the format of numbers passed to standard library
22829 routines, and if necessary explicit type conversions may be needed.
22830
22831 The use of @code{IEEE_Float} is recommended in GNAT since it is more
22832 efficient, and (given that it conforms to an international standard)
22833 potentially more portable.
22834 The situation in which @code{VAX_Float} may be useful is in interfacing
22835 to existing code and data that expect the use of @code{VAX_Float}.
22836 In such a situation use the predefined @code{VAX_Float}
22837 types in package @code{System}, as extended by
22838 @code{Extend_System}. For example, use @code{System.F_Float}
22839 to specify the 32-bit @code{F-Float} format.
22840
22841 @noindent
22842 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
22843 to allow control over the internal representation chosen
22844 for the predefined type @code{Long_Float} and for floating-point
22845 type declarations with digits specified in the range 7 .. 15.
22846 The format of this pragma is as follows:
22847
22848 @smallexample @c ada
22849 @cartouche
22850 pragma Long_Float (D_FLOAT | G_FLOAT);
22851 @end cartouche
22852 @end smallexample
22853
22854 @node Fixed-Point Types and Representations
22855 @subsection Fixed-Point Types and Representations
22856
22857 @noindent
22858 On HP Ada for OpenVMS Alpha systems, rounding is
22859 away from zero for both positive and negative numbers.
22860 Therefore, @code{+0.5} rounds to @code{1},
22861 and @code{-0.5} rounds to @code{-1}.
22862
22863 On GNAT the results of operations
22864 on fixed-point types are in accordance with the Ada
22865 rules. In particular, results of operations on decimal
22866 fixed-point types are truncated.
22867
22868 @node Record and Array Component Alignment
22869 @subsection Record and Array Component Alignment
22870
22871 @noindent
22872 On HP Ada for OpenVMS Alpha, all non composite components
22873 are aligned on natural boundaries. For example, 1-byte
22874 components are aligned on byte boundaries, 2-byte
22875 components on 2-byte boundaries, 4-byte components on 4-byte
22876 byte boundaries, and so on. The OpenVMS Alpha hardware
22877 runs more efficiently with naturally aligned data.
22878
22879 On GNAT, alignment rules are compatible
22880 with HP Ada for OpenVMS Alpha.
22881
22882 @node Address Clauses
22883 @subsection Address Clauses
22884
22885 @noindent
22886 In HP Ada and GNAT, address clauses are supported for
22887 objects and imported subprograms.
22888 The predefined type @code{System.Address} is a private type
22889 in both compilers on Alpha OpenVMS, with the same representation
22890 (it is simply a machine pointer). Addition, subtraction, and comparison
22891 operations are available in the standard Ada package
22892 @code{System.Storage_Elements}, or in package @code{System}
22893 if it is extended to include @code{System.Aux_DEC} using a
22894 pragma @code{Extend_System} as previously described.
22895
22896 Note that code that @code{with}'s both this extended package @code{System}
22897 and the package @code{System.Storage_Elements} should not @code{use}
22898 both packages, or ambiguities will result. In general it is better
22899 not to mix these two sets of facilities. The Ada package was
22900 designed specifically to provide the kind of features that HP Ada
22901 adds directly to package @code{System}.
22902
22903 The type @code{System.Address} is a 64-bit integer type in GNAT for
22904 I64 OpenVMS.  For more information,
22905 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22906
22907 GNAT is compatible with HP Ada in its handling of address
22908 clauses, except for some limitations in
22909 the form of address clauses for composite objects with
22910 initialization. Such address clauses are easily replaced
22911 by the use of an explicitly-defined constant as described
22912 in the Ada Reference Manual (13.1(22)). For example, the sequence
22913 of declarations:
22914
22915 @smallexample @c ada
22916 @cartouche
22917 X, Y : Integer := Init_Func;
22918 Q : String (X .. Y) := "abc";
22919 ...
22920 for Q'Address use Compute_Address;
22921 @end cartouche
22922 @end smallexample
22923
22924 @noindent
22925 will be rejected by GNAT, since the address cannot be computed at the time
22926 that @code{Q} is declared. To achieve the intended effect, write instead:
22927
22928 @smallexample @c ada
22929 @group
22930 @cartouche
22931 X, Y : Integer := Init_Func;
22932 Q_Address : constant Address := Compute_Address;
22933 Q : String (X .. Y) := "abc";
22934 ...
22935 for Q'Address use Q_Address;
22936 @end cartouche
22937 @end group
22938 @end smallexample
22939
22940 @noindent
22941 which will be accepted by GNAT (and other Ada compilers), and is also
22942 compatible with Ada 83. A fuller description of the restrictions
22943 on address specifications is found in the @cite{GNAT Reference Manual}.
22944
22945 @node Other Representation Clauses
22946 @subsection Other Representation Clauses
22947
22948 @noindent
22949 GNAT implements in a compatible manner all the representation
22950 clauses supported by HP Ada. In addition, GNAT
22951 implements the representation clause forms that were introduced in Ada 95,
22952 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
22953
22954 @node The Package STANDARD
22955 @section The Package @code{STANDARD}
22956
22957 @noindent
22958 The package @code{STANDARD}, as implemented by HP Ada, is fully
22959 described in the @cite{Ada Reference Manual} and in the
22960 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
22961 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
22962
22963 In addition, HP Ada supports the Latin-1 character set in
22964 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
22965 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
22966 the type @code{WIDE_CHARACTER}.
22967
22968 The floating-point types supported by GNAT are those
22969 supported by HP Ada, but the defaults are different, and are controlled by
22970 pragmas. See @ref{Floating-Point Types and Representations}, for details.
22971
22972 @node The Package SYSTEM
22973 @section The Package @code{SYSTEM}
22974
22975 @noindent
22976 HP Ada provides a specific version of the package
22977 @code{SYSTEM} for each platform on which the language is implemented.
22978 For the complete specification of the package @code{SYSTEM}, see
22979 Appendix F of the @cite{HP Ada Language Reference Manual}.
22980
22981 On HP Ada, the package @code{SYSTEM} includes the following conversion
22982 functions:
22983 @itemize @bullet
22984 @item @code{TO_ADDRESS(INTEGER)}
22985
22986 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
22987
22988 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
22989
22990 @item @code{TO_INTEGER(ADDRESS)}
22991
22992 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
22993
22994 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
22995               functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
22996 @end itemize
22997
22998 @noindent
22999 By default, GNAT supplies a version of @code{SYSTEM} that matches
23000 the definition given in the @cite{Ada Reference Manual}.
23001 This
23002 is a subset of the HP system definitions, which is as
23003 close as possible to the original definitions. The only difference
23004 is that the definition of @code{SYSTEM_NAME} is different:
23005
23006 @smallexample @c ada
23007 @cartouche
23008 type Name is (SYSTEM_NAME_GNAT);
23009 System_Name : constant Name := SYSTEM_NAME_GNAT;
23010 @end cartouche
23011 @end smallexample
23012
23013 @noindent
23014 Also, GNAT adds the Ada declarations for
23015 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
23016
23017 However, the use of the following pragma causes GNAT
23018 to extend the definition of package @code{SYSTEM} so that it
23019 encompasses the full set of HP-specific extensions,
23020 including the functions listed above:
23021
23022 @smallexample @c ada
23023 @cartouche
23024 pragma Extend_System (Aux_DEC);
23025 @end cartouche
23026 @end smallexample
23027
23028 @noindent
23029 The pragma @code{Extend_System} is a configuration pragma that
23030 is most conveniently placed in the @file{gnat.adc} file. See the
23031 @cite{GNAT Reference Manual} for further details.
23032
23033 HP Ada does not allow the recompilation of the package
23034 @code{SYSTEM}. Instead HP Ada provides several pragmas
23035 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
23036 to modify values in the package @code{SYSTEM}.
23037 On OpenVMS Alpha systems, the pragma
23038 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
23039 its single argument.
23040
23041 GNAT does permit the recompilation of package @code{SYSTEM} using
23042 the special switch @option{-gnatg}, and this switch can be used if
23043 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
23044 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
23045 or @code{MEMORY_SIZE} by any other means.
23046
23047 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
23048 enumeration literal @code{SYSTEM_NAME_GNAT}.
23049
23050 The definitions provided by the use of
23051
23052 @smallexample @c ada
23053 pragma Extend_System (AUX_Dec);
23054 @end smallexample
23055
23056 @noindent
23057 are virtually identical to those provided by the HP Ada 83 package
23058 @code{SYSTEM}. One important difference is that the name of the
23059 @code{TO_ADDRESS}
23060 function for type @code{UNSIGNED_LONGWORD} is changed to
23061 @code{TO_ADDRESS_LONG}.
23062 See the @cite{GNAT Reference Manual} for a discussion of why this change was
23063 necessary.
23064
23065 @noindent
23066 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
23067 is in fact
23068 an extension to Ada 83 not strictly compatible with the reference manual.
23069 GNAT, in order to be exactly compatible with the standard,
23070 does not provide this capability. In HP Ada 83, the
23071 point of this definition is to deal with a call like:
23072
23073 @smallexample @c ada
23074 TO_ADDRESS (16#12777#);
23075 @end smallexample
23076
23077 @noindent
23078 Normally, according to Ada 83 semantics, one would expect this to be
23079 ambiguous, since it matches both the @code{INTEGER} and
23080 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
23081 However, in HP Ada 83, there is no ambiguity, since the
23082 definition using @i{universal_integer} takes precedence.
23083
23084 In GNAT, since the version with @i{universal_integer} cannot be supplied,
23085 it is
23086 not possible to be 100% compatible. Since there are many programs using
23087 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
23088 GNAT was
23089 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
23090 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
23091
23092 @smallexample @c ada
23093 function To_Address (X : Integer) return Address;
23094 pragma Pure_Function (To_Address);
23095
23096 function To_Address_Long (X : Unsigned_Longword) return Address;
23097 pragma Pure_Function (To_Address_Long);
23098 @end smallexample
23099
23100 @noindent
23101 This means that programs using @code{TO_ADDRESS} for
23102 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
23103
23104 @node Tasking and Task-Related Features
23105 @section Tasking and Task-Related Features
23106
23107 @noindent
23108 This section compares the treatment of tasking in GNAT
23109 and in HP Ada for OpenVMS Alpha.
23110 The GNAT description applies to both Alpha and I64 OpenVMS.
23111 For detailed information on tasking in
23112 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
23113 relevant run-time reference manual.
23114
23115 @menu
23116 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
23117 * Assigning Task IDs::
23118 * Task IDs and Delays::
23119 * Task-Related Pragmas::
23120 * Scheduling and Task Priority::
23121 * The Task Stack::
23122 * External Interrupts::
23123 @end menu
23124
23125 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
23126 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
23127
23128 @noindent
23129 On OpenVMS Alpha systems, each Ada task (except a passive
23130 task) is implemented as a single stream of execution
23131 that is created and managed by the kernel. On these
23132 systems, HP Ada tasking support is based on DECthreads,
23133 an implementation of the POSIX standard for threads.
23134
23135 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
23136 code that calls DECthreads routines can be used together.
23137 The interaction between Ada tasks and DECthreads routines
23138 can have some benefits. For example when on OpenVMS Alpha,
23139 HP Ada can call C code that is already threaded.
23140
23141 GNAT uses the facilities of DECthreads,
23142 and Ada tasks are mapped to threads.
23143
23144 @node Assigning Task IDs
23145 @subsection Assigning Task IDs
23146
23147 @noindent
23148 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
23149 the environment task that executes the main program. On
23150 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
23151 that have been created but are not yet activated.
23152
23153 On OpenVMS Alpha systems, task IDs are assigned at
23154 activation. On GNAT systems, task IDs are also assigned at
23155 task creation but do not have the same form or values as
23156 task ID values in HP Ada. There is no null task, and the
23157 environment task does not have a specific task ID value.
23158
23159 @node Task IDs and Delays
23160 @subsection Task IDs and Delays
23161
23162 @noindent
23163 On OpenVMS Alpha systems, tasking delays are implemented
23164 using Timer System Services. The Task ID is used for the
23165 identification of the timer request (the @code{REQIDT} parameter).
23166 If Timers are used in the application take care not to use
23167 @code{0} for the identification, because cancelling such a timer
23168 will cancel all timers and may lead to unpredictable results.
23169
23170 @node Task-Related Pragmas
23171 @subsection Task-Related Pragmas
23172
23173 @noindent
23174 Ada supplies the pragma @code{TASK_STORAGE}, which allows
23175 specification of the size of the guard area for a task
23176 stack. (The guard area forms an area of memory that has no
23177 read or write access and thus helps in the detection of
23178 stack overflow.) On OpenVMS Alpha systems, if the pragma
23179 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
23180 area is created. In the absence of a pragma @code{TASK_STORAGE},
23181 a default guard area is created.
23182
23183 GNAT supplies the following task-related pragmas:
23184
23185 @itemize @bullet
23186 @item  @code{TASK_INFO}
23187
23188               This pragma appears within a task definition and
23189               applies to the task in which it appears. The argument
23190               must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
23191
23192 @item  @code{TASK_STORAGE}
23193
23194               GNAT implements pragma @code{TASK_STORAGE} in the same way as
23195               HP Ada.
23196               Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
23197               @code{SUPPRESS}, and @code{VOLATILE}.
23198 @end itemize
23199 @node Scheduling and Task Priority
23200 @subsection Scheduling and Task Priority
23201
23202 @noindent
23203 HP Ada implements the Ada language requirement that
23204 when two tasks are eligible for execution and they have
23205 different priorities, the lower priority task does not
23206 execute while the higher priority task is waiting. The HP
23207 Ada Run-Time Library keeps a task running until either the
23208 task is suspended or a higher priority task becomes ready.
23209
23210 On OpenVMS Alpha systems, the default strategy is round-
23211 robin with preemption. Tasks of equal priority take turns
23212 at the processor. A task is run for a certain period of
23213 time and then placed at the tail of the ready queue for
23214 its priority level.
23215
23216 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
23217 which can be used to enable or disable round-robin
23218 scheduling of tasks with the same priority.
23219 See the relevant HP Ada run-time reference manual for
23220 information on using the pragmas to control HP Ada task
23221 scheduling.
23222
23223 GNAT follows the scheduling rules of Annex D (Real-Time
23224 Annex) of the @cite{Ada Reference Manual}. In general, this
23225 scheduling strategy is fully compatible with HP Ada
23226 although it provides some additional constraints (as
23227 fully documented in Annex D).
23228 GNAT implements time slicing control in a manner compatible with
23229 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
23230 are identical to the HP Ada 83 pragma of the same name.
23231 Note that it is not possible to mix GNAT tasking and
23232 HP Ada 83 tasking in the same program, since the two run-time
23233 libraries are not compatible.
23234
23235 @node The Task Stack
23236 @subsection The Task Stack
23237
23238 @noindent
23239 In HP Ada, a task stack is allocated each time a
23240 non-passive task is activated. As soon as the task is
23241 terminated, the storage for the task stack is deallocated.
23242 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
23243 a default stack size is used. Also, regardless of the size
23244 specified, some additional space is allocated for task
23245 management purposes. On OpenVMS Alpha systems, at least
23246 one page is allocated.
23247
23248 GNAT handles task stacks in a similar manner. In accordance with
23249 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
23250 an alternative method for controlling the task stack size.
23251 The specification of the attribute @code{T'STORAGE_SIZE} is also
23252 supported in a manner compatible with HP Ada.
23253
23254 @node External Interrupts
23255 @subsection External Interrupts
23256
23257 @noindent
23258 On HP Ada, external interrupts can be associated with task entries.
23259 GNAT is compatible with HP Ada in its handling of external interrupts.
23260
23261 @node Pragmas and Pragma-Related Features
23262 @section Pragmas and Pragma-Related Features
23263
23264 @noindent
23265 Both HP Ada and GNAT supply all language-defined pragmas
23266 as specified by the Ada 83 standard. GNAT also supplies all
23267 language-defined pragmas introduced by Ada 95 and Ada 2005.
23268 In addition, GNAT implements the implementation-defined pragmas
23269 from HP Ada 83.
23270
23271 @itemize @bullet
23272 @item  @code{AST_ENTRY}
23273
23274 @item  @code{COMMON_OBJECT}
23275
23276 @item  @code{COMPONENT_ALIGNMENT}
23277
23278 @item  @code{EXPORT_EXCEPTION}
23279
23280 @item  @code{EXPORT_FUNCTION}
23281
23282 @item  @code{EXPORT_OBJECT}
23283
23284 @item  @code{EXPORT_PROCEDURE}
23285
23286 @item  @code{EXPORT_VALUED_PROCEDURE}
23287
23288 @item  @code{FLOAT_REPRESENTATION}
23289
23290 @item  @code{IDENT}
23291
23292 @item  @code{IMPORT_EXCEPTION}
23293
23294 @item  @code{IMPORT_FUNCTION}
23295
23296 @item  @code{IMPORT_OBJECT}
23297
23298 @item  @code{IMPORT_PROCEDURE}
23299
23300 @item  @code{IMPORT_VALUED_PROCEDURE}
23301
23302 @item  @code{INLINE_GENERIC}
23303
23304 @item  @code{INTERFACE_NAME}
23305
23306 @item  @code{LONG_FLOAT}
23307
23308 @item  @code{MAIN_STORAGE}
23309
23310 @item  @code{PASSIVE}
23311
23312 @item  @code{PSET_OBJECT}
23313
23314 @item  @code{SHARE_GENERIC}
23315
23316 @item  @code{SUPPRESS_ALL}
23317
23318 @item  @code{TASK_STORAGE}
23319
23320 @item  @code{TIME_SLICE}
23321
23322 @item  @code{TITLE}
23323 @end itemize
23324
23325 @noindent
23326 These pragmas are all fully implemented, with the exception of @code{TITLE},
23327 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
23328 recognized, but which have no
23329 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
23330 use of Ada protected objects. In GNAT, all generics are inlined.
23331
23332 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
23333 a separate subprogram specification which must appear before the
23334 subprogram body.
23335
23336 GNAT also supplies a number of implementation-defined pragmas as follows:
23337 @itemize @bullet
23338 @item  @code{ABORT_DEFER}
23339
23340 @item  @code{ADA_83}
23341
23342 @item  @code{ADA_95}
23343
23344 @item  @code{ADA_05}
23345
23346 @item  @code{ANNOTATE}
23347
23348 @item  @code{ASSERT}
23349
23350 @item  @code{C_PASS_BY_COPY}
23351
23352 @item  @code{CPP_CLASS}
23353
23354 @item  @code{CPP_CONSTRUCTOR}
23355
23356 @item  @code{CPP_DESTRUCTOR}
23357
23358 @item  @code{DEBUG}
23359
23360 @item  @code{EXTEND_SYSTEM}
23361
23362 @item  @code{LINKER_ALIAS}
23363
23364 @item  @code{LINKER_SECTION}
23365
23366 @item  @code{MACHINE_ATTRIBUTE}
23367
23368 @item  @code{NO_RETURN}
23369
23370 @item  @code{PURE_FUNCTION}
23371
23372 @item  @code{SOURCE_FILE_NAME}
23373
23374 @item  @code{SOURCE_REFERENCE}
23375
23376 @item  @code{TASK_INFO}
23377
23378 @item  @code{UNCHECKED_UNION}
23379
23380 @item  @code{UNIMPLEMENTED_UNIT}
23381
23382 @item  @code{UNIVERSAL_DATA}
23383
23384 @item  @code{UNSUPPRESS}
23385
23386 @item  @code{WARNINGS}
23387
23388 @item  @code{WEAK_EXTERNAL}
23389 @end itemize
23390
23391 @noindent
23392 For full details on these GNAT implementation-defined pragmas, see
23393 the GNAT Reference Manual.
23394
23395 @menu
23396 * Restrictions on the Pragma INLINE::
23397 * Restrictions on the Pragma INTERFACE::
23398 * Restrictions on the Pragma SYSTEM_NAME::
23399 @end menu
23400
23401 @node Restrictions on the Pragma INLINE
23402 @subsection Restrictions on Pragma @code{INLINE}
23403
23404 @noindent
23405 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
23406 @itemize @bullet
23407 @item  Parameters cannot have a task type.
23408
23409 @item  Function results cannot be task types, unconstrained
23410 array types, or unconstrained types with discriminants.
23411
23412 @item  Bodies cannot declare the following:
23413 @itemize @bullet
23414 @item  Subprogram body or stub (imported subprogram is allowed)
23415
23416 @item  Tasks
23417
23418 @item  Generic declarations
23419
23420 @item  Instantiations
23421
23422 @item  Exceptions
23423
23424 @item  Access types (types derived from access types allowed)
23425
23426 @item  Array or record types
23427
23428 @item  Dependent tasks
23429
23430 @item  Direct recursive calls of subprogram or containing
23431 subprogram, directly or via a renaming
23432
23433 @end itemize
23434 @end itemize
23435
23436 @noindent
23437 In GNAT, the only restriction on pragma @code{INLINE} is that the
23438 body must occur before the call if both are in the same
23439 unit, and the size must be appropriately small. There are
23440 no other specific restrictions which cause subprograms to
23441 be incapable of being inlined.
23442
23443 @node  Restrictions on the Pragma INTERFACE
23444 @subsection  Restrictions on Pragma @code{INTERFACE}
23445
23446 @noindent
23447 The following restrictions on pragma @code{INTERFACE}
23448 are enforced by both HP Ada and GNAT:
23449 @itemize @bullet
23450 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
23451 Default is the default on OpenVMS Alpha systems.
23452
23453 @item  Parameter passing: Language specifies default
23454 mechanisms but can be overridden with an @code{EXPORT} pragma.
23455
23456 @itemize @bullet
23457 @item  Ada: Use internal Ada rules.
23458
23459 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
23460 record or task type. Result cannot be a string, an
23461 array, or a record.
23462
23463 @item  Fortran: Parameters cannot have a task type. Result cannot
23464 be a string, an array, or a record.
23465 @end itemize
23466 @end itemize
23467
23468 @noindent
23469 GNAT is entirely upwards compatible with HP Ada, and in addition allows
23470 record parameters for all languages.
23471
23472 @node  Restrictions on the Pragma SYSTEM_NAME
23473 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
23474
23475 @noindent
23476 For HP Ada for OpenVMS Alpha, the enumeration literal
23477 for the type @code{NAME} is @code{OPENVMS_AXP}.
23478 In GNAT, the enumeration
23479 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
23480
23481 @node  Library of Predefined Units
23482 @section  Library of Predefined Units
23483
23484 @noindent
23485 A library of predefined units is provided as part of the
23486 HP Ada and GNAT implementations. HP Ada does not provide
23487 the package @code{MACHINE_CODE} but instead recommends importing
23488 assembler code.
23489
23490 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
23491 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
23492 version.
23493 The HP Ada Predefined Library units are modified to remove post-Ada 83
23494 incompatibilities and to make them interoperable with GNAT
23495 (@pxref{Changes to DECLIB}, for details).
23496 The units are located in the @file{DECLIB} directory.
23497
23498 The GNAT RTL is contained in
23499 the @file{ADALIB} directory, and
23500 the default search path is set up to find @code{DECLIB} units in preference
23501 to @code{ADALIB} units with the same name (@code{TEXT_IO},
23502 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
23503
23504 @menu
23505 * Changes to DECLIB::
23506 @end menu
23507
23508 @node Changes to DECLIB
23509 @subsection Changes to @code{DECLIB}
23510
23511 @noindent
23512 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
23513 compatibility are minor and include the following:
23514
23515 @itemize @bullet
23516 @item  Adjusting the location of pragmas and record representation
23517 clauses to obey Ada 95 (and thus Ada 2005) rules
23518
23519 @item  Adding the proper notation to generic formal parameters
23520 that take unconstrained types in instantiation
23521
23522 @item  Adding pragma @code{ELABORATE_BODY} to package specifications
23523 that have package bodies not otherwise allowed
23524
23525 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
23526 ``@code{PROTECTD}''.
23527 Currently these are found only in the @code{STARLET} package spec.
23528
23529 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
23530 where the address size is constrained to 32 bits.
23531 @end itemize
23532
23533 @noindent
23534 None of the above changes is visible to users.
23535
23536 @node Bindings
23537 @section Bindings
23538
23539 @noindent
23540 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
23541 @itemize @bullet
23542
23543 @item  Command Language Interpreter (CLI interface)
23544
23545 @item  DECtalk Run-Time Library (DTK interface)
23546
23547 @item  Librarian utility routines (LBR interface)
23548
23549 @item  General Purpose Run-Time Library (LIB interface)
23550
23551 @item  Math Run-Time Library (MTH interface)
23552
23553 @item  National Character Set Run-Time Library (NCS interface)
23554
23555 @item  Compiled Code Support Run-Time Library (OTS interface)
23556
23557 @item  Parallel Processing Run-Time Library (PPL interface)
23558
23559 @item  Screen Management Run-Time Library (SMG interface)
23560
23561 @item  Sort Run-Time Library (SOR interface)
23562
23563 @item  String Run-Time Library (STR interface)
23564
23565 @item STARLET System Library
23566 @findex Starlet
23567
23568 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
23569
23570 @item  X Windows Toolkit (XT interface)
23571
23572 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
23573 @end itemize
23574
23575 @noindent
23576 GNAT provides implementations of these HP bindings in the @code{DECLIB}
23577 directory, on both the Alpha and I64 OpenVMS platforms.
23578
23579 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
23580 in the
23581 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
23582 A pragma @code{Linker_Options} has been added to packages @code{Xm},
23583 @code{Xt}, and @code{X_Lib}
23584 causing the default X/Motif sharable image libraries to be linked in. This
23585 is done via options files named @file{xm.opt}, @file{xt.opt}, and
23586 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
23587
23588 It may be necessary to edit these options files to update or correct the
23589 library names if, for example, the newer X/Motif bindings from
23590 @file{ADA$EXAMPLES}
23591 had been (previous to installing GNAT) copied and renamed to supersede the
23592 default @file{ADA$PREDEFINED} versions.
23593
23594 @menu
23595 * Shared Libraries and Options Files::
23596 * Interfaces to C::
23597 @end menu
23598
23599 @node Shared Libraries and Options Files
23600 @subsection Shared Libraries and Options Files
23601
23602 @noindent
23603 When using the HP Ada
23604 predefined X and Motif bindings, the linking with their sharable images is
23605 done automatically by @command{GNAT LINK}.
23606 When using other X and Motif bindings, you need
23607 to add the corresponding sharable images to the command line for
23608 @code{GNAT LINK}. When linking with shared libraries, or with
23609 @file{.OPT} files, you must
23610 also add them to the command line for @command{GNAT LINK}.
23611
23612 A shared library to be used with GNAT is built in the same way as other
23613 libraries under VMS. The VMS Link command can be used in standard fashion.
23614
23615 @node Interfaces to C
23616 @subsection Interfaces to C
23617
23618 @noindent
23619 HP Ada
23620 provides the following Ada types and operations:
23621
23622 @itemize @bullet
23623 @item C types package (@code{C_TYPES})
23624
23625 @item C strings (@code{C_TYPES.NULL_TERMINATED})
23626
23627 @item Other_types (@code{SHORT_INT})
23628 @end itemize
23629
23630 @noindent
23631 Interfacing to C with GNAT, you can use the above approach
23632 described for HP Ada or the facilities of Annex B of
23633 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
23634 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
23635 information, see the section ``Interfacing to C'' in the
23636 @cite{GNAT Reference Manual}.
23637
23638 The @option{-gnatF} qualifier forces default and explicit
23639 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
23640 to be uppercased for compatibility with the default behavior
23641 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
23642
23643 @node Main Program Definition
23644 @section Main Program Definition
23645
23646 @noindent
23647 The following section discusses differences in the
23648 definition of main programs on HP Ada and GNAT.
23649 On HP Ada, main programs are defined to meet the
23650 following conditions:
23651 @itemize @bullet
23652 @item  Procedure with no formal parameters (returns @code{0} upon
23653        normal completion)
23654
23655 @item  Procedure with no formal parameters (returns @code{42} when
23656        an unhandled exception is raised)
23657
23658 @item  Function with no formal parameters whose returned value
23659        is of a discrete type
23660
23661 @item  Procedure with one @code{out} formal of a discrete type for
23662        which a specification of pragma @code{EXPORT_VALUED_PROCEDURE}
23663        is given.
23664
23665 @end itemize
23666
23667 @noindent
23668 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
23669 a main function or main procedure returns a discrete
23670 value whose size is less than 64 bits (32 on VAX systems),
23671 the value is zero- or sign-extended as appropriate.
23672 On GNAT, main programs are defined as follows:
23673 @itemize @bullet
23674 @item  Must be a non-generic, parameterless subprogram that
23675 is either a procedure or function returning an Ada
23676 @code{STANDARD.INTEGER} (the predefined type)
23677
23678 @item  Cannot be a generic subprogram or an instantiation of a
23679 generic subprogram
23680 @end itemize
23681
23682 @node Implementation-Defined Attributes
23683 @section Implementation-Defined Attributes
23684
23685 @noindent
23686 GNAT provides all HP Ada implementation-defined
23687 attributes.
23688
23689 @node Compiler and Run-Time Interfacing
23690 @section Compiler and Run-Time Interfacing
23691
23692 @noindent
23693 HP Ada provides the following qualifiers to pass options to the linker
23694 (ACS LINK):
23695 @itemize @bullet
23696 @item  @option{/WAIT} and @option{/SUBMIT}
23697
23698 @item  @option{/COMMAND}
23699
23700 @item  @option{/[NO]MAP}
23701
23702 @item  @option{/OUTPUT=@i{file-spec}}
23703
23704 @item  @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
23705 @end itemize
23706
23707 @noindent
23708 To pass options to the linker, GNAT provides the following
23709 switches:
23710
23711 @itemize @bullet
23712 @item   @option{/EXECUTABLE=@i{exec-name}}
23713
23714 @item   @option{/VERBOSE}
23715
23716 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
23717 @end itemize
23718
23719 @noindent
23720 For more information on these switches, see
23721 @ref{Switches for gnatlink}.
23722 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
23723 to control optimization. HP Ada also supplies the
23724 following pragmas:
23725 @itemize @bullet
23726 @item  @code{OPTIMIZE}
23727
23728 @item  @code{INLINE}
23729
23730 @item  @code{INLINE_GENERIC}
23731
23732 @item  @code{SUPPRESS_ALL}
23733
23734 @item  @code{PASSIVE}
23735 @end itemize
23736
23737 @noindent
23738 In GNAT, optimization is controlled strictly by command
23739 line parameters, as described in the corresponding section of this guide.
23740 The HP pragmas for control of optimization are
23741 recognized but ignored.
23742
23743 Note that in GNAT, the default is optimization off, whereas in HP Ada
23744 the default is that optimization is turned on.
23745
23746 @node Program Compilation and Library Management
23747 @section Program Compilation and Library Management
23748
23749 @noindent
23750 HP Ada and GNAT provide a comparable set of commands to
23751 build programs. HP Ada also provides a program library,
23752 which is a concept that does not exist on GNAT. Instead,
23753 GNAT provides directories of sources that are compiled as
23754 needed.
23755
23756 The following table summarizes
23757 the HP Ada commands and provides
23758 equivalent GNAT commands. In this table, some GNAT
23759 equivalents reflect the fact that GNAT does not use the
23760 concept of a program library. Instead, it uses a model
23761 in which collections of source and object files are used
23762 in a manner consistent with other languages like C and
23763 Fortran. Therefore, standard system file commands are used
23764 to manipulate these elements. Those GNAT commands are marked with
23765 an asterisk.
23766 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
23767
23768 @need 1500
23769 @multitable @columnfractions .35 .65
23770
23771 @item @emph{HP Ada Command}
23772 @tab @emph{GNAT Equivalent / Description}
23773
23774 @item @command{ADA}
23775 @tab @command{GNAT COMPILE}@*
23776 Invokes the compiler to compile one or more Ada source files.
23777
23778 @item @command{ACS ATTACH}@*
23779 @tab [No equivalent]@*
23780 Switches control of terminal from current process running the program
23781 library manager.
23782
23783 @item @command{ACS CHECK}
23784 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
23785 Forms the execution closure of one
23786 or more compiled units and checks completeness and currency.
23787
23788 @item @command{ACS COMPILE}
23789 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23790 Forms the execution closure of one or
23791 more specified units, checks completeness and currency,
23792 identifies units that have revised source files, compiles same,
23793 and recompiles units that are or will become obsolete.
23794 Also completes incomplete generic instantiations.
23795
23796 @item @command{ACS COPY FOREIGN}
23797 @tab Copy (*)@*
23798 Copies a foreign object file into the program library as a
23799 library unit body.
23800
23801 @item @command{ACS COPY UNIT}
23802 @tab Copy (*)@*
23803 Copies a compiled unit from one program library to another.
23804
23805 @item @command{ACS CREATE LIBRARY}
23806 @tab Create /directory (*)@*
23807 Creates a program library.
23808
23809 @item @command{ACS CREATE SUBLIBRARY}
23810 @tab Create /directory (*)@*
23811 Creates a program sublibrary.
23812
23813 @item @command{ACS DELETE LIBRARY}
23814 @tab @*
23815 Deletes a program library and its contents.
23816
23817 @item @command{ACS DELETE SUBLIBRARY}
23818 @tab @*
23819 Deletes a program sublibrary and its contents.
23820
23821 @item @command{ACS DELETE UNIT}
23822 @tab Delete file (*)@*
23823 On OpenVMS systems, deletes one or more compiled units from
23824 the current program library.
23825
23826 @item @command{ACS DIRECTORY}
23827 @tab Directory (*)@*
23828 On OpenVMS systems, lists units contained in the current
23829 program library.
23830
23831 @item @command{ACS ENTER FOREIGN}
23832 @tab Copy (*)@*
23833 Allows the import of a foreign body as an Ada library
23834 specification and enters a reference to a pointer.
23835
23836 @item @command{ACS ENTER UNIT}
23837 @tab Copy (*)@*
23838 Enters a reference (pointer) from the current program library to
23839 a unit compiled into another program library.
23840
23841 @item @command{ACS EXIT}
23842 @tab [No equivalent]@*
23843 Exits from the program library manager.
23844
23845 @item @command{ACS EXPORT}
23846 @tab Copy (*)@*
23847 Creates an object file that contains system-specific object code
23848 for one or more units. With GNAT, object files can simply be copied
23849 into the desired directory.
23850
23851 @item @command{ACS EXTRACT SOURCE}
23852 @tab Copy (*)@*
23853 Allows access to the copied source file for each Ada compilation unit
23854
23855 @item @command{ACS HELP}
23856 @tab @command{HELP GNAT}@*
23857 Provides online help.
23858
23859 @item @command{ACS LINK}
23860 @tab @command{GNAT LINK}@*
23861 Links an object file containing Ada units into an executable file.
23862
23863 @item @command{ACS LOAD}
23864 @tab Copy (*)@*
23865 Loads (partially compiles) Ada units into the program library.
23866 Allows loading a program from a collection of files into a library
23867 without knowing the relationship among units.
23868
23869 @item @command{ACS MERGE}
23870 @tab Copy (*)@*
23871 Merges into the current program library, one or more units from
23872 another library where they were modified.
23873
23874 @item @command{ACS RECOMPILE}
23875 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23876 Recompiles from   external or copied source files any obsolete
23877 unit in the closure. Also, completes any incomplete generic
23878 instantiations.
23879
23880 @item @command{ACS REENTER}
23881 @tab @command{GNAT MAKE}@*
23882 Reenters current references to units compiled after last entered
23883 with the @command{ACS ENTER UNIT} command.
23884
23885 @item @command{ACS SET LIBRARY}
23886 @tab Set default (*)@*
23887 Defines a program library to be the compilation context as well
23888 as the target library for compiler output and commands in general.
23889
23890 @item @command{ACS SET PRAGMA}
23891 @tab Edit @file{gnat.adc} (*)@*
23892 Redefines specified  values of the library characteristics
23893 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
23894 and @code{Float_Representation}.
23895
23896 @item @command{ACS SET SOURCE}
23897 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
23898 Defines the source file search list for the @command{ACS COMPILE} command.
23899
23900 @item @command{ACS SHOW LIBRARY}
23901 @tab Directory (*)@*
23902 Lists information about one or more program libraries.
23903
23904 @item @command{ACS SHOW PROGRAM}
23905 @tab [No equivalent]@*
23906 Lists information about the execution closure of one or
23907 more units in the program library.
23908
23909 @item @command{ACS SHOW SOURCE}
23910 @tab Show logical @code{ADA_INCLUDE_PATH}@*
23911 Shows the source file search used when compiling units.
23912
23913 @item @command{ACS SHOW VERSION}
23914 @tab Compile with @option{VERBOSE} option
23915 Displays the version number of the compiler and program library
23916 manager used.
23917
23918 @item @command{ACS SPAWN}
23919 @tab [No equivalent]@*
23920 Creates a subprocess of the current process (same as @command{DCL SPAWN}
23921 command).
23922
23923 @item @command{ACS VERIFY}
23924 @tab [No equivalent]@*
23925 Performs a series of consistency checks on a program library to
23926 determine whether the library structure and library files are in
23927 valid form.
23928 @end multitable
23929
23930 @noindent
23931
23932 @node Input-Output
23933 @section Input-Output
23934
23935 @noindent
23936 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
23937 Management Services (RMS) to perform operations on
23938 external files.
23939
23940 @noindent
23941 HP Ada and GNAT predefine an identical set of input-
23942 output packages. To make the use of the
23943 generic @code{TEXT_IO} operations more convenient, HP Ada
23944 provides predefined library packages that instantiate the
23945 integer and floating-point operations for the predefined
23946 integer and floating-point types as shown in the following table.
23947
23948 @multitable @columnfractions .45 .55
23949 @item @emph{Package Name} @tab Instantiation
23950
23951 @item @code{INTEGER_TEXT_IO}
23952 @tab @code{INTEGER_IO(INTEGER)}
23953
23954 @item @code{SHORT_INTEGER_TEXT_IO}
23955 @tab @code{INTEGER_IO(SHORT_INTEGER)}
23956
23957 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
23958 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
23959
23960 @item @code{FLOAT_TEXT_IO}
23961 @tab @code{FLOAT_IO(FLOAT)}
23962
23963 @item @code{LONG_FLOAT_TEXT_IO}
23964 @tab @code{FLOAT_IO(LONG_FLOAT)}
23965 @end multitable
23966
23967 @noindent
23968 The HP Ada predefined packages and their operations
23969 are implemented using OpenVMS Alpha files and input-output
23970 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
23971 Familiarity with the following is recommended:
23972 @itemize @bullet
23973 @item  RMS file organizations and access methods
23974
23975 @item  OpenVMS file specifications and directories
23976
23977 @item  OpenVMS File Definition Language (FDL)
23978 @end itemize
23979
23980 @noindent
23981 GNAT provides I/O facilities that are completely
23982 compatible with HP Ada. The distribution includes the
23983 standard HP Ada versions of all I/O packages, operating
23984 in a manner compatible with HP Ada. In particular, the
23985 following packages are by default the HP Ada (Ada 83)
23986 versions of these packages rather than the renamings
23987 suggested in Annex J of the Ada Reference Manual:
23988 @itemize @bullet
23989 @item  @code{TEXT_IO}
23990
23991 @item  @code{SEQUENTIAL_IO}
23992
23993 @item  @code{DIRECT_IO}
23994 @end itemize
23995
23996 @noindent
23997 The use of the standard child package syntax (for
23998 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
23999 packages.
24000 GNAT provides HP-compatible predefined instantiations
24001 of the @code{TEXT_IO} packages, and also
24002 provides the standard predefined instantiations required
24003 by the @cite{Ada Reference Manual}.
24004
24005 For further information on how GNAT interfaces to the file
24006 system or how I/O is implemented in programs written in
24007 mixed languages, see the chapter ``Implementation of the
24008 Standard I/O'' in the @cite{GNAT Reference Manual}.
24009 This chapter covers the following:
24010 @itemize @bullet
24011 @item  Standard I/O packages
24012
24013 @item  @code{FORM} strings
24014
24015 @item  @code{ADA.DIRECT_IO}
24016
24017 @item  @code{ADA.SEQUENTIAL_IO}
24018
24019 @item  @code{ADA.TEXT_IO}
24020
24021 @item  Stream pointer positioning
24022
24023 @item  Reading and writing non-regular files
24024
24025 @item  @code{GET_IMMEDIATE}
24026
24027 @item  Treating @code{TEXT_IO} files as streams
24028
24029 @item  Shared files
24030
24031 @item  Open modes
24032 @end itemize
24033
24034 @node Implementation Limits
24035 @section Implementation Limits
24036
24037 @noindent
24038 The following table lists implementation limits for HP Ada
24039 and GNAT systems.
24040 @multitable @columnfractions .60 .20 .20
24041 @sp 1
24042 @item  @emph{Compilation Parameter}
24043 @tab   @emph{HP Ada}
24044 @tab   @emph{GNAT}
24045 @sp 1
24046
24047 @item  In a subprogram or entry  declaration, maximum number of
24048        formal parameters that are of an unconstrained record type
24049 @tab   32
24050 @tab   No set limit
24051 @sp 1
24052
24053 @item  Maximum identifier length (number of characters)
24054 @tab   255
24055 @tab   32766
24056 @sp 1
24057
24058 @item  Maximum number of characters in a source line
24059 @tab   255
24060 @tab   32766
24061 @sp 1
24062
24063 @item  Maximum collection size   (number of bytes)
24064 @tab   2**31-1
24065 @tab   2**31-1
24066 @sp 1
24067
24068 @item  Maximum number of discriminants for a record type
24069 @tab   245
24070 @tab   No set limit
24071 @sp 1
24072
24073 @item  Maximum number of formal parameters in an entry or
24074        subprogram declaration
24075 @tab   246
24076 @tab    No set limit
24077 @sp 1
24078
24079 @item  Maximum number of dimensions in an array type
24080 @tab   255
24081 @tab   No set limit
24082 @sp 1
24083
24084 @item  Maximum number of library  units and subunits in a compilation.
24085 @tab   4095
24086 @tab   No set limit
24087 @sp 1
24088
24089 @item  Maximum number of library units and subunits in an execution.
24090 @tab   16383
24091 @tab   No set limit
24092 @sp 1
24093
24094 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
24095        or @code{PSECT_OBJECT}
24096 @tab   32757
24097 @tab   No set limit
24098 @sp 1
24099
24100 @item  Maximum number of enumeration literals in an enumeration type
24101        definition
24102 @tab   65535
24103 @tab   No set limit
24104 @sp 1
24105
24106 @item  Maximum number of lines in a source file
24107 @tab   65534
24108 @tab   No set limit
24109 @sp 1
24110
24111 @item  Maximum number of bits in any object
24112 @tab   2**31-1
24113 @tab   2**31-1
24114 @sp 1
24115
24116 @item  Maximum size of the static portion of a stack frame (approximate)
24117 @tab   2**31-1
24118 @tab   2**31-1
24119 @end multitable
24120
24121 @node Tools and Utilities
24122 @section Tools and Utilities
24123
24124 @noindent
24125 The following table lists some of the OpenVMS development tools
24126 available for HP Ada, and the corresponding tools for
24127 use with @value{EDITION} on Alpha and I64 platforms.
24128 Aside from the debugger, all the OpenVMS tools identified are part
24129 of the DECset package.
24130
24131 @iftex
24132 @c Specify table in TeX since Texinfo does a poor job
24133 @tex
24134 \smallskip
24135 \smallskip
24136 \settabs\+Language-Sensitive Editor\quad
24137    &Product with HP Ada\quad
24138    &\cr
24139 \+\it Tool
24140    &\it Product with HP Ada
24141    & \it Product with GNAT Pro\cr
24142 \smallskip
24143 \+Code Management System
24144    &HP CMS
24145    & HP CMS\cr
24146 \smallskip
24147 \+Language-Sensitive Editor
24148    &HP LSE
24149    & emacs or HP LSE (Alpha)\cr
24150 \+
24151    &
24152    & HP LSE (I64)\cr
24153 \smallskip
24154 \+Debugger
24155    &OpenVMS Debug
24156    & gdb (Alpha),\cr
24157 \+
24158    &
24159    & OpenVMS Debug (I64)\cr
24160 \smallskip
24161 \+Source Code Analyzer /
24162    &HP SCA
24163    & GNAT XREF\cr
24164 \+Cross Referencer
24165    &
24166    &\cr
24167 \smallskip
24168 \+Test Manager
24169    &HP Digital Test
24170    & HP DTM\cr
24171 \+
24172    &Manager (DTM)
24173    &\cr
24174 \smallskip
24175 \+Performance and
24176    & HP PCA
24177    & HP PCA\cr
24178 \+Coverage Analyzer
24179    &
24180    &\cr
24181 \smallskip
24182 \+Module Management
24183    & HP MMS
24184    & Not applicable\cr
24185 \+ System
24186    &
24187    &\cr
24188 \smallskip
24189 \smallskip
24190 @end tex
24191 @end iftex
24192
24193 @ifnottex
24194 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
24195 @c the TeX version above for the printed version
24196 @flushleft
24197 @c @multitable @columnfractions .3 .4 .4
24198 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
24199 @item @i{Tool}
24200  @tab @i{Tool with HP Ada}
24201  @tab @i{Tool with @value{EDITION}}
24202 @item Code Management@*System
24203  @tab HP CMS
24204  @tab HP CMS
24205 @item Language-Sensitive@*Editor
24206  @tab HP LSE
24207  @tab emacs or HP LSE (Alpha)
24208 @item
24209  @tab
24210  @tab HP LSE (I64)
24211 @item Debugger
24212  @tab OpenVMS Debug
24213  @tab gdb (Alpha),
24214 @item
24215  @tab
24216  @tab OpenVMS Debug (I64)
24217 @item Source Code Analyzer /@*Cross Referencer
24218  @tab HP SCA
24219  @tab GNAT XREF
24220 @item Test Manager
24221  @tab HP Digital Test@*Manager (DTM)
24222  @tab HP DTM
24223 @item Performance and@*Coverage Analyzer
24224  @tab HP PCA
24225  @tab HP PCA
24226 @item Module Management@*System
24227  @tab HP MMS
24228  @tab Not applicable
24229 @end multitable
24230 @end flushleft
24231 @end ifnottex
24232
24233 @end ifset
24234
24235 @c **************************************
24236 @node Platform-Specific Information for the Run-Time Libraries
24237 @appendix Platform-Specific Information for the Run-Time Libraries
24238 @cindex Tasking and threads libraries
24239 @cindex Threads libraries and tasking
24240 @cindex Run-time libraries (platform-specific information)
24241
24242 @noindent
24243 The GNAT run-time implementation may vary with respect to both the
24244 underlying threads library and the exception handling scheme.
24245 For threads support, one or more of the following are supplied:
24246 @itemize @bullet
24247 @item @b{native threads library}, a binding to the thread package from
24248 the underlying operating system
24249
24250 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
24251 POSIX thread package
24252 @end itemize
24253
24254 @noindent
24255 For exception handling, either or both of two models are supplied:
24256 @itemize @bullet
24257 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
24258 Most programs should experience a substantial speed improvement by
24259 being compiled with a ZCX run-time.
24260 This is especially true for
24261 tasking applications or applications with many exception handlers.}
24262 @cindex Zero-Cost Exceptions
24263 @cindex ZCX (Zero-Cost Exceptions)
24264 which uses binder-generated tables that
24265 are interrogated at run time to locate a handler
24266
24267 @item @b{setjmp / longjmp} (``SJLJ''),
24268 @cindex setjmp/longjmp Exception Model
24269 @cindex SJLJ (setjmp/longjmp Exception Model)
24270 which uses dynamically-set data to establish
24271 the set of handlers
24272 @end itemize
24273
24274 @noindent
24275 This appendix summarizes which combinations of threads and exception support
24276 are supplied on various GNAT platforms.
24277 It then shows how to select a particular library either
24278 permanently or temporarily,
24279 explains the properties of (and tradeoffs among) the various threads
24280 libraries, and provides some additional
24281 information about several specific platforms.
24282
24283 @menu
24284 * Summary of Run-Time Configurations::
24285 * Specifying a Run-Time Library::
24286 * Choosing the Scheduling Policy::
24287 * Solaris-Specific Considerations::
24288 * Linux-Specific Considerations::
24289 * AIX-Specific Considerations::
24290 @end menu
24291
24292 @node Summary of Run-Time Configurations
24293 @section Summary of Run-Time Configurations
24294
24295 @multitable @columnfractions .30 .70
24296 @item @b{alpha-openvms}
24297 @item @code{@ @ }@i{rts-native (default)}
24298 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
24299 @item @code{@ @ @ @ }Exceptions @tab ZCX
24300 @*
24301 @item @b{alpha-tru64}
24302 @item @code{@ @ }@i{rts-native (default)}
24303 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
24304 @item @code{@ @ @ @ }Exceptions @tab ZCX
24305 @*
24306 @item @code{@ @ }@i{rts-sjlj}
24307 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
24308 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24309 @*
24310 @item @b{ia64-hp_linux}
24311 @item @code{@ @ }@i{rts-native (default)}
24312 @item @code{@ @ @ @ }Tasking    @tab pthread library
24313 @item @code{@ @ @ @ }Exceptions @tab ZCX
24314 @*
24315 @item @b{ia64-hpux}
24316 @item @code{@ @ }@i{rts-native (default)}
24317 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
24318 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24319 @*
24320 @item @b{ia64-openvms}
24321 @item @code{@ @ }@i{rts-native (default)}
24322 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
24323 @item @code{@ @ @ @ }Exceptions @tab ZCX
24324 @*
24325 @item @b{ia64-sgi_linux}
24326 @item @code{@ @ }@i{rts-native (default)}
24327 @item @code{@ @ @ @ }Tasking    @tab pthread library
24328 @item @code{@ @ @ @ }Exceptions @tab ZCX
24329 @*
24330 @item @b{mips-irix}
24331 @item @code{@ @ }@i{rts-native (default)}
24332 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
24333 @item @code{@ @ @ @ }Exceptions @tab ZCX
24334 @*
24335 @item @b{pa-hpux}
24336 @item @code{@ @ }@i{rts-native (default)}
24337 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
24338 @item @code{@ @ @ @ }Exceptions @tab ZCX
24339 @*
24340 @item @code{@ @ }@i{rts-sjlj}
24341 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
24342 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24343 @*
24344 @item @b{ppc-aix}
24345 @item @code{@ @ }@i{rts-native (default)}
24346 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
24347 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24348 @*
24349 @item @b{ppc-darwin}
24350 @item @code{@ @ }@i{rts-native (default)}
24351 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
24352 @item @code{@ @ @ @ }Exceptions @tab ZCX
24353 @*
24354 @item @b{sparc-solaris}  @tab
24355 @item @code{@ @ }@i{rts-native (default)}
24356 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
24357 @item @code{@ @ @ @ }Exceptions @tab ZCX
24358 @*
24359 @item @code{@ @ }@i{rts-pthread}
24360 @item @code{@ @ @ @ }Tasking    @tab pthread library
24361 @item @code{@ @ @ @ }Exceptions @tab ZCX
24362 @*
24363 @item @code{@ @ }@i{rts-sjlj}
24364 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
24365 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24366 @*
24367 @item @b{sparc64-solaris}  @tab
24368 @item @code{@ @ }@i{rts-native (default)}
24369 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
24370 @item @code{@ @ @ @ }Exceptions @tab ZCX
24371 @*
24372 @item @b{x86-linux}
24373 @item @code{@ @ }@i{rts-native (default)}
24374 @item @code{@ @ @ @ }Tasking    @tab pthread library
24375 @item @code{@ @ @ @ }Exceptions @tab ZCX
24376 @*
24377 @item @code{@ @ }@i{rts-sjlj}
24378 @item @code{@ @ @ @ }Tasking    @tab pthread library
24379 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24380 @*
24381 @item @b{x86-lynx}
24382 @item @code{@ @ }@i{rts-native (default)}
24383 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
24384 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24385 @*
24386 @item @b{x86-solaris}
24387 @item @code{@ @ }@i{rts-native (default)}
24388 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
24389 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24390 @*
24391 @item @b{x86-windows}
24392 @item @code{@ @ }@i{rts-native (default)}
24393 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
24394 @item @code{@ @ @ @ }Exceptions @tab ZCX
24395 @*
24396 @item @code{@ @ }@i{rts-sjlj (default)}
24397 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
24398 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24399 @*
24400 @item @b{x86_64-linux}
24401 @item @code{@ @ }@i{rts-native (default)}
24402 @item @code{@ @ @ @ }Tasking    @tab pthread library
24403 @item @code{@ @ @ @ }Exceptions @tab ZCX
24404 @*
24405 @item @code{@ @ }@i{rts-sjlj}
24406 @item @code{@ @ @ @ }Tasking    @tab pthread library
24407 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24408 @*
24409 @end multitable
24410
24411 @node Specifying a Run-Time Library
24412 @section Specifying a Run-Time Library
24413
24414 @noindent
24415 The @file{adainclude} subdirectory containing the sources of the GNAT
24416 run-time library, and the @file{adalib} subdirectory containing the
24417 @file{ALI} files and the static and/or shared GNAT library, are located
24418 in the gcc target-dependent area:
24419
24420 @smallexample
24421 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
24422 @end smallexample
24423
24424 @noindent
24425 As indicated above, on some platforms several run-time libraries are supplied.
24426 These libraries are installed in the target dependent area and
24427 contain a complete source and binary subdirectory. The detailed description
24428 below explains the differences between the different libraries in terms of
24429 their thread support.
24430
24431 The default run-time library (when GNAT is installed) is @emph{rts-native}.
24432 This default run time is selected by the means of soft links.
24433 For example on x86-linux:
24434
24435 @smallexample
24436 @group
24437  $(target-dir)
24438      |
24439      +--- adainclude----------+
24440      |                        |
24441      +--- adalib-----------+  |
24442      |                     |  |
24443      +--- rts-native       |  |
24444      |    |                |  |
24445      |    +--- adainclude <---+
24446      |    |                |
24447      |    +--- adalib <----+
24448      |
24449      +--- rts-sjlj
24450           |
24451           +--- adainclude
24452           |
24453           +--- adalib
24454 @end group
24455 @end smallexample
24456
24457 @noindent
24458 If the @i{rts-sjlj} library is to be selected on a permanent basis,
24459 these soft links can be modified with the following commands:
24460
24461 @smallexample
24462 $ cd $target
24463 $ rm -f adainclude adalib
24464 $ ln -s rts-sjlj/adainclude adainclude
24465 $ ln -s rts-sjlj/adalib adalib
24466 @end smallexample
24467
24468 @noindent
24469 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
24470 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
24471 @file{$target/ada_object_path}.
24472
24473 Selecting another run-time library temporarily can be
24474 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
24475 @cindex @option{--RTS} option
24476
24477 @node Choosing the Scheduling Policy
24478 @section Choosing the Scheduling Policy
24479
24480 @noindent
24481 When using a POSIX threads implementation, you have a choice of several
24482 scheduling policies: @code{SCHED_FIFO},
24483 @cindex @code{SCHED_FIFO} scheduling policy
24484 @code{SCHED_RR}
24485 @cindex @code{SCHED_RR} scheduling policy
24486 and @code{SCHED_OTHER}.
24487 @cindex @code{SCHED_OTHER} scheduling policy
24488 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
24489 or @code{SCHED_RR} requires special (e.g., root) privileges.
24490
24491 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
24492 @code{SCHED_FIFO},
24493 @cindex @code{SCHED_FIFO} scheduling policy
24494 you can use one of the following:
24495
24496 @itemize @bullet
24497 @item
24498 @code{pragma Time_Slice (0.0)}
24499 @cindex pragma Time_Slice
24500 @item
24501 the corresponding binder option @option{-T0}
24502 @cindex @option{-T0} option
24503 @item
24504 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24505 @cindex pragma Task_Dispatching_Policy
24506 @end itemize
24507
24508 @noindent
24509 To specify @code{SCHED_RR},
24510 @cindex @code{SCHED_RR} scheduling policy
24511 you should use @code{pragma Time_Slice} with a
24512 value greater than @code{0.0}, or else use the corresponding @option{-T}
24513 binder option.
24514
24515 @node Solaris-Specific Considerations
24516 @section Solaris-Specific Considerations
24517 @cindex Solaris Sparc threads libraries
24518
24519 @noindent
24520 This section addresses some topics related to the various threads libraries
24521 on Sparc Solaris.
24522
24523 @menu
24524 * Solaris Threads Issues::
24525 @end menu
24526
24527 @node Solaris Threads Issues
24528 @subsection Solaris Threads Issues
24529
24530 @noindent
24531 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
24532 library based on POSIX threads --- @emph{rts-pthread}.
24533 @cindex rts-pthread threads library
24534 This run-time library has the advantage of being mostly shared across all
24535 POSIX-compliant thread implementations, and it also provides under
24536 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
24537 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
24538 and @code{PTHREAD_PRIO_PROTECT}
24539 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
24540 semantics that can be selected using the predefined pragma
24541 @code{Locking_Policy}
24542 @cindex pragma Locking_Policy (under rts-pthread)
24543 with respectively
24544 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
24545 @cindex @code{Inheritance_Locking} (under rts-pthread)
24546 @cindex @code{Ceiling_Locking} (under rts-pthread)
24547
24548 As explained above, the native run-time library is based on the Solaris thread
24549 library (@code{libthread}) and is the default library.
24550
24551 When the Solaris threads library is used (this is the default), programs
24552 compiled with GNAT can automatically take advantage of
24553 and can thus execute on multiple processors.
24554 The user can alternatively specify a processor on which the program should run
24555 to emulate a single-processor system. The multiprocessor / uniprocessor choice
24556 is made by
24557 setting the environment variable @code{GNAT_PROCESSOR}
24558 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
24559 to one of the following:
24560
24561 @table @code
24562 @item -2
24563 Use the default configuration (run the program on all
24564          available processors) - this is the same as having
24565          @code{GNAT_PROCESSOR} unset
24566
24567 @item -1
24568 Let the run-time implementation choose one processor and run the program on
24569          that processor
24570
24571 @item 0 .. Last_Proc
24572 Run the program on the specified processor.
24573   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
24574 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
24575 @end table
24576
24577 @node Linux-Specific Considerations
24578 @section Linux-Specific Considerations
24579 @cindex Linux threads libraries
24580
24581 @noindent
24582 On GNU/Linux without NPTL support (usually system with GNU C Library
24583 older than 2.3), the signal model is not POSIX compliant, which means
24584 that to send a signal to the process, you need to send the signal to all
24585 threads, e.g. by using @code{killpg()}.
24586
24587 @node AIX-Specific Considerations
24588 @section AIX-Specific Considerations
24589 @cindex AIX resolver library
24590
24591 @noindent
24592 On AIX, the resolver library initializes some internal structure on
24593 the first call to @code{get*by*} functions, which are used to implement
24594 @code{GNAT.Sockets.Get_Host_By_Name} and
24595 @code{GNAT.Sockets.Get_Host_By_Address}.
24596 If such initialization occurs within an Ada task, and the stack size for
24597 the task is the default size, a stack overflow may occur.
24598
24599 To avoid this overflow, the user should either ensure that the first call
24600 to @code{GNAT.Sockets.Get_Host_By_Name} or
24601 @code{GNAT.Sockets.Get_Host_By_Addrss}
24602 occurs in the environment task, or use @code{pragma Storage_Size} to
24603 specify a sufficiently large size for the stack of the task that contains
24604 this call.
24605
24606 @c *******************************
24607 @node Example of Binder Output File
24608 @appendix Example of Binder Output File
24609
24610 @noindent
24611 This Appendix displays the source code for @command{gnatbind}'s output
24612 file generated for a simple ``Hello World'' program.
24613 Comments have been added for clarification purposes.
24614
24615 @smallexample @c adanocomment
24616 @iftex
24617 @leftskip=0cm
24618 @end iftex
24619 --  The package is called Ada_Main unless this name is actually used
24620 --  as a unit name in the partition, in which case some other unique
24621 --  name is used.
24622
24623 with System;
24624 package ada_main is
24625
24626    Elab_Final_Code : Integer;
24627    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
24628
24629    --  The main program saves the parameters (argument count,
24630    --  argument values, environment pointer) in global variables
24631    --  for later access by other units including
24632    --  Ada.Command_Line.
24633
24634    gnat_argc : Integer;
24635    gnat_argv : System.Address;
24636    gnat_envp : System.Address;
24637
24638    --  The actual variables are stored in a library routine. This
24639    --  is useful for some shared library situations, where there
24640    --  are problems if variables are not in the library.
24641
24642    pragma Import (C, gnat_argc);
24643    pragma Import (C, gnat_argv);
24644    pragma Import (C, gnat_envp);
24645
24646    --  The exit status is similarly an external location
24647
24648    gnat_exit_status : Integer;
24649    pragma Import (C, gnat_exit_status);
24650
24651    GNAT_Version : constant String :=
24652                     "GNAT Version: 6.0.0w (20061115)";
24653    pragma Export (C, GNAT_Version, "__gnat_version");
24654
24655    --  This is the generated adafinal routine that performs
24656    --  finalization at the end of execution. In the case where
24657    --  Ada is the main program, this main program makes a call
24658    --  to adafinal at program termination.
24659
24660    procedure adafinal;
24661    pragma Export (C, adafinal, "adafinal");
24662
24663    --  This is the generated adainit routine that performs
24664    --  initialization at the start of execution. In the case
24665    --  where Ada is the main program, this main program makes
24666    --  a call to adainit at program startup.
24667
24668    procedure adainit;
24669    pragma Export (C, adainit, "adainit");
24670
24671    --  This routine is called at the start of execution. It is
24672    --  a dummy routine that is used by the debugger to breakpoint
24673    --  at the start of execution.
24674
24675    procedure Break_Start;
24676    pragma Import (C, Break_Start, "__gnat_break_start");
24677
24678    --  This is the actual generated main program (it would be
24679    --  suppressed if the no main program switch were used). As
24680    --  required by standard system conventions, this program has
24681    --  the external name main.
24682
24683    function main
24684      (argc : Integer;
24685       argv : System.Address;
24686       envp : System.Address)
24687       return Integer;
24688    pragma Export (C, main, "main");
24689
24690    --  The following set of constants give the version
24691    --  identification values for every unit in the bound
24692    --  partition. This identification is computed from all
24693    --  dependent semantic units, and corresponds to the
24694    --  string that would be returned by use of the
24695    --  Body_Version or Version attributes.
24696
24697    type Version_32 is mod 2 ** 32;
24698    u00001 : constant Version_32 := 16#7880BEB3#;
24699    u00002 : constant Version_32 := 16#0D24CBD0#;
24700    u00003 : constant Version_32 := 16#3283DBEB#;
24701    u00004 : constant Version_32 := 16#2359F9ED#;
24702    u00005 : constant Version_32 := 16#664FB847#;
24703    u00006 : constant Version_32 := 16#68E803DF#;
24704    u00007 : constant Version_32 := 16#5572E604#;
24705    u00008 : constant Version_32 := 16#46B173D8#;
24706    u00009 : constant Version_32 := 16#156A40CF#;
24707    u00010 : constant Version_32 := 16#033DABE0#;
24708    u00011 : constant Version_32 := 16#6AB38FEA#;
24709    u00012 : constant Version_32 := 16#22B6217D#;
24710    u00013 : constant Version_32 := 16#68A22947#;
24711    u00014 : constant Version_32 := 16#18CC4A56#;
24712    u00015 : constant Version_32 := 16#08258E1B#;
24713    u00016 : constant Version_32 := 16#367D5222#;
24714    u00017 : constant Version_32 := 16#20C9ECA4#;
24715    u00018 : constant Version_32 := 16#50D32CB6#;
24716    u00019 : constant Version_32 := 16#39A8BB77#;
24717    u00020 : constant Version_32 := 16#5CF8FA2B#;
24718    u00021 : constant Version_32 := 16#2F1EB794#;
24719    u00022 : constant Version_32 := 16#31AB6444#;
24720    u00023 : constant Version_32 := 16#1574B6E9#;
24721    u00024 : constant Version_32 := 16#5109C189#;
24722    u00025 : constant Version_32 := 16#56D770CD#;
24723    u00026 : constant Version_32 := 16#02F9DE3D#;
24724    u00027 : constant Version_32 := 16#08AB6B2C#;
24725    u00028 : constant Version_32 := 16#3FA37670#;
24726    u00029 : constant Version_32 := 16#476457A0#;
24727    u00030 : constant Version_32 := 16#731E1B6E#;
24728    u00031 : constant Version_32 := 16#23C2E789#;
24729    u00032 : constant Version_32 := 16#0F1BD6A1#;
24730    u00033 : constant Version_32 := 16#7C25DE96#;
24731    u00034 : constant Version_32 := 16#39ADFFA2#;
24732    u00035 : constant Version_32 := 16#571DE3E7#;
24733    u00036 : constant Version_32 := 16#5EB646AB#;
24734    u00037 : constant Version_32 := 16#4249379B#;
24735    u00038 : constant Version_32 := 16#0357E00A#;
24736    u00039 : constant Version_32 := 16#3784FB72#;
24737    u00040 : constant Version_32 := 16#2E723019#;
24738    u00041 : constant Version_32 := 16#623358EA#;
24739    u00042 : constant Version_32 := 16#107F9465#;
24740    u00043 : constant Version_32 := 16#6843F68A#;
24741    u00044 : constant Version_32 := 16#63305874#;
24742    u00045 : constant Version_32 := 16#31E56CE1#;
24743    u00046 : constant Version_32 := 16#02917970#;
24744    u00047 : constant Version_32 := 16#6CCBA70E#;
24745    u00048 : constant Version_32 := 16#41CD4204#;
24746    u00049 : constant Version_32 := 16#572E3F58#;
24747    u00050 : constant Version_32 := 16#20729FF5#;
24748    u00051 : constant Version_32 := 16#1D4F93E8#;
24749    u00052 : constant Version_32 := 16#30B2EC3D#;
24750    u00053 : constant Version_32 := 16#34054F96#;
24751    u00054 : constant Version_32 := 16#5A199860#;
24752    u00055 : constant Version_32 := 16#0E7F912B#;
24753    u00056 : constant Version_32 := 16#5760634A#;
24754    u00057 : constant Version_32 := 16#5D851835#;
24755
24756    --  The following Export pragmas export the version numbers
24757    --  with symbolic names ending in B (for body) or S
24758    --  (for spec) so that they can be located in a link. The
24759    --  information provided here is sufficient to track down
24760    --  the exact versions of units used in a given build.
24761
24762    pragma Export (C, u00001, "helloB");
24763    pragma Export (C, u00002, "system__standard_libraryB");
24764    pragma Export (C, u00003, "system__standard_libraryS");
24765    pragma Export (C, u00004, "adaS");
24766    pragma Export (C, u00005, "ada__text_ioB");
24767    pragma Export (C, u00006, "ada__text_ioS");
24768    pragma Export (C, u00007, "ada__exceptionsB");
24769    pragma Export (C, u00008, "ada__exceptionsS");
24770    pragma Export (C, u00009, "gnatS");
24771    pragma Export (C, u00010, "gnat__heap_sort_aB");
24772    pragma Export (C, u00011, "gnat__heap_sort_aS");
24773    pragma Export (C, u00012, "systemS");
24774    pragma Export (C, u00013, "system__exception_tableB");
24775    pragma Export (C, u00014, "system__exception_tableS");
24776    pragma Export (C, u00015, "gnat__htableB");
24777    pragma Export (C, u00016, "gnat__htableS");
24778    pragma Export (C, u00017, "system__exceptionsS");
24779    pragma Export (C, u00018, "system__machine_state_operationsB");
24780    pragma Export (C, u00019, "system__machine_state_operationsS");
24781    pragma Export (C, u00020, "system__machine_codeS");
24782    pragma Export (C, u00021, "system__storage_elementsB");
24783    pragma Export (C, u00022, "system__storage_elementsS");
24784    pragma Export (C, u00023, "system__secondary_stackB");
24785    pragma Export (C, u00024, "system__secondary_stackS");
24786    pragma Export (C, u00025, "system__parametersB");
24787    pragma Export (C, u00026, "system__parametersS");
24788    pragma Export (C, u00027, "system__soft_linksB");
24789    pragma Export (C, u00028, "system__soft_linksS");
24790    pragma Export (C, u00029, "system__stack_checkingB");
24791    pragma Export (C, u00030, "system__stack_checkingS");
24792    pragma Export (C, u00031, "system__tracebackB");
24793    pragma Export (C, u00032, "system__tracebackS");
24794    pragma Export (C, u00033, "ada__streamsS");
24795    pragma Export (C, u00034, "ada__tagsB");
24796    pragma Export (C, u00035, "ada__tagsS");
24797    pragma Export (C, u00036, "system__string_opsB");
24798    pragma Export (C, u00037, "system__string_opsS");
24799    pragma Export (C, u00038, "interfacesS");
24800    pragma Export (C, u00039, "interfaces__c_streamsB");
24801    pragma Export (C, u00040, "interfaces__c_streamsS");
24802    pragma Export (C, u00041, "system__file_ioB");
24803    pragma Export (C, u00042, "system__file_ioS");
24804    pragma Export (C, u00043, "ada__finalizationB");
24805    pragma Export (C, u00044, "ada__finalizationS");
24806    pragma Export (C, u00045, "system__finalization_rootB");
24807    pragma Export (C, u00046, "system__finalization_rootS");
24808    pragma Export (C, u00047, "system__finalization_implementationB");
24809    pragma Export (C, u00048, "system__finalization_implementationS");
24810    pragma Export (C, u00049, "system__string_ops_concat_3B");
24811    pragma Export (C, u00050, "system__string_ops_concat_3S");
24812    pragma Export (C, u00051, "system__stream_attributesB");
24813    pragma Export (C, u00052, "system__stream_attributesS");
24814    pragma Export (C, u00053, "ada__io_exceptionsS");
24815    pragma Export (C, u00054, "system__unsigned_typesS");
24816    pragma Export (C, u00055, "system__file_control_blockS");
24817    pragma Export (C, u00056, "ada__finalization__list_controllerB");
24818    pragma Export (C, u00057, "ada__finalization__list_controllerS");
24819
24820    -- BEGIN ELABORATION ORDER
24821    -- ada (spec)
24822    -- gnat (spec)
24823    -- gnat.heap_sort_a (spec)
24824    -- gnat.heap_sort_a (body)
24825    -- gnat.htable (spec)
24826    -- gnat.htable (body)
24827    -- interfaces (spec)
24828    -- system (spec)
24829    -- system.machine_code (spec)
24830    -- system.parameters (spec)
24831    -- system.parameters (body)
24832    -- interfaces.c_streams (spec)
24833    -- interfaces.c_streams (body)
24834    -- system.standard_library (spec)
24835    -- ada.exceptions (spec)
24836    -- system.exception_table (spec)
24837    -- system.exception_table (body)
24838    -- ada.io_exceptions (spec)
24839    -- system.exceptions (spec)
24840    -- system.storage_elements (spec)
24841    -- system.storage_elements (body)
24842    -- system.machine_state_operations (spec)
24843    -- system.machine_state_operations (body)
24844    -- system.secondary_stack (spec)
24845    -- system.stack_checking (spec)
24846    -- system.soft_links (spec)
24847    -- system.soft_links (body)
24848    -- system.stack_checking (body)
24849    -- system.secondary_stack (body)
24850    -- system.standard_library (body)
24851    -- system.string_ops (spec)
24852    -- system.string_ops (body)
24853    -- ada.tags (spec)
24854    -- ada.tags (body)
24855    -- ada.streams (spec)
24856    -- system.finalization_root (spec)
24857    -- system.finalization_root (body)
24858    -- system.string_ops_concat_3 (spec)
24859    -- system.string_ops_concat_3 (body)
24860    -- system.traceback (spec)
24861    -- system.traceback (body)
24862    -- ada.exceptions (body)
24863    -- system.unsigned_types (spec)
24864    -- system.stream_attributes (spec)
24865    -- system.stream_attributes (body)
24866    -- system.finalization_implementation (spec)
24867    -- system.finalization_implementation (body)
24868    -- ada.finalization (spec)
24869    -- ada.finalization (body)
24870    -- ada.finalization.list_controller (spec)
24871    -- ada.finalization.list_controller (body)
24872    -- system.file_control_block (spec)
24873    -- system.file_io (spec)
24874    -- system.file_io (body)
24875    -- ada.text_io (spec)
24876    -- ada.text_io (body)
24877    -- hello (body)
24878    -- END ELABORATION ORDER
24879
24880 end ada_main;
24881
24882 --  The following source file name pragmas allow the generated file
24883 --  names to be unique for different main programs. They are needed
24884 --  since the package name will always be Ada_Main.
24885
24886 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
24887 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
24888
24889 --  Generated package body for Ada_Main starts here
24890
24891 package body ada_main is
24892
24893    --  The actual finalization is performed by calling the
24894    --  library routine in System.Standard_Library.Adafinal
24895
24896    procedure Do_Finalize;
24897    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
24898
24899    -------------
24900    -- adainit --
24901    -------------
24902
24903 @findex adainit
24904    procedure adainit is
24905
24906       --  These booleans are set to True once the associated unit has
24907       --  been elaborated. It is also used to avoid elaborating the
24908       --  same unit twice.
24909
24910       E040 : Boolean;
24911       pragma Import (Ada, E040, "interfaces__c_streams_E");
24912
24913       E008 : Boolean;
24914       pragma Import (Ada, E008, "ada__exceptions_E");
24915
24916       E014 : Boolean;
24917       pragma Import (Ada, E014, "system__exception_table_E");
24918
24919       E053 : Boolean;
24920       pragma Import (Ada, E053, "ada__io_exceptions_E");
24921
24922       E017 : Boolean;
24923       pragma Import (Ada, E017, "system__exceptions_E");
24924
24925       E024 : Boolean;
24926       pragma Import (Ada, E024, "system__secondary_stack_E");
24927
24928       E030 : Boolean;
24929       pragma Import (Ada, E030, "system__stack_checking_E");
24930
24931       E028 : Boolean;
24932       pragma Import (Ada, E028, "system__soft_links_E");
24933
24934       E035 : Boolean;
24935       pragma Import (Ada, E035, "ada__tags_E");
24936
24937       E033 : Boolean;
24938       pragma Import (Ada, E033, "ada__streams_E");
24939
24940       E046 : Boolean;
24941       pragma Import (Ada, E046, "system__finalization_root_E");
24942
24943       E048 : Boolean;
24944       pragma Import (Ada, E048, "system__finalization_implementation_E");
24945
24946       E044 : Boolean;
24947       pragma Import (Ada, E044, "ada__finalization_E");
24948
24949       E057 : Boolean;
24950       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
24951
24952       E055 : Boolean;
24953       pragma Import (Ada, E055, "system__file_control_block_E");
24954
24955       E042 : Boolean;
24956       pragma Import (Ada, E042, "system__file_io_E");
24957
24958       E006 : Boolean;
24959       pragma Import (Ada, E006, "ada__text_io_E");
24960
24961       --  Set_Globals is a library routine that stores away the
24962       --  value of the indicated set of global values in global
24963       --  variables within the library.
24964
24965       procedure Set_Globals
24966         (Main_Priority            : Integer;
24967          Time_Slice_Value         : Integer;
24968          WC_Encoding              : Character;
24969          Locking_Policy           : Character;
24970          Queuing_Policy           : Character;
24971          Task_Dispatching_Policy  : Character;
24972          Adafinal                 : System.Address;
24973          Unreserve_All_Interrupts : Integer;
24974          Exception_Tracebacks     : Integer);
24975 @findex __gnat_set_globals
24976       pragma Import (C, Set_Globals, "__gnat_set_globals");
24977
24978       --  SDP_Table_Build is a library routine used to build the
24979       --  exception tables. See unit Ada.Exceptions in files
24980       --  a-except.ads/adb for full details of how zero cost
24981       --  exception handling works. This procedure, the call to
24982       --  it, and the two following tables are all omitted if the
24983       --  build is in longjmp/setjump exception mode.
24984
24985 @findex SDP_Table_Build
24986 @findex Zero Cost Exceptions
24987       procedure SDP_Table_Build
24988         (SDP_Addresses   : System.Address;
24989          SDP_Count       : Natural;
24990          Elab_Addresses  : System.Address;
24991          Elab_Addr_Count : Natural);
24992       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
24993
24994       --  Table of Unit_Exception_Table addresses. Used for zero
24995       --  cost exception handling to build the top level table.
24996
24997       ST : aliased constant array (1 .. 23) of System.Address := (
24998         Hello'UET_Address,
24999         Ada.Text_Io'UET_Address,
25000         Ada.Exceptions'UET_Address,
25001         Gnat.Heap_Sort_A'UET_Address,
25002         System.Exception_Table'UET_Address,
25003         System.Machine_State_Operations'UET_Address,
25004         System.Secondary_Stack'UET_Address,
25005         System.Parameters'UET_Address,
25006         System.Soft_Links'UET_Address,
25007         System.Stack_Checking'UET_Address,
25008         System.Traceback'UET_Address,
25009         Ada.Streams'UET_Address,
25010         Ada.Tags'UET_Address,
25011         System.String_Ops'UET_Address,
25012         Interfaces.C_Streams'UET_Address,
25013         System.File_Io'UET_Address,
25014         Ada.Finalization'UET_Address,
25015         System.Finalization_Root'UET_Address,
25016         System.Finalization_Implementation'UET_Address,
25017         System.String_Ops_Concat_3'UET_Address,
25018         System.Stream_Attributes'UET_Address,
25019         System.File_Control_Block'UET_Address,
25020         Ada.Finalization.List_Controller'UET_Address);
25021
25022       --  Table of addresses of elaboration routines. Used for
25023       --  zero cost exception handling to make sure these
25024       --  addresses are included in the top level procedure
25025       --  address table.
25026
25027       EA : aliased constant array (1 .. 23) of System.Address := (
25028         adainit'Code_Address,
25029         Do_Finalize'Code_Address,
25030         Ada.Exceptions'Elab_Spec'Address,
25031         System.Exceptions'Elab_Spec'Address,
25032         Interfaces.C_Streams'Elab_Spec'Address,
25033         System.Exception_Table'Elab_Body'Address,
25034         Ada.Io_Exceptions'Elab_Spec'Address,
25035         System.Stack_Checking'Elab_Spec'Address,
25036         System.Soft_Links'Elab_Body'Address,
25037         System.Secondary_Stack'Elab_Body'Address,
25038         Ada.Tags'Elab_Spec'Address,
25039         Ada.Tags'Elab_Body'Address,
25040         Ada.Streams'Elab_Spec'Address,
25041         System.Finalization_Root'Elab_Spec'Address,
25042         Ada.Exceptions'Elab_Body'Address,
25043         System.Finalization_Implementation'Elab_Spec'Address,
25044         System.Finalization_Implementation'Elab_Body'Address,
25045         Ada.Finalization'Elab_Spec'Address,
25046         Ada.Finalization.List_Controller'Elab_Spec'Address,
25047         System.File_Control_Block'Elab_Spec'Address,
25048         System.File_Io'Elab_Body'Address,
25049         Ada.Text_Io'Elab_Spec'Address,
25050         Ada.Text_Io'Elab_Body'Address);
25051
25052    --  Start of processing for adainit
25053
25054    begin
25055
25056       --  Call SDP_Table_Build to build the top level procedure
25057       --  table for zero cost exception handling (omitted in
25058       --  longjmp/setjump mode).
25059
25060       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
25061
25062       --  Call Set_Globals to record various information for
25063       --  this partition.  The values are derived by the binder
25064       --  from information stored in the ali files by the compiler.
25065
25066 @findex __gnat_set_globals
25067       Set_Globals
25068         (Main_Priority            => -1,
25069          --  Priority of main program, -1 if no pragma Priority used
25070
25071          Time_Slice_Value         => -1,
25072          --  Time slice from Time_Slice pragma, -1 if none used
25073
25074          WC_Encoding              => 'b',
25075          --  Wide_Character encoding used, default is brackets
25076
25077          Locking_Policy           => ' ',
25078          --  Locking_Policy used, default of space means not
25079          --  specified, otherwise it is the first character of
25080          --  the policy name.
25081
25082          Queuing_Policy           => ' ',
25083          --  Queuing_Policy used, default of space means not
25084          --  specified, otherwise it is the first character of
25085          --  the policy name.
25086
25087          Task_Dispatching_Policy  => ' ',
25088          --  Task_Dispatching_Policy used, default of space means
25089          --  not specified, otherwise first character of the
25090          --  policy name.
25091
25092          Adafinal                 => System.Null_Address,
25093          --  Address of Adafinal routine, not used anymore
25094
25095          Unreserve_All_Interrupts => 0,
25096          --  Set true if pragma Unreserve_All_Interrupts was used
25097
25098          Exception_Tracebacks     => 0);
25099          --  Indicates if exception tracebacks are enabled
25100
25101       Elab_Final_Code := 1;
25102
25103       --  Now we have the elaboration calls for all units in the partition.
25104       --  The Elab_Spec and Elab_Body attributes generate references to the
25105       --  implicit elaboration procedures generated by the compiler for
25106       --  each unit that requires elaboration.
25107
25108       if not E040 then
25109          Interfaces.C_Streams'Elab_Spec;
25110       end if;
25111       E040 := True;
25112       if not E008 then
25113          Ada.Exceptions'Elab_Spec;
25114       end if;
25115       if not E014 then
25116          System.Exception_Table'Elab_Body;
25117          E014 := True;
25118       end if;
25119       if not E053 then
25120          Ada.Io_Exceptions'Elab_Spec;
25121          E053 := True;
25122       end if;
25123       if not E017 then
25124          System.Exceptions'Elab_Spec;
25125          E017 := True;
25126       end if;
25127       if not E030 then
25128          System.Stack_Checking'Elab_Spec;
25129       end if;
25130       if not E028 then
25131          System.Soft_Links'Elab_Body;
25132          E028 := True;
25133       end if;
25134       E030 := True;
25135       if not E024 then
25136          System.Secondary_Stack'Elab_Body;
25137          E024 := True;
25138       end if;
25139       if not E035 then
25140          Ada.Tags'Elab_Spec;
25141       end if;
25142       if not E035 then
25143          Ada.Tags'Elab_Body;
25144          E035 := True;
25145       end if;
25146       if not E033 then
25147          Ada.Streams'Elab_Spec;
25148          E033 := True;
25149       end if;
25150       if not E046 then
25151          System.Finalization_Root'Elab_Spec;
25152       end if;
25153       E046 := True;
25154       if not E008 then
25155          Ada.Exceptions'Elab_Body;
25156          E008 := True;
25157       end if;
25158       if not E048 then
25159          System.Finalization_Implementation'Elab_Spec;
25160       end if;
25161       if not E048 then
25162          System.Finalization_Implementation'Elab_Body;
25163          E048 := True;
25164       end if;
25165       if not E044 then
25166          Ada.Finalization'Elab_Spec;
25167       end if;
25168       E044 := True;
25169       if not E057 then
25170          Ada.Finalization.List_Controller'Elab_Spec;
25171       end if;
25172       E057 := True;
25173       if not E055 then
25174          System.File_Control_Block'Elab_Spec;
25175          E055 := True;
25176       end if;
25177       if not E042 then
25178          System.File_Io'Elab_Body;
25179          E042 := True;
25180       end if;
25181       if not E006 then
25182          Ada.Text_Io'Elab_Spec;
25183       end if;
25184       if not E006 then
25185          Ada.Text_Io'Elab_Body;
25186          E006 := True;
25187       end if;
25188
25189       Elab_Final_Code := 0;
25190    end adainit;
25191
25192    --------------
25193    -- adafinal --
25194    --------------
25195
25196 @findex adafinal
25197    procedure adafinal is
25198    begin
25199       Do_Finalize;
25200    end adafinal;
25201
25202    ----------
25203    -- main --
25204    ----------
25205
25206    --  main is actually a function, as in the ANSI C standard,
25207    --  defined to return the exit status. The three parameters
25208    --  are the argument count, argument values and environment
25209    --  pointer.
25210
25211 @findex Main Program
25212    function main
25213      (argc : Integer;
25214       argv : System.Address;
25215       envp : System.Address)
25216       return Integer
25217    is
25218       --  The initialize routine performs low level system
25219       --  initialization using a standard library routine which
25220       --  sets up signal handling and performs any other
25221       --  required setup. The routine can be found in file
25222       --  a-init.c.
25223
25224 @findex __gnat_initialize
25225       procedure initialize;
25226       pragma Import (C, initialize, "__gnat_initialize");
25227
25228       --  The finalize routine performs low level system
25229       --  finalization using a standard library routine. The
25230       --  routine is found in file a-final.c and in the standard
25231       --  distribution is a dummy routine that does nothing, so
25232       --  really this is a hook for special user finalization.
25233
25234 @findex __gnat_finalize
25235       procedure finalize;
25236       pragma Import (C, finalize, "__gnat_finalize");
25237
25238       --  We get to the main program of the partition by using
25239       --  pragma Import because if we try to with the unit and
25240       --  call it Ada style, then not only do we waste time
25241       --  recompiling it, but also, we don't really know the right
25242       --  switches (e.g. identifier character set) to be used
25243       --  to compile it.
25244
25245       procedure Ada_Main_Program;
25246       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
25247
25248    --  Start of processing for main
25249
25250    begin
25251       --  Save global variables
25252
25253       gnat_argc := argc;
25254       gnat_argv := argv;
25255       gnat_envp := envp;
25256
25257       --  Call low level system initialization
25258
25259       Initialize;
25260
25261       --  Call our generated Ada initialization routine
25262
25263       adainit;
25264
25265       --  This is the point at which we want the debugger to get
25266       --  control
25267
25268       Break_Start;
25269
25270       --  Now we call the main program of the partition
25271
25272       Ada_Main_Program;
25273
25274       --  Perform Ada finalization
25275
25276       adafinal;
25277
25278       --  Perform low level system finalization
25279
25280       Finalize;
25281
25282       --  Return the proper exit status
25283       return (gnat_exit_status);
25284    end;
25285
25286 --  This section is entirely comments, so it has no effect on the
25287 --  compilation of the Ada_Main package. It provides the list of
25288 --  object files and linker options, as well as some standard
25289 --  libraries needed for the link. The gnatlink utility parses
25290 --  this b~hello.adb file to read these comment lines to generate
25291 --  the appropriate command line arguments for the call to the
25292 --  system linker. The BEGIN/END lines are used for sentinels for
25293 --  this parsing operation.
25294
25295 --  The exact file names will of course depend on the environment,
25296 --  host/target and location of files on the host system.
25297
25298 @findex Object file list
25299 -- BEGIN Object file/option list
25300    --   ./hello.o
25301    --   -L./
25302    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
25303    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
25304 -- END Object file/option list
25305
25306 end ada_main;
25307 @end smallexample
25308
25309 @noindent
25310 The Ada code in the above example is exactly what is generated by the
25311 binder. We have added comments to more clearly indicate the function
25312 of each part of the generated @code{Ada_Main} package.
25313
25314 The code is standard Ada in all respects, and can be processed by any
25315 tools that handle Ada. In particular, it is possible to use the debugger
25316 in Ada mode to debug the generated @code{Ada_Main} package. For example,
25317 suppose that for reasons that you do not understand, your program is crashing
25318 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
25319 you can place a breakpoint on the call:
25320
25321 @smallexample @c ada
25322 Ada.Text_Io'Elab_Body;
25323 @end smallexample
25324
25325 @noindent
25326 and trace the elaboration routine for this package to find out where
25327 the problem might be (more usually of course you would be debugging
25328 elaboration code in your own application).
25329
25330 @node Elaboration Order Handling in GNAT
25331 @appendix Elaboration Order Handling in GNAT
25332 @cindex Order of elaboration
25333 @cindex Elaboration control
25334
25335 @menu
25336 * Elaboration Code::
25337 * Checking the Elaboration Order::
25338 * Controlling the Elaboration Order::
25339 * Controlling Elaboration in GNAT - Internal Calls::
25340 * Controlling Elaboration in GNAT - External Calls::
25341 * Default Behavior in GNAT - Ensuring Safety::
25342 * Treatment of Pragma Elaborate::
25343 * Elaboration Issues for Library Tasks::
25344 * Mixing Elaboration Models::
25345 * What to Do If the Default Elaboration Behavior Fails::
25346 * Elaboration for Access-to-Subprogram Values::
25347 * Summary of Procedures for Elaboration Control::
25348 * Other Elaboration Order Considerations::
25349 @end menu
25350
25351 @noindent
25352 This chapter describes the handling of elaboration code in Ada and
25353 in GNAT, and discusses how the order of elaboration of program units can
25354 be controlled in GNAT, either automatically or with explicit programming
25355 features.
25356
25357 @node Elaboration Code
25358 @section Elaboration Code
25359
25360 @noindent
25361 Ada provides rather general mechanisms for executing code at elaboration
25362 time, that is to say before the main program starts executing. Such code arises
25363 in three contexts:
25364
25365 @table @asis
25366 @item Initializers for variables.
25367 Variables declared at the library level, in package specs or bodies, can
25368 require initialization that is performed at elaboration time, as in:
25369 @smallexample @c ada
25370 @cartouche
25371 Sqrt_Half : Float := Sqrt (0.5);
25372 @end cartouche
25373 @end smallexample
25374
25375 @item Package initialization code
25376 Code in a @code{BEGIN-END} section at the outer level of a package body is
25377 executed as part of the package body elaboration code.
25378
25379 @item Library level task allocators
25380 Tasks that are declared using task allocators at the library level
25381 start executing immediately and hence can execute at elaboration time.
25382 @end table
25383
25384 @noindent
25385 Subprogram calls are possible in any of these contexts, which means that
25386 any arbitrary part of the program may be executed as part of the elaboration
25387 code. It is even possible to write a program which does all its work at
25388 elaboration time, with a null main program, although stylistically this
25389 would usually be considered an inappropriate way to structure
25390 a program.
25391
25392 An important concern arises in the context of elaboration code:
25393 we have to be sure that it is executed in an appropriate order. What we
25394 have is a series of elaboration code sections, potentially one section
25395 for each unit in the program. It is important that these execute
25396 in the correct order. Correctness here means that, taking the above
25397 example of the declaration of @code{Sqrt_Half},
25398 if some other piece of
25399 elaboration code references @code{Sqrt_Half},
25400 then it must run after the
25401 section of elaboration code that contains the declaration of
25402 @code{Sqrt_Half}.
25403
25404 There would never be any order of elaboration problem if we made a rule
25405 that whenever you @code{with} a unit, you must elaborate both the spec and body
25406 of that unit before elaborating the unit doing the @code{with}'ing:
25407
25408 @smallexample @c ada
25409 @group
25410 @cartouche
25411 with Unit_1;
25412 package Unit_2 is ...
25413 @end cartouche
25414 @end group
25415 @end smallexample
25416
25417 @noindent
25418 would require that both the body and spec of @code{Unit_1} be elaborated
25419 before the spec of @code{Unit_2}. However, a rule like that would be far too
25420 restrictive. In particular, it would make it impossible to have routines
25421 in separate packages that were mutually recursive.
25422
25423 You might think that a clever enough compiler could look at the actual
25424 elaboration code and determine an appropriate correct order of elaboration,
25425 but in the general case, this is not possible. Consider the following
25426 example.
25427
25428 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
25429 that references
25430 the variable @code{Sqrt_1}, which is declared in the elaboration code
25431 of the body of @code{Unit_1}:
25432
25433 @smallexample @c ada
25434 @cartouche
25435 Sqrt_1 : Float := Sqrt (0.1);
25436 @end cartouche
25437 @end smallexample
25438
25439 @noindent
25440 The elaboration code of the body of @code{Unit_1} also contains:
25441
25442 @smallexample @c ada
25443 @group
25444 @cartouche
25445 if expression_1 = 1 then
25446    Q := Unit_2.Func_2;
25447 end if;
25448 @end cartouche
25449 @end group
25450 @end smallexample
25451
25452 @noindent
25453 @code{Unit_2} is exactly parallel,
25454 it has a procedure @code{Func_2} that references
25455 the variable @code{Sqrt_2}, which is declared in the elaboration code of
25456 the body @code{Unit_2}:
25457
25458 @smallexample @c ada
25459 @cartouche
25460 Sqrt_2 : Float := Sqrt (0.1);
25461 @end cartouche
25462 @end smallexample
25463
25464 @noindent
25465 The elaboration code of the body of @code{Unit_2} also contains:
25466
25467 @smallexample @c ada
25468 @group
25469 @cartouche
25470 if expression_2 = 2 then
25471    Q := Unit_1.Func_1;
25472 end if;
25473 @end cartouche
25474 @end group
25475 @end smallexample
25476
25477 @noindent
25478 Now the question is, which of the following orders of elaboration is
25479 acceptable:
25480
25481 @smallexample
25482 @group
25483 Spec of Unit_1
25484 Spec of Unit_2
25485 Body of Unit_1
25486 Body of Unit_2
25487 @end group
25488 @end smallexample
25489
25490 @noindent
25491 or
25492
25493 @smallexample
25494 @group
25495 Spec of Unit_2
25496 Spec of Unit_1
25497 Body of Unit_2
25498 Body of Unit_1
25499 @end group
25500 @end smallexample
25501
25502 @noindent
25503 If you carefully analyze the flow here, you will see that you cannot tell
25504 at compile time the answer to this question.
25505 If @code{expression_1} is not equal to 1,
25506 and @code{expression_2} is not equal to 2,
25507 then either order is acceptable, because neither of the function calls is
25508 executed. If both tests evaluate to true, then neither order is acceptable
25509 and in fact there is no correct order.
25510
25511 If one of the two expressions is true, and the other is false, then one
25512 of the above orders is correct, and the other is incorrect. For example,
25513 if @code{expression_1} = 1 and @code{expression_2} /= 2,
25514 then the call to @code{Func_2}
25515 will occur, but not the call to @code{Func_1.}
25516 This means that it is essential
25517 to elaborate the body of @code{Unit_1} before
25518 the body of @code{Unit_2}, so the first
25519 order of elaboration is correct and the second is wrong.
25520
25521 By making @code{expression_1} and @code{expression_2}
25522 depend on input data, or perhaps
25523 the time of day, we can make it impossible for the compiler or binder
25524 to figure out which of these expressions will be true, and hence it
25525 is impossible to guarantee a safe order of elaboration at run time.
25526
25527 @node Checking the Elaboration Order
25528 @section Checking the Elaboration Order
25529
25530 @noindent
25531 In some languages that involve the same kind of elaboration problems,
25532 e.g. Java and C++, the programmer is expected to worry about these
25533 ordering problems himself, and it is common to
25534 write a program in which an incorrect elaboration order  gives
25535 surprising results, because it references variables before they
25536 are initialized.
25537 Ada is designed to be a safe language, and a programmer-beware approach is
25538 clearly not sufficient. Consequently, the language provides three lines
25539 of defense:
25540
25541 @table @asis
25542 @item Standard rules
25543 Some standard rules restrict the possible choice of elaboration
25544 order. In particular, if you @code{with} a unit, then its spec is always
25545 elaborated before the unit doing the @code{with}. Similarly, a parent
25546 spec is always elaborated before the child spec, and finally
25547 a spec is always elaborated before its corresponding body.
25548
25549 @item Dynamic elaboration checks
25550 @cindex Elaboration checks
25551 @cindex Checks, elaboration
25552 Dynamic checks are made at run time, so that if some entity is accessed
25553 before it is elaborated (typically  by means of a subprogram call)
25554 then the exception (@code{Program_Error}) is raised.
25555
25556 @item Elaboration control
25557 Facilities are provided for the programmer to specify the desired order
25558 of elaboration.
25559 @end table
25560
25561 Let's look at these facilities in more detail. First, the rules for
25562 dynamic checking. One possible rule would be simply to say that the
25563 exception is raised if you access a variable which has not yet been
25564 elaborated. The trouble with this approach is that it could require
25565 expensive checks on every variable reference. Instead Ada has two
25566 rules which are a little more restrictive, but easier to check, and
25567 easier to state:
25568
25569 @table @asis
25570 @item Restrictions on calls
25571 A subprogram can only be called at elaboration time if its body
25572 has been elaborated. The rules for elaboration given above guarantee
25573 that the spec of the subprogram has been elaborated before the
25574 call, but not the body. If this rule is violated, then the
25575 exception @code{Program_Error} is raised.
25576
25577 @item Restrictions on instantiations
25578 A generic unit can only be instantiated if the body of the generic
25579 unit has been elaborated. Again, the rules for elaboration given above
25580 guarantee that the spec of the generic unit has been elaborated
25581 before the instantiation, but not the body. If this rule is
25582 violated, then the exception @code{Program_Error} is raised.
25583 @end table
25584
25585 @noindent
25586 The idea is that if the body has been elaborated, then any variables
25587 it references must have been elaborated; by checking for the body being
25588 elaborated we guarantee that none of its references causes any
25589 trouble. As we noted above, this is a little too restrictive, because a
25590 subprogram that has no non-local references in its body may in fact be safe
25591 to call. However, it really would be unsafe to rely on this, because
25592 it would mean that the caller was aware of details of the implementation
25593 in the body. This goes against the basic tenets of Ada.
25594
25595 A plausible implementation can be described as follows.
25596 A Boolean variable is associated with each subprogram
25597 and each generic unit. This variable is initialized to False, and is set to
25598 True at the point body is elaborated. Every call or instantiation checks the
25599 variable, and raises @code{Program_Error} if the variable is False.
25600
25601 Note that one might think that it would be good enough to have one Boolean
25602 variable for each package, but that would not deal with cases of trying
25603 to call a body in the same package as the call
25604 that has not been elaborated yet.
25605 Of course a compiler may be able to do enough analysis to optimize away
25606 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
25607 does such optimizations, but still the easiest conceptual model is to
25608 think of there being one variable per subprogram.
25609
25610 @node Controlling the Elaboration Order
25611 @section Controlling the Elaboration Order
25612
25613 @noindent
25614 In the previous section we discussed the rules in Ada which ensure
25615 that @code{Program_Error} is raised if an incorrect elaboration order is
25616 chosen. This prevents erroneous executions, but we need mechanisms to
25617 specify a correct execution and avoid the exception altogether.
25618 To achieve this, Ada provides a number of features for controlling
25619 the order of elaboration. We discuss these features in this section.
25620
25621 First, there are several ways of indicating to the compiler that a given
25622 unit has no elaboration problems:
25623
25624 @table @asis
25625 @item packages that do not require a body
25626 A library package that does not require a body does not permit
25627 a body (this rule was introduced in Ada 95).
25628 Thus if we have a such a package, as in:
25629
25630 @smallexample @c ada
25631 @group
25632 @cartouche
25633 package Definitions is
25634    generic
25635       type m is new integer;
25636    package Subp is
25637       type a is array (1 .. 10) of m;
25638       type b is array (1 .. 20) of m;
25639    end Subp;
25640 end Definitions;
25641 @end cartouche
25642 @end group
25643 @end smallexample
25644
25645 @noindent
25646 A package that @code{with}'s @code{Definitions} may safely instantiate
25647 @code{Definitions.Subp} because the compiler can determine that there
25648 definitely is no package body to worry about in this case
25649
25650 @item pragma Pure
25651 @cindex pragma Pure
25652 @findex Pure
25653 Places sufficient restrictions on a unit to guarantee that
25654 no call to any subprogram in the unit can result in an
25655 elaboration problem. This means that the compiler does not need
25656 to worry about the point of elaboration of such units, and in
25657 particular, does not need to check any calls to any subprograms
25658 in this unit.
25659
25660 @item pragma Preelaborate
25661 @findex Preelaborate
25662 @cindex pragma Preelaborate
25663 This pragma places slightly less stringent restrictions on a unit than
25664 does pragma Pure,
25665 but these restrictions are still sufficient to ensure that there
25666 are no elaboration problems with any calls to the unit.
25667
25668 @item pragma Elaborate_Body
25669 @findex Elaborate_Body
25670 @cindex pragma Elaborate_Body
25671 This pragma requires that the body of a unit be elaborated immediately
25672 after its spec. Suppose a unit @code{A} has such a pragma,
25673 and unit @code{B} does
25674 a @code{with} of unit @code{A}. Recall that the standard rules require
25675 the spec of unit @code{A}
25676 to be elaborated before the @code{with}'ing unit; given the pragma in
25677 @code{A}, we also know that the body of @code{A}
25678 will be elaborated before @code{B}, so
25679 that calls to @code{A} are safe and do not need a check.
25680 @end table
25681
25682 @noindent
25683 Note that,
25684 unlike pragma @code{Pure} and pragma @code{Preelaborate},
25685 the use of
25686 @code{Elaborate_Body} does not guarantee that the program is
25687 free of elaboration problems, because it may not be possible
25688 to satisfy the requested elaboration order.
25689 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
25690 If a programmer
25691 marks @code{Unit_1} as @code{Elaborate_Body},
25692 and not @code{Unit_2,} then the order of
25693 elaboration will be:
25694
25695 @smallexample
25696 @group
25697 Spec of Unit_2
25698 Spec of Unit_1
25699 Body of Unit_1
25700 Body of Unit_2
25701 @end group
25702 @end smallexample
25703
25704 @noindent
25705 Now that means that the call to @code{Func_1} in @code{Unit_2}
25706 need not be checked,
25707 it must be safe. But the call to @code{Func_2} in
25708 @code{Unit_1} may still fail if
25709 @code{Expression_1} is equal to 1,
25710 and the programmer must still take
25711 responsibility for this not being the case.
25712
25713 If all units carry a pragma @code{Elaborate_Body}, then all problems are
25714 eliminated, except for calls entirely within a body, which are
25715 in any case fully under programmer control. However, using the pragma
25716 everywhere is not always possible.
25717 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
25718 we marked both of them as having pragma @code{Elaborate_Body}, then
25719 clearly there would be no possible elaboration order.
25720
25721 The above pragmas allow a server to guarantee safe use by clients, and
25722 clearly this is the preferable approach. Consequently a good rule
25723 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
25724 and if this is not possible,
25725 mark them as @code{Elaborate_Body} if possible.
25726 As we have seen, there are situations where neither of these
25727 three pragmas can be used.
25728 So we also provide methods for clients to control the
25729 order of elaboration of the servers on which they depend:
25730
25731 @table @asis
25732 @item pragma Elaborate (unit)
25733 @findex Elaborate
25734 @cindex pragma Elaborate
25735 This pragma is placed in the context clause, after a @code{with} clause,
25736 and it requires that the body of the named unit be elaborated before
25737 the unit in which the pragma occurs. The idea is to use this pragma
25738 if the current unit calls at elaboration time, directly or indirectly,
25739 some subprogram in the named unit.
25740
25741 @item pragma Elaborate_All (unit)
25742 @findex Elaborate_All
25743 @cindex pragma Elaborate_All
25744 This is a stronger version of the Elaborate pragma. Consider the
25745 following example:
25746
25747 @smallexample
25748 Unit A @code{with}'s unit B and calls B.Func in elab code
25749 Unit B @code{with}'s unit C, and B.Func calls C.Func
25750 @end smallexample
25751
25752 @noindent
25753 Now if we put a pragma @code{Elaborate (B)}
25754 in unit @code{A}, this ensures that the
25755 body of @code{B} is elaborated before the call, but not the
25756 body of @code{C}, so
25757 the call to @code{C.Func} could still cause @code{Program_Error} to
25758 be raised.
25759
25760 The effect of a pragma @code{Elaborate_All} is stronger, it requires
25761 not only that the body of the named unit be elaborated before the
25762 unit doing the @code{with}, but also the bodies of all units that the
25763 named unit uses, following @code{with} links transitively. For example,
25764 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
25765 then it requires
25766 not only that the body of @code{B} be elaborated before @code{A},
25767 but also the
25768 body of @code{C}, because @code{B} @code{with}'s @code{C}.
25769 @end table
25770
25771 @noindent
25772 We are now in a position to give a usage rule in Ada for avoiding
25773 elaboration problems, at least if dynamic dispatching and access to
25774 subprogram values are not used. We will handle these cases separately
25775 later.
25776
25777 The rule is simple. If a unit has elaboration code that can directly or
25778 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
25779 a generic package in a @code{with}'ed unit,
25780 then if the @code{with}'ed unit does not have
25781 pragma @code{Pure} or @code{Preelaborate}, then the client should have
25782 a pragma @code{Elaborate_All}
25783 for the @code{with}'ed unit. By following this rule a client is
25784 assured that calls can be made without risk of an exception.
25785
25786 For generic subprogram instantiations, the rule can be relaxed to
25787 require only a pragma @code{Elaborate} since elaborating the body
25788 of a subprogram cannot cause any transitive elaboration (we are
25789 not calling the subprogram in this case, just elaborating its
25790 declaration).
25791
25792 If this rule is not followed, then a program may be in one of four
25793 states:
25794
25795 @table @asis
25796 @item No order exists
25797 No order of elaboration exists which follows the rules, taking into
25798 account any @code{Elaborate}, @code{Elaborate_All},
25799 or @code{Elaborate_Body} pragmas. In
25800 this case, an Ada compiler must diagnose the situation at bind
25801 time, and refuse to build an executable program.
25802
25803 @item One or more orders exist, all incorrect
25804 One or more acceptable elaboration orders exists, and all of them
25805 generate an elaboration order problem. In this case, the binder
25806 can build an executable program, but @code{Program_Error} will be raised
25807 when the program is run.
25808
25809 @item Several orders exist, some right, some incorrect
25810 One or more acceptable elaboration orders exists, and some of them
25811 work, and some do not. The programmer has not controlled
25812 the order of elaboration, so the binder may or may not pick one of
25813 the correct orders, and the program may or may not raise an
25814 exception when it is run. This is the worst case, because it means
25815 that the program may fail when moved to another compiler, or even
25816 another version of the same compiler.
25817
25818 @item One or more orders exists, all correct
25819 One ore more acceptable elaboration orders exist, and all of them
25820 work. In this case the program runs successfully. This state of
25821 affairs can be guaranteed by following the rule we gave above, but
25822 may be true even if the rule is not followed.
25823 @end table
25824
25825 @noindent
25826 Note that one additional advantage of following our rules on the use
25827 of @code{Elaborate} and @code{Elaborate_All}
25828 is that the program continues to stay in the ideal (all orders OK) state
25829 even if maintenance
25830 changes some bodies of some units. Conversely, if a program that does
25831 not follow this rule happens to be safe at some point, this state of affairs
25832 may deteriorate silently as a result of maintenance changes.
25833
25834 You may have noticed that the above discussion did not mention
25835 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
25836 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
25837 code in the body makes calls to some other unit, so it is still necessary
25838 to use @code{Elaborate_All} on such units.
25839
25840 @node Controlling Elaboration in GNAT - Internal Calls
25841 @section Controlling Elaboration in GNAT - Internal Calls
25842
25843 @noindent
25844 In the case of internal calls, i.e. calls within a single package, the
25845 programmer has full control over the order of elaboration, and it is up
25846 to the programmer to elaborate declarations in an appropriate order. For
25847 example writing:
25848
25849 @smallexample @c ada
25850 @group
25851 @cartouche
25852 function One return Float;
25853
25854 Q : Float := One;
25855
25856 function One return Float is
25857 begin
25858      return 1.0;
25859 end One;
25860 @end cartouche
25861 @end group
25862 @end smallexample
25863
25864 @noindent
25865 will obviously raise @code{Program_Error} at run time, because function
25866 One will be called before its body is elaborated. In this case GNAT will
25867 generate a warning that the call will raise @code{Program_Error}:
25868
25869 @smallexample
25870 @group
25871 @cartouche
25872  1. procedure y is
25873  2.    function One return Float;
25874  3.
25875  4.    Q : Float := One;
25876                     |
25877     >>> warning: cannot call "One" before body is elaborated
25878     >>> warning: Program_Error will be raised at run time
25879
25880  5.
25881  6.    function One return Float is
25882  7.    begin
25883  8.         return 1.0;
25884  9.    end One;
25885 10.
25886 11. begin
25887 12.    null;
25888 13. end;
25889 @end cartouche
25890 @end group
25891 @end smallexample
25892
25893 @noindent
25894 Note that in this particular case, it is likely that the call is safe, because
25895 the function @code{One} does not access any global variables.
25896 Nevertheless in Ada, we do not want the validity of the check to depend on
25897 the contents of the body (think about the separate compilation case), so this
25898 is still wrong, as we discussed in the previous sections.
25899
25900 The error is easily corrected by rearranging the declarations so that the
25901 body of @code{One} appears before the declaration containing the call
25902 (note that in Ada 95 and Ada 2005,
25903 declarations can appear in any order, so there is no restriction that
25904 would prevent this reordering, and if we write:
25905
25906 @smallexample @c ada
25907 @group
25908 @cartouche
25909 function One return Float;
25910
25911 function One return Float is
25912 begin
25913      return 1.0;
25914 end One;
25915
25916 Q : Float := One;
25917 @end cartouche
25918 @end group
25919 @end smallexample
25920
25921 @noindent
25922 then all is well, no warning is generated, and no
25923 @code{Program_Error} exception
25924 will be raised.
25925 Things are more complicated when a chain of subprograms is executed:
25926
25927 @smallexample @c ada
25928 @group
25929 @cartouche
25930 function A return Integer;
25931 function B return Integer;
25932 function C return Integer;
25933
25934 function B return Integer is begin return A; end;
25935 function C return Integer is begin return B; end;
25936
25937 X : Integer := C;
25938
25939 function A return Integer is begin return 1; end;
25940 @end cartouche
25941 @end group
25942 @end smallexample
25943
25944 @noindent
25945 Now the call to @code{C}
25946 at elaboration time in the declaration of @code{X} is correct, because
25947 the body of @code{C} is already elaborated,
25948 and the call to @code{B} within the body of
25949 @code{C} is correct, but the call
25950 to @code{A} within the body of @code{B} is incorrect, because the body
25951 of @code{A} has not been elaborated, so @code{Program_Error}
25952 will be raised on the call to @code{A}.
25953 In this case GNAT will generate a
25954 warning that @code{Program_Error} may be
25955 raised at the point of the call. Let's look at the warning:
25956
25957 @smallexample
25958 @group
25959 @cartouche
25960  1. procedure x is
25961  2.    function A return Integer;
25962  3.    function B return Integer;
25963  4.    function C return Integer;
25964  5.
25965  6.    function B return Integer is begin return A; end;
25966                                                     |
25967     >>> warning: call to "A" before body is elaborated may
25968                  raise Program_Error
25969     >>> warning: "B" called at line 7
25970     >>> warning: "C" called at line 9
25971
25972  7.    function C return Integer is begin return B; end;
25973  8.
25974  9.    X : Integer := C;
25975 10.
25976 11.    function A return Integer is begin return 1; end;
25977 12.
25978 13. begin
25979 14.    null;
25980 15. end;
25981 @end cartouche
25982 @end group
25983 @end smallexample
25984
25985 @noindent
25986 Note that the message here says ``may raise'', instead of the direct case,
25987 where the message says ``will be raised''. That's because whether
25988 @code{A} is
25989 actually called depends in general on run-time flow of control.
25990 For example, if the body of @code{B} said
25991
25992 @smallexample @c ada
25993 @group
25994 @cartouche
25995 function B return Integer is
25996 begin
25997    if some-condition-depending-on-input-data then
25998       return A;
25999    else
26000       return 1;
26001    end if;
26002 end B;
26003 @end cartouche
26004 @end group
26005 @end smallexample
26006
26007 @noindent
26008 then we could not know until run time whether the incorrect call to A would
26009 actually occur, so @code{Program_Error} might
26010 or might not be raised. It is possible for a compiler to
26011 do a better job of analyzing bodies, to
26012 determine whether or not @code{Program_Error}
26013 might be raised, but it certainly
26014 couldn't do a perfect job (that would require solving the halting problem
26015 and is provably impossible), and because this is a warning anyway, it does
26016 not seem worth the effort to do the analysis. Cases in which it
26017 would be relevant are rare.
26018
26019 In practice, warnings of either of the forms given
26020 above will usually correspond to
26021 real errors, and should be examined carefully and eliminated.
26022 In the rare case where a warning is bogus, it can be suppressed by any of
26023 the following methods:
26024
26025 @itemize @bullet
26026 @item
26027 Compile with the @option{-gnatws} switch set
26028
26029 @item
26030 Suppress @code{Elaboration_Check} for the called subprogram
26031
26032 @item
26033 Use pragma @code{Warnings_Off} to turn warnings off for the call
26034 @end itemize
26035
26036 @noindent
26037 For the internal elaboration check case,
26038 GNAT by default generates the
26039 necessary run-time checks to ensure
26040 that @code{Program_Error} is raised if any
26041 call fails an elaboration check. Of course this can only happen if a
26042 warning has been issued as described above. The use of pragma
26043 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
26044 some of these checks, meaning that it may be possible (but is not
26045 guaranteed) for a program to be able to call a subprogram whose body
26046 is not yet elaborated, without raising a @code{Program_Error} exception.
26047
26048 @node Controlling Elaboration in GNAT - External Calls
26049 @section Controlling Elaboration in GNAT - External Calls
26050
26051 @noindent
26052 The previous section discussed the case in which the execution of a
26053 particular thread of elaboration code occurred entirely within a
26054 single unit. This is the easy case to handle, because a programmer
26055 has direct and total control over the order of elaboration, and
26056 furthermore, checks need only be generated in cases which are rare
26057 and which the compiler can easily detect.
26058 The situation is more complex when separate compilation is taken into account.
26059 Consider the following:
26060
26061 @smallexample @c ada
26062 @cartouche
26063 @group
26064 package Math is
26065    function Sqrt (Arg : Float) return Float;
26066 end Math;
26067
26068 package body Math is
26069    function Sqrt (Arg : Float) return Float is
26070    begin
26071          ...
26072    end Sqrt;
26073 end Math;
26074 @end group
26075 @group
26076 with Math;
26077 package Stuff is
26078    X : Float := Math.Sqrt (0.5);
26079 end Stuff;
26080
26081 with Stuff;
26082 procedure Main is
26083 begin
26084    ...
26085 end Main;
26086 @end group
26087 @end cartouche
26088 @end smallexample
26089
26090 @noindent
26091 where @code{Main} is the main program. When this program is executed, the
26092 elaboration code must first be executed, and one of the jobs of the
26093 binder is to determine the order in which the units of a program are
26094 to be elaborated. In this case we have four units: the spec and body
26095 of @code{Math},
26096 the spec of @code{Stuff} and the body of @code{Main}).
26097 In what order should the four separate sections of elaboration code
26098 be executed?
26099
26100 There are some restrictions in the order of elaboration that the binder
26101 can choose. In particular, if unit U has a @code{with}
26102 for a package @code{X}, then you
26103 are assured that the spec of @code{X}
26104 is elaborated before U , but you are
26105 not assured that the body of @code{X}
26106 is elaborated before U.
26107 This means that in the above case, the binder is allowed to choose the
26108 order:
26109
26110 @smallexample
26111 spec of Math
26112 spec of Stuff
26113 body of Math
26114 body of Main
26115 @end smallexample
26116
26117 @noindent
26118 but that's not good, because now the call to @code{Math.Sqrt}
26119 that happens during
26120 the elaboration of the @code{Stuff}
26121 spec happens before the body of @code{Math.Sqrt} is
26122 elaborated, and hence causes @code{Program_Error} exception to be raised.
26123 At first glance, one might say that the binder is misbehaving, because
26124 obviously you want to elaborate the body of something you @code{with}
26125 first, but
26126 that is not a general rule that can be followed in all cases. Consider
26127
26128 @smallexample @c ada
26129 @group
26130 @cartouche
26131 package X is ...
26132
26133 package Y is ...
26134
26135 with X;
26136 package body Y is ...
26137
26138 with Y;
26139 package body X is ...
26140 @end cartouche
26141 @end group
26142 @end smallexample
26143
26144 @noindent
26145 This is a common arrangement, and, apart from the order of elaboration
26146 problems that might arise in connection with elaboration code, this works fine.
26147 A rule that says that you must first elaborate the body of anything you
26148 @code{with} cannot work in this case:
26149 the body of @code{X} @code{with}'s @code{Y},
26150 which means you would have to
26151 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
26152 which means
26153 you have to elaborate the body of @code{X} first, but ... and we have a
26154 loop that cannot be broken.
26155
26156 It is true that the binder can in many cases guess an order of elaboration
26157 that is unlikely to cause a @code{Program_Error}
26158 exception to be raised, and it tries to do so (in the
26159 above example of @code{Math/Stuff/Spec}, the GNAT binder will
26160 by default
26161 elaborate the body of @code{Math} right after its spec, so all will be well).
26162
26163 However, a program that blindly relies on the binder to be helpful can
26164 get into trouble, as we discussed in the previous sections, so
26165 GNAT
26166 provides a number of facilities for assisting the programmer in
26167 developing programs that are robust with respect to elaboration order.
26168
26169 @node Default Behavior in GNAT - Ensuring Safety
26170 @section Default Behavior in GNAT - Ensuring Safety
26171
26172 @noindent
26173 The default behavior in GNAT ensures elaboration safety. In its
26174 default mode GNAT implements the
26175 rule we previously described as the right approach. Let's restate it:
26176
26177 @itemize
26178 @item
26179 @emph{If a unit has elaboration code that can directly or indirectly make a
26180 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
26181 package in a @code{with}'ed unit, then if the @code{with}'ed unit
26182 does not have pragma @code{Pure} or
26183 @code{Preelaborate}, then the client should have an
26184 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
26185
26186 @emph{In the case of instantiating a generic subprogram, it is always
26187 sufficient to have only an @code{Elaborate} pragma for the
26188 @code{with}'ed unit.}
26189 @end itemize
26190
26191 @noindent
26192 By following this rule a client is assured that calls and instantiations
26193 can be made without risk of an exception.
26194
26195 In this mode GNAT traces all calls that are potentially made from
26196 elaboration code, and puts in any missing implicit @code{Elaborate}
26197 and @code{Elaborate_All} pragmas.
26198 The advantage of this approach is that no elaboration problems
26199 are possible if the binder can find an elaboration order that is
26200 consistent with these implicit @code{Elaborate} and
26201 @code{Elaborate_All} pragmas. The
26202 disadvantage of this approach is that no such order may exist.
26203
26204 If the binder does not generate any diagnostics, then it means that it has
26205 found an elaboration order that is guaranteed to be safe. However, the binder
26206 may still be relying on implicitly generated @code{Elaborate} and
26207 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
26208 guaranteed.
26209
26210 If it is important to guarantee portability, then the compilations should
26211 use the
26212 @option{-gnatwl}
26213 (warn on elaboration problems) switch. This will cause warning messages
26214 to be generated indicating the missing @code{Elaborate} and
26215 @code{Elaborate_All} pragmas.
26216 Consider the following source program:
26217
26218 @smallexample @c ada
26219 @group
26220 @cartouche
26221 with k;
26222 package j is
26223   m : integer := k.r;
26224 end;
26225 @end cartouche
26226 @end group
26227 @end smallexample
26228
26229 @noindent
26230 where it is clear that there
26231 should be a pragma @code{Elaborate_All}
26232 for unit @code{k}. An implicit pragma will be generated, and it is
26233 likely that the binder will be able to honor it. However, if you want
26234 to port this program to some other Ada compiler than GNAT.
26235 it is safer to include the pragma explicitly in the source. If this
26236 unit is compiled with the
26237 @option{-gnatwl}
26238 switch, then the compiler outputs a warning:
26239
26240 @smallexample
26241 @group
26242 @cartouche
26243 1. with k;
26244 2. package j is
26245 3.   m : integer := k.r;
26246                      |
26247    >>> warning: call to "r" may raise Program_Error
26248    >>> warning: missing pragma Elaborate_All for "k"
26249
26250 4. end;
26251 @end cartouche
26252 @end group
26253 @end smallexample
26254
26255 @noindent
26256 and these warnings can be used as a guide for supplying manually
26257 the missing pragmas. It is usually a bad idea to use this warning
26258 option during development. That's because it will warn you when
26259 you need to put in a pragma, but cannot warn you when it is time
26260 to take it out. So the use of pragma @code{Elaborate_All} may lead to
26261 unnecessary dependencies and even false circularities.
26262
26263 This default mode is more restrictive than the Ada Reference
26264 Manual, and it is possible to construct programs which will compile
26265 using the dynamic model described there, but will run into a
26266 circularity using the safer static model we have described.
26267
26268 Of course any Ada compiler must be able to operate in a mode
26269 consistent with the requirements of the Ada Reference Manual,
26270 and in particular must have the capability of implementing the
26271 standard dynamic model of elaboration with run-time checks.
26272
26273 In GNAT, this standard mode can be achieved either by the use of
26274 the @option{-gnatE} switch on the compiler (@command{gcc} or
26275 @command{gnatmake}) command, or by the use of the configuration pragma:
26276
26277 @smallexample @c ada
26278 pragma Elaboration_Checks (RM);
26279 @end smallexample
26280
26281 @noindent
26282 Either approach will cause the unit affected to be compiled using the
26283 standard dynamic run-time elaboration checks described in the Ada
26284 Reference Manual. The static model is generally preferable, since it
26285 is clearly safer to rely on compile and link time checks rather than
26286 run-time checks. However, in the case of legacy code, it may be
26287 difficult to meet the requirements of the static model. This
26288 issue is further discussed in
26289 @ref{What to Do If the Default Elaboration Behavior Fails}.
26290
26291 Note that the static model provides a strict subset of the allowed
26292 behavior and programs of the Ada Reference Manual, so if you do
26293 adhere to the static model and no circularities exist,
26294 then you are assured that your program will
26295 work using the dynamic model, providing that you remove any
26296 pragma Elaborate statements from the source.
26297
26298 @node Treatment of Pragma Elaborate
26299 @section Treatment of Pragma Elaborate
26300 @cindex Pragma Elaborate
26301
26302 @noindent
26303 The use of @code{pragma Elaborate}
26304 should generally be avoided in Ada 95 and Ada 2005 programs,
26305 since there is no guarantee that transitive calls
26306 will be properly handled. Indeed at one point, this pragma was placed
26307 in Annex J (Obsolescent Features), on the grounds that it is never useful.
26308
26309 Now that's a bit restrictive. In practice, the case in which
26310 @code{pragma Elaborate} is useful is when the caller knows that there
26311 are no transitive calls, or that the called unit contains all necessary
26312 transitive @code{pragma Elaborate} statements, and legacy code often
26313 contains such uses.
26314
26315 Strictly speaking the static mode in GNAT should ignore such pragmas,
26316 since there is no assurance at compile time that the necessary safety
26317 conditions are met. In practice, this would cause GNAT to be incompatible
26318 with correctly written Ada 83 code that had all necessary
26319 @code{pragma Elaborate} statements in place. Consequently, we made the
26320 decision that GNAT in its default mode will believe that if it encounters
26321 a @code{pragma Elaborate} then the programmer knows what they are doing,
26322 and it will trust that no elaboration errors can occur.
26323
26324 The result of this decision is two-fold. First to be safe using the
26325 static mode, you should remove all @code{pragma Elaborate} statements.
26326 Second, when fixing circularities in existing code, you can selectively
26327 use @code{pragma Elaborate} statements to convince the static mode of
26328 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
26329 statement.
26330
26331 When using the static mode with @option{-gnatwl}, any use of
26332 @code{pragma Elaborate} will generate a warning about possible
26333 problems.
26334
26335 @node Elaboration Issues for Library Tasks
26336 @section Elaboration Issues for Library Tasks
26337 @cindex Library tasks, elaboration issues
26338 @cindex Elaboration of library tasks
26339
26340 @noindent
26341 In this section we examine special elaboration issues that arise for
26342 programs that declare library level tasks.
26343
26344 Generally the model of execution of an Ada program is that all units are
26345 elaborated, and then execution of the program starts. However, the
26346 declaration of library tasks definitely does not fit this model. The
26347 reason for this is that library tasks start as soon as they are declared
26348 (more precisely, as soon as the statement part of the enclosing package
26349 body is reached), that is to say before elaboration
26350 of the program is complete. This means that if such a task calls a
26351 subprogram, or an entry in another task, the callee may or may not be
26352 elaborated yet, and in the standard
26353 Reference Manual model of dynamic elaboration checks, you can even
26354 get timing dependent Program_Error exceptions, since there can be
26355 a race between the elaboration code and the task code.
26356
26357 The static model of elaboration in GNAT seeks to avoid all such
26358 dynamic behavior, by being conservative, and the conservative
26359 approach in this particular case is to assume that all the code
26360 in a task body is potentially executed at elaboration time if
26361 a task is declared at the library level.
26362
26363 This can definitely result in unexpected circularities. Consider
26364 the following example
26365
26366 @smallexample @c ada
26367 package Decls is
26368   task Lib_Task is
26369      entry Start;
26370   end Lib_Task;
26371
26372   type My_Int is new Integer;
26373
26374   function Ident (M : My_Int) return My_Int;
26375 end Decls;
26376
26377 with Utils;
26378 package body Decls is
26379   task body Lib_Task is
26380   begin
26381      accept Start;
26382      Utils.Put_Val (2);
26383   end Lib_Task;
26384
26385   function Ident (M : My_Int) return My_Int is
26386   begin
26387      return M;
26388   end Ident;
26389 end Decls;
26390
26391 with Decls;
26392 package Utils is
26393   procedure Put_Val (Arg : Decls.My_Int);
26394 end Utils;
26395
26396 with Text_IO;
26397 package body Utils is
26398   procedure Put_Val (Arg : Decls.My_Int) is
26399   begin
26400      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26401   end Put_Val;
26402 end Utils;
26403
26404 with Decls;
26405 procedure Main is
26406 begin
26407    Decls.Lib_Task.Start;
26408 end;
26409 @end smallexample
26410
26411 @noindent
26412 If the above example is compiled in the default static elaboration
26413 mode, then a circularity occurs. The circularity comes from the call
26414 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
26415 this call occurs in elaboration code, we need an implicit pragma
26416 @code{Elaborate_All} for @code{Utils}. This means that not only must
26417 the spec and body of @code{Utils} be elaborated before the body
26418 of @code{Decls}, but also the spec and body of any unit that is
26419 @code{with'ed} by the body of @code{Utils} must also be elaborated before
26420 the body of @code{Decls}. This is the transitive implication of
26421 pragma @code{Elaborate_All} and it makes sense, because in general
26422 the body of @code{Put_Val} might have a call to something in a
26423 @code{with'ed} unit.
26424
26425 In this case, the body of Utils (actually its spec) @code{with's}
26426 @code{Decls}. Unfortunately this means that the body of @code{Decls}
26427 must be elaborated before itself, in case there is a call from the
26428 body of @code{Utils}.
26429
26430 Here is the exact chain of events we are worrying about:
26431
26432 @enumerate
26433 @item
26434 In the body of @code{Decls} a call is made from within the body of a library
26435 task to a subprogram in the package @code{Utils}. Since this call may
26436 occur at elaboration time (given that the task is activated at elaboration
26437 time), we have to assume the worst, i.e. that the
26438 call does happen at elaboration time.
26439
26440 @item
26441 This means that the body and spec of @code{Util} must be elaborated before
26442 the body of @code{Decls} so that this call does not cause an access before
26443 elaboration.
26444
26445 @item
26446 Within the body of @code{Util}, specifically within the body of
26447 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
26448 by this package.
26449
26450 @item
26451 One such @code{with}'ed package is package @code{Decls}, so there
26452 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
26453 In fact there is such a call in this example, but we would have to
26454 assume that there was such a call even if it were not there, since
26455 we are not supposed to write the body of @code{Decls} knowing what
26456 is in the body of @code{Utils}; certainly in the case of the
26457 static elaboration model, the compiler does not know what is in
26458 other bodies and must assume the worst.
26459
26460 @item
26461 This means that the spec and body of @code{Decls} must also be
26462 elaborated before we elaborate the unit containing the call, but
26463 that unit is @code{Decls}! This means that the body of @code{Decls}
26464 must be elaborated before itself, and that's a circularity.
26465 @end enumerate
26466
26467 @noindent
26468 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
26469 the body of @code{Decls} you will get a true Ada Reference Manual
26470 circularity that makes the program illegal.
26471
26472 In practice, we have found that problems with the static model of
26473 elaboration in existing code often arise from library tasks, so
26474 we must address this particular situation.
26475
26476 Note that if we compile and run the program above, using the dynamic model of
26477 elaboration (that is to say use the @option{-gnatE} switch),
26478 then it compiles, binds,
26479 links, and runs, printing the expected result of 2. Therefore in some sense
26480 the circularity here is only apparent, and we need to capture
26481 the properties of this program that  distinguish it from other library-level
26482 tasks that have real elaboration problems.
26483
26484 We have four possible answers to this question:
26485
26486 @itemize @bullet
26487
26488 @item
26489 Use the dynamic model of elaboration.
26490
26491 If we use the @option{-gnatE} switch, then as noted above, the program works.
26492 Why is this? If we examine the task body, it is apparent that the task cannot
26493 proceed past the
26494 @code{accept} statement until after elaboration has been completed, because
26495 the corresponding entry call comes from the main program, not earlier.
26496 This is why the dynamic model works here. But that's really giving
26497 up on a precise analysis, and we prefer to take this approach only if we cannot
26498 solve the
26499 problem in any other manner. So let us examine two ways to reorganize
26500 the program to avoid the potential elaboration problem.
26501
26502 @item
26503 Split library tasks into separate packages.
26504
26505 Write separate packages, so that library tasks are isolated from
26506 other declarations as much as possible. Let us look at a variation on
26507 the above program.
26508
26509 @smallexample @c ada
26510 package Decls1 is
26511   task Lib_Task is
26512      entry Start;
26513   end Lib_Task;
26514 end Decls1;
26515
26516 with Utils;
26517 package body Decls1 is
26518   task body Lib_Task is
26519   begin
26520      accept Start;
26521      Utils.Put_Val (2);
26522   end Lib_Task;
26523 end Decls1;
26524
26525 package Decls2 is
26526   type My_Int is new Integer;
26527   function Ident (M : My_Int) return My_Int;
26528 end Decls2;
26529
26530 with Utils;
26531 package body Decls2 is
26532   function Ident (M : My_Int) return My_Int is
26533   begin
26534      return M;
26535   end Ident;
26536 end Decls2;
26537
26538 with Decls2;
26539 package Utils is
26540   procedure Put_Val (Arg : Decls2.My_Int);
26541 end Utils;
26542
26543 with Text_IO;
26544 package body Utils is
26545   procedure Put_Val (Arg : Decls2.My_Int) is
26546   begin
26547      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
26548   end Put_Val;
26549 end Utils;
26550
26551 with Decls1;
26552 procedure Main is
26553 begin
26554    Decls1.Lib_Task.Start;
26555 end;
26556 @end smallexample
26557
26558 @noindent
26559 All we have done is to split @code{Decls} into two packages, one
26560 containing the library task, and one containing everything else. Now
26561 there is no cycle, and the program compiles, binds, links and executes
26562 using the default static model of elaboration.
26563
26564 @item
26565 Declare separate task types.
26566
26567 A significant part of the problem arises because of the use of the
26568 single task declaration form. This means that the elaboration of
26569 the task type, and the elaboration of the task itself (i.e. the
26570 creation of the task) happen at the same time. A good rule
26571 of style in Ada is to always create explicit task types. By
26572 following the additional step of placing task objects in separate
26573 packages from the task type declaration, many elaboration problems
26574 are avoided. Here is another modified example of the example program:
26575
26576 @smallexample @c ada
26577 package Decls is
26578   task type Lib_Task_Type is
26579      entry Start;
26580   end Lib_Task_Type;
26581
26582   type My_Int is new Integer;
26583
26584   function Ident (M : My_Int) return My_Int;
26585 end Decls;
26586
26587 with Utils;
26588 package body Decls is
26589   task body Lib_Task_Type is
26590   begin
26591      accept Start;
26592      Utils.Put_Val (2);
26593   end Lib_Task_Type;
26594
26595   function Ident (M : My_Int) return My_Int is
26596   begin
26597      return M;
26598   end Ident;
26599 end Decls;
26600
26601 with Decls;
26602 package Utils is
26603   procedure Put_Val (Arg : Decls.My_Int);
26604 end Utils;
26605
26606 with Text_IO;
26607 package body Utils is
26608   procedure Put_Val (Arg : Decls.My_Int) is
26609   begin
26610      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26611   end Put_Val;
26612 end Utils;
26613
26614 with Decls;
26615 package Declst is
26616    Lib_Task : Decls.Lib_Task_Type;
26617 end Declst;
26618
26619 with Declst;
26620 procedure Main is
26621 begin
26622    Declst.Lib_Task.Start;
26623 end;
26624 @end smallexample
26625
26626 @noindent
26627 What we have done here is to replace the @code{task} declaration in
26628 package @code{Decls} with a @code{task type} declaration. Then we
26629 introduce a separate package @code{Declst} to contain the actual
26630 task object. This separates the elaboration issues for
26631 the @code{task type}
26632 declaration, which causes no trouble, from the elaboration issues
26633 of the task object, which is also unproblematic, since it is now independent
26634 of the elaboration of  @code{Utils}.
26635 This separation of concerns also corresponds to
26636 a generally sound engineering principle of separating declarations
26637 from instances. This version of the program also compiles, binds, links,
26638 and executes, generating the expected output.
26639
26640 @item
26641 Use No_Entry_Calls_In_Elaboration_Code restriction.
26642 @cindex No_Entry_Calls_In_Elaboration_Code
26643
26644 The previous two approaches described how a program can be restructured
26645 to avoid the special problems caused by library task bodies. in practice,
26646 however, such restructuring may be difficult to apply to existing legacy code,
26647 so we must consider solutions that do not require massive rewriting.
26648
26649 Let us consider more carefully why our original sample program works
26650 under the dynamic model of elaboration. The reason is that the code
26651 in the task body blocks immediately on the @code{accept}
26652 statement. Now of course there is nothing to prohibit elaboration
26653 code from making entry calls (for example from another library level task),
26654 so we cannot tell in isolation that
26655 the task will not execute the accept statement  during elaboration.
26656
26657 However, in practice it is very unusual to see elaboration code
26658 make any entry calls, and the pattern of tasks starting
26659 at elaboration time and then immediately blocking on @code{accept} or
26660 @code{select} statements is very common. What this means is that
26661 the compiler is being too pessimistic when it analyzes the
26662 whole package body as though it might be executed at elaboration
26663 time.
26664
26665 If we know that the elaboration code contains no entry calls, (a very safe
26666 assumption most of the time, that could almost be made the default
26667 behavior), then we can compile all units of the program under control
26668 of the following configuration pragma:
26669
26670 @smallexample
26671 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
26672 @end smallexample
26673
26674 @noindent
26675 This pragma can be placed in the @file{gnat.adc} file in the usual
26676 manner. If we take our original unmodified program and compile it
26677 in the presence of a @file{gnat.adc} containing the above pragma,
26678 then once again, we can compile, bind, link, and execute, obtaining
26679 the expected result. In the presence of this pragma, the compiler does
26680 not trace calls in a task body, that appear after the first @code{accept}
26681 or @code{select} statement, and therefore does not report a potential
26682 circularity in the original program.
26683
26684 The compiler will check to the extent it can that the above
26685 restriction is not violated, but it is not always possible to do a
26686 complete check at compile time, so it is important to use this
26687 pragma only if the stated restriction is in fact met, that is to say
26688 no task receives an entry call before elaboration of all units is completed.
26689
26690 @end itemize
26691
26692 @node Mixing Elaboration Models
26693 @section Mixing Elaboration Models
26694 @noindent
26695 So far, we have assumed that the entire program is either compiled
26696 using the dynamic model or static model, ensuring consistency. It
26697 is possible to mix the two models, but rules have to be followed
26698 if this mixing is done to ensure that elaboration checks are not
26699 omitted.
26700
26701 The basic rule is that @emph{a unit compiled with the static model cannot
26702 be @code{with'ed} by a unit compiled with the dynamic model}. The
26703 reason for this is that in the static model, a unit assumes that
26704 its clients guarantee to use (the equivalent of) pragma
26705 @code{Elaborate_All} so that no elaboration checks are required
26706 in inner subprograms, and this assumption is violated if the
26707 client is compiled with dynamic checks.
26708
26709 The precise rule is as follows. A unit that is compiled with dynamic
26710 checks can only @code{with} a unit that meets at least one of the
26711 following criteria:
26712
26713 @itemize @bullet
26714
26715 @item
26716 The @code{with'ed} unit is itself compiled with dynamic elaboration
26717 checks (that is with the @option{-gnatE} switch.
26718
26719 @item
26720 The @code{with'ed} unit is an internal GNAT implementation unit from
26721 the System, Interfaces, Ada, or GNAT hierarchies.
26722
26723 @item
26724 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
26725
26726 @item
26727 The @code{with'ing} unit (that is the client) has an explicit pragma
26728 @code{Elaborate_All} for the @code{with'ed} unit.
26729
26730 @end itemize
26731
26732 @noindent
26733 If this rule is violated, that is if a unit with dynamic elaboration
26734 checks @code{with's} a unit that does not meet one of the above four
26735 criteria, then the binder (@code{gnatbind}) will issue a warning
26736 similar to that in the following example:
26737
26738 @smallexample
26739 warning: "x.ads" has dynamic elaboration checks and with's
26740 warning:   "y.ads" which has static elaboration checks
26741 @end smallexample
26742
26743 @noindent
26744 These warnings indicate that the rule has been violated, and that as a result
26745 elaboration checks may be missed in the resulting executable file.
26746 This warning may be suppressed using the @option{-ws} binder switch
26747 in the usual manner.
26748
26749 One useful application of this mixing rule is in the case of a subsystem
26750 which does not itself @code{with} units from the remainder of the
26751 application. In this case, the entire subsystem can be compiled with
26752 dynamic checks to resolve a circularity in the subsystem, while
26753 allowing the main application that uses this subsystem to be compiled
26754 using the more reliable default static model.
26755
26756 @node What to Do If the Default Elaboration Behavior Fails
26757 @section What to Do If the Default Elaboration Behavior Fails
26758
26759 @noindent
26760 If the binder cannot find an acceptable order, it outputs detailed
26761 diagnostics. For example:
26762 @smallexample
26763 @group
26764 @iftex
26765 @leftskip=0cm
26766 @end iftex
26767 error: elaboration circularity detected
26768 info:   "proc (body)" must be elaborated before "pack (body)"
26769 info:     reason: Elaborate_All probably needed in unit "pack (body)"
26770 info:     recompile "pack (body)" with -gnatwl
26771 info:                             for full details
26772 info:       "proc (body)"
26773 info:         is needed by its spec:
26774 info:       "proc (spec)"
26775 info:         which is withed by:
26776 info:       "pack (body)"
26777 info:  "pack (body)" must be elaborated before "proc (body)"
26778 info:     reason: pragma Elaborate in unit "proc (body)"
26779 @end group
26780
26781 @end smallexample
26782
26783 @noindent
26784 In this case we have a cycle that the binder cannot break. On the one
26785 hand, there is an explicit pragma Elaborate in @code{proc} for
26786 @code{pack}. This means that the body of @code{pack} must be elaborated
26787 before the body of @code{proc}. On the other hand, there is elaboration
26788 code in @code{pack} that calls a subprogram in @code{proc}. This means
26789 that for maximum safety, there should really be a pragma
26790 Elaborate_All in @code{pack} for @code{proc} which would require that
26791 the body of @code{proc} be elaborated before the body of
26792 @code{pack}. Clearly both requirements cannot be satisfied.
26793 Faced with a circularity of this kind, you have three different options.
26794
26795 @table @asis
26796 @item Fix the program
26797 The most desirable option from the point of view of long-term maintenance
26798 is to rearrange the program so that the elaboration problems are avoided.
26799 One useful technique is to place the elaboration code into separate
26800 child packages. Another is to move some of the initialization code to
26801 explicitly called subprograms, where the program controls the order
26802 of initialization explicitly. Although this is the most desirable option,
26803 it may be impractical and involve too much modification, especially in
26804 the case of complex legacy code.
26805
26806 @item Perform dynamic checks
26807 If the compilations are done using the
26808 @option{-gnatE}
26809 (dynamic elaboration check) switch, then GNAT behaves in a quite different
26810 manner. Dynamic checks are generated for all calls that could possibly result
26811 in raising an exception. With this switch, the compiler does not generate
26812 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
26813 exactly as specified in the @cite{Ada Reference Manual}.
26814 The binder will generate
26815 an executable program that may or may not raise @code{Program_Error}, and then
26816 it is the programmer's job to ensure that it does not raise an exception. Note
26817 that it is important to compile all units with the switch, it cannot be used
26818 selectively.
26819
26820 @item Suppress checks
26821 The drawback of dynamic checks is that they generate a
26822 significant overhead at run time, both in space and time. If you
26823 are absolutely sure that your program cannot raise any elaboration
26824 exceptions, and you still want to use the dynamic elaboration model,
26825 then you can use the configuration pragma
26826 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
26827 example this pragma could be placed in the @file{gnat.adc} file.
26828
26829 @item Suppress checks selectively
26830 When you know that certain calls or instantiations in elaboration code cannot
26831 possibly lead to an elaboration error, and the binder nevertheless complains
26832 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
26833 elaboration circularities, it is possible to remove those warnings locally and
26834 obtain a program that will bind. Clearly this can be unsafe, and it is the
26835 responsibility of the programmer to make sure that the resulting program has no
26836 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
26837 used with different granularity to suppress warnings and break elaboration
26838 circularities:
26839
26840 @itemize @bullet
26841 @item
26842 Place the pragma that names the called subprogram in the declarative part
26843 that contains the call.
26844
26845 @item
26846 Place the pragma in the declarative part, without naming an entity. This
26847 disables warnings on all calls in the corresponding  declarative region.
26848
26849 @item
26850 Place the pragma in the package spec that declares the called subprogram,
26851 and name the subprogram. This disables warnings on all elaboration calls to
26852 that subprogram.
26853
26854 @item
26855 Place the pragma in the package spec that declares the called subprogram,
26856 without naming any entity. This disables warnings on all elaboration calls to
26857 all subprograms declared in this spec.
26858
26859 @item Use Pragma Elaborate
26860 As previously described in section @xref{Treatment of Pragma Elaborate},
26861 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
26862 that no elaboration checks are required on calls to the designated unit.
26863 There may be cases in which the caller knows that no transitive calls
26864 can occur, so that a @code{pragma Elaborate} will be sufficient in a
26865 case where @code{pragma Elaborate_All} would cause a circularity.
26866 @end itemize
26867
26868 @noindent
26869 These five cases are listed in order of decreasing safety, and therefore
26870 require increasing programmer care in their application. Consider the
26871 following program:
26872
26873 @smallexample @c adanocomment
26874 package Pack1 is
26875   function F1 return Integer;
26876   X1 : Integer;
26877 end Pack1;
26878
26879 package Pack2 is
26880   function F2 return Integer;
26881   function Pure (x : integer) return integer;
26882   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
26883   --  pragma Suppress (Elaboration_Check);              -- (4)
26884 end Pack2;
26885
26886 with Pack2;
26887 package body Pack1 is
26888   function F1 return Integer is
26889   begin
26890     return 100;
26891   end F1;
26892   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
26893 begin
26894   declare
26895     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
26896     --  pragma Suppress(Elaboration_Check);             -- (2)
26897   begin
26898     X1 := Pack2.F2 + 1;                --  Elab. call (2)
26899   end;
26900 end Pack1;
26901
26902 with Pack1;
26903 package body Pack2 is
26904   function F2 return Integer is
26905   begin
26906      return Pack1.F1;
26907   end F2;
26908   function Pure (x : integer) return integer is
26909   begin
26910      return x ** 3 - 3 * x;
26911   end;
26912 end Pack2;
26913
26914 with Pack1, Ada.Text_IO;
26915 procedure Proc3 is
26916 begin
26917   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
26918 end Proc3;
26919 @end smallexample
26920 In the absence of any pragmas, an attempt to bind this program produces
26921 the following diagnostics:
26922 @smallexample
26923 @group
26924 @iftex
26925 @leftskip=.5cm
26926 @end iftex
26927 error: elaboration circularity detected
26928 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
26929 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
26930 info:       recompile "pack1 (body)" with -gnatwl for full details
26931 info:          "pack1 (body)"
26932 info:             must be elaborated along with its spec:
26933 info:          "pack1 (spec)"
26934 info:             which is withed by:
26935 info:          "pack2 (body)"
26936 info:             which must be elaborated along with its spec:
26937 info:          "pack2 (spec)"
26938 info:             which is withed by:
26939 info:          "pack1 (body)"
26940 @end group
26941 @end smallexample
26942 The sources of the circularity are the two calls to @code{Pack2.Pure} and
26943 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
26944 F2 is safe, even though F2 calls F1, because the call appears after the
26945 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
26946 remove the warning on the call. It is also possible to use pragma (2)
26947 because there are no other potentially unsafe calls in the block.
26948
26949 @noindent
26950 The call to @code{Pure} is safe because this function does not depend on the
26951 state of @code{Pack2}. Therefore any call to this function is safe, and it
26952 is correct to place pragma (3) in the corresponding package spec.
26953
26954 @noindent
26955 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
26956 warnings on all calls to functions declared therein. Note that this is not
26957 necessarily safe, and requires more detailed examination of the subprogram
26958 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
26959 be already elaborated.
26960 @end table
26961
26962 @noindent
26963 It is hard to generalize on which of these four approaches should be
26964 taken. Obviously if it is possible to fix the program so that the default
26965 treatment works, this is preferable, but this may not always be practical.
26966 It is certainly simple enough to use
26967 @option{-gnatE}
26968 but the danger in this case is that, even if the GNAT binder
26969 finds a correct elaboration order, it may not always do so,
26970 and certainly a binder from another Ada compiler might not. A
26971 combination of testing and analysis (for which the warnings generated
26972 with the
26973 @option{-gnatwl}
26974 switch can be useful) must be used to ensure that the program is free
26975 of errors. One switch that is useful in this testing is the
26976 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
26977 switch for
26978 @code{gnatbind}.
26979 Normally the binder tries to find an order that has the best chance of
26980 of avoiding elaboration problems. With this switch, the binder
26981 plays a devil's advocate role, and tries to choose the order that
26982 has the best chance of failing. If your program works even with this
26983 switch, then it has a better chance of being error free, but this is still
26984 not a guarantee.
26985
26986 For an example of this approach in action, consider the C-tests (executable
26987 tests) from the ACVC suite. If these are compiled and run with the default
26988 treatment, then all but one of them succeed without generating any error
26989 diagnostics from the binder. However, there is one test that fails, and
26990 this is not surprising, because the whole point of this test is to ensure
26991 that the compiler can handle cases where it is impossible to determine
26992 a correct order statically, and it checks that an exception is indeed
26993 raised at run time.
26994
26995 This one test must be compiled and run using the
26996 @option{-gnatE}
26997 switch, and then it passes. Alternatively, the entire suite can
26998 be run using this switch. It is never wrong to run with the dynamic
26999 elaboration switch if your code is correct, and we assume that the
27000 C-tests are indeed correct (it is less efficient, but efficiency is
27001 not a factor in running the ACVC tests.)
27002
27003 @node Elaboration for Access-to-Subprogram Values
27004 @section Elaboration for Access-to-Subprogram Values
27005 @cindex Access-to-subprogram
27006
27007 @noindent
27008 Access-to-subprogram types (introduced in Ada 95) complicate
27009 the handling of elaboration. The trouble is that it becomes
27010 impossible to tell at compile time which procedure
27011 is being called. This means that it is not possible for the binder
27012 to analyze the elaboration requirements in this case.
27013
27014 If at the point at which the access value is created
27015 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
27016 the body of the subprogram is
27017 known to have been elaborated, then the access value is safe, and its use
27018 does not require a check. This may be achieved by appropriate arrangement
27019 of the order of declarations if the subprogram is in the current unit,
27020 or, if the subprogram is in another unit, by using pragma
27021 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
27022 on the referenced unit.
27023
27024 If the referenced body is not known to have been elaborated at the point
27025 the access value is created, then any use of the access value must do a
27026 dynamic check, and this dynamic check will fail and raise a
27027 @code{Program_Error} exception if the body has not been elaborated yet.
27028 GNAT will generate the necessary checks, and in addition, if the
27029 @option{-gnatwl}
27030 switch is set, will generate warnings that such checks are required.
27031
27032 The use of dynamic dispatching for tagged types similarly generates
27033 a requirement for dynamic checks, and premature calls to any primitive
27034 operation of a tagged type before the body of the operation has been
27035 elaborated, will result in the raising of @code{Program_Error}.
27036
27037 @node Summary of Procedures for Elaboration Control
27038 @section Summary of Procedures for Elaboration Control
27039 @cindex Elaboration control
27040
27041 @noindent
27042 First, compile your program with the default options, using none of
27043 the special elaboration control switches. If the binder successfully
27044 binds your program, then you can be confident that, apart from issues
27045 raised by the use of access-to-subprogram types and dynamic dispatching,
27046 the program is free of elaboration errors. If it is important that the
27047 program be portable, then use the
27048 @option{-gnatwl}
27049 switch to generate warnings about missing @code{Elaborate} or
27050 @code{Elaborate_All} pragmas, and supply the missing pragmas.
27051
27052 If the program fails to bind using the default static elaboration
27053 handling, then you can fix the program to eliminate the binder
27054 message, or recompile the entire program with the
27055 @option{-gnatE} switch to generate dynamic elaboration checks,
27056 and, if you are sure there really are no elaboration problems,
27057 use a global pragma @code{Suppress (Elaboration_Check)}.
27058
27059 @node Other Elaboration Order Considerations
27060 @section Other Elaboration Order Considerations
27061 @noindent
27062 This section has been entirely concerned with the issue of finding a valid
27063 elaboration order, as defined by the Ada Reference Manual. In a case
27064 where several elaboration orders are valid, the task is to find one
27065 of the possible valid elaboration orders (and the static model in GNAT
27066 will ensure that this is achieved).
27067
27068 The purpose of the elaboration rules in the Ada Reference Manual is to
27069 make sure that no entity is accessed before it has been elaborated. For
27070 a subprogram, this means that the spec and body must have been elaborated
27071 before the subprogram is called. For an object, this means that the object
27072 must have been elaborated before its value is read or written. A violation
27073 of either of these two requirements is an access before elaboration order,
27074 and this section has been all about avoiding such errors.
27075
27076 In the case where more than one order of elaboration is possible, in the
27077 sense that access before elaboration errors are avoided, then any one of
27078 the orders is ``correct'' in the sense that it meets the requirements of
27079 the Ada Reference Manual, and no such error occurs.
27080
27081 However, it may be the case for a given program, that there are
27082 constraints on the order of elaboration that come not from consideration
27083 of avoiding elaboration errors, but rather from extra-lingual logic
27084 requirements. Consider this example:
27085
27086 @smallexample @c ada
27087 with Init_Constants;
27088 package Constants is
27089    X : Integer := 0;
27090    Y : Integer := 0;
27091 end Constants;
27092
27093 package Init_Constants is
27094    procedure P; -- require a body
27095 end Init_Constants;
27096
27097 with Constants;
27098 package body Init_Constants is
27099    procedure P is begin null; end;
27100 begin
27101    Constants.X := 3;
27102    Constants.Y := 4;
27103 end Init_Constants;
27104
27105 with Constants;
27106 package Calc is
27107    Z : Integer := Constants.X + Constants.Y;
27108 end Calc;
27109
27110 with Calc;
27111 with Text_IO; use Text_IO;
27112 procedure Main is
27113 begin
27114    Put_Line (Calc.Z'Img);
27115 end Main;
27116 @end smallexample
27117
27118 @noindent
27119 In this example, there is more than one valid order of elaboration. For
27120 example both the following are correct orders:
27121
27122 @smallexample
27123 Init_Constants spec
27124 Constants spec
27125 Calc spec
27126 Init_Constants body
27127 Main body
27128
27129   and
27130
27131 Init_Constants spec
27132 Init_Constants body
27133 Constants spec
27134 Calc spec
27135 Main body
27136 @end smallexample
27137
27138 @noindent
27139 There is no language rule to prefer one or the other, both are correct
27140 from an order of elaboration point of view. But the programmatic effects
27141 of the two orders are very different. In the first, the elaboration routine
27142 of @code{Calc} initializes @code{Z} to zero, and then the main program
27143 runs with this value of zero. But in the second order, the elaboration
27144 routine of @code{Calc} runs after the body of Init_Constants has set
27145 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
27146 runs.
27147
27148 One could perhaps by applying pretty clever non-artificial intelligence
27149 to the situation guess that it is more likely that the second order of
27150 elaboration is the one desired, but there is no formal linguistic reason
27151 to prefer one over the other. In fact in this particular case, GNAT will
27152 prefer the second order, because of the rule that bodies are elaborated
27153 as soon as possible, but it's just luck that this is what was wanted
27154 (if indeed the second order was preferred).
27155
27156 If the program cares about the order of elaboration routines in a case like
27157 this, it is important to specify the order required. In this particular
27158 case, that could have been achieved by adding to the spec of Calc:
27159
27160 @smallexample @c ada
27161 pragma Elaborate_All (Constants);
27162 @end smallexample
27163
27164 @noindent
27165 which requires that the body (if any) and spec of @code{Constants},
27166 as well as the body and spec of any unit @code{with}'ed by
27167 @code{Constants} be elaborated before @code{Calc} is elaborated.
27168
27169 Clearly no automatic method can always guess which alternative you require,
27170 and if you are working with legacy code that had constraints of this kind
27171 which were not properly specified by adding @code{Elaborate} or
27172 @code{Elaborate_All} pragmas, then indeed it is possible that two different
27173 compilers can choose different orders.
27174
27175 However, GNAT does attempt to diagnose the common situation where there
27176 are uninitialized variables in the visible part of a package spec, and the
27177 corresponding package body has an elaboration block that directly or
27178 indirectly initialized one or more of these variables. This is the situation
27179 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
27180 a warning that suggests this addition if it detects this situation.
27181
27182 The @code{gnatbind}
27183 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
27184 out problems. This switch causes bodies to be elaborated as late as possible
27185 instead of as early as possible. In the example above, it would have forced
27186 the choice of the first elaboration order. If you get different results
27187 when using this switch, and particularly if one set of results is right,
27188 and one is wrong as far as you are concerned, it shows that you have some
27189 missing @code{Elaborate} pragmas. For the example above, we have the
27190 following output:
27191
27192 @smallexample
27193 gnatmake -f -q main
27194 main
27195  7
27196 gnatmake -f -q main -bargs -p
27197 main
27198  0
27199 @end smallexample
27200
27201 @noindent
27202 It is of course quite unlikely that both these results are correct, so
27203 it is up to you in a case like this to investigate the source of the
27204 difference, by looking at the two elaboration orders that are chosen,
27205 and figuring out which is correct, and then adding the necessary
27206 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
27207
27208 @node Inline Assembler
27209 @appendix Inline Assembler
27210
27211 @noindent
27212 If you need to write low-level software that interacts directly
27213 with the hardware, Ada provides two ways to incorporate assembly
27214 language code into your program.  First, you can import and invoke
27215 external routines written in assembly language, an Ada feature fully
27216 supported by GNAT@.  However, for small sections of code it may be simpler
27217 or more efficient to include assembly language statements directly
27218 in your Ada source program, using the facilities of the implementation-defined
27219 package @code{System.Machine_Code}, which incorporates the gcc
27220 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
27221 including the following:
27222
27223 @itemize @bullet
27224 @item No need to use non-Ada tools
27225 @item Consistent interface over different targets
27226 @item Automatic usage of the proper calling conventions
27227 @item Access to Ada constants and variables
27228 @item Definition of intrinsic routines
27229 @item Possibility of inlining a subprogram comprising assembler code
27230 @item Code optimizer can take Inline Assembler code into account
27231 @end itemize
27232
27233 This chapter presents a series of examples to show you how to use
27234 the Inline Assembler.  Although it focuses on the Intel x86,
27235 the general approach applies also to other processors.
27236 It is assumed that you are familiar with Ada
27237 and with assembly language programming.
27238
27239 @menu
27240 * Basic Assembler Syntax::
27241 * A Simple Example of Inline Assembler::
27242 * Output Variables in Inline Assembler::
27243 * Input Variables in Inline Assembler::
27244 * Inlining Inline Assembler Code::
27245 * Other Asm Functionality::
27246 @end menu
27247
27248 @c ---------------------------------------------------------------------------
27249 @node Basic Assembler Syntax
27250 @section Basic Assembler Syntax
27251
27252 @noindent
27253 The assembler used by GNAT and gcc is based not on the Intel assembly
27254 language, but rather on a language that descends from the AT&T Unix
27255 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
27256 The following table summarizes the main features of @emph{as} syntax
27257 and points out the differences from the Intel conventions.
27258 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
27259 pre-processor) documentation for further information.
27260
27261 @table @asis
27262 @item Register names
27263 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
27264 @*
27265 Intel: No extra punctuation; for example @code{eax}
27266
27267 @item Immediate operand
27268 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
27269 @*
27270 Intel: No extra punctuation; for example @code{4}
27271
27272 @item Address
27273 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
27274 @*
27275 Intel: No extra punctuation; for example @code{loc}
27276
27277 @item Memory contents
27278 gcc / @emph{as}: No extra punctuation; for example @code{loc}
27279 @*
27280 Intel: Square brackets; for example @code{[loc]}
27281
27282 @item Register contents
27283 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
27284 @*
27285 Intel: Square brackets; for example @code{[eax]}
27286
27287 @item Hexadecimal numbers
27288 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
27289 @*
27290 Intel: Trailing ``h''; for example @code{A0h}
27291
27292 @item Operand size
27293 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
27294 a 16-bit word
27295 @*
27296 Intel: Implicit, deduced by assembler; for example @code{mov}
27297
27298 @item Instruction repetition
27299 gcc / @emph{as}: Split into two lines; for example
27300 @*
27301 @code{rep}
27302 @*
27303 @code{stosl}
27304 @*
27305 Intel: Keep on one line; for example @code{rep stosl}
27306
27307 @item Order of operands
27308 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
27309 @*
27310 Intel: Destination first; for example @code{mov eax, 4}
27311 @end table
27312
27313 @c ---------------------------------------------------------------------------
27314 @node A Simple Example of Inline Assembler
27315 @section A Simple Example of Inline Assembler
27316
27317 @noindent
27318 The following example will generate a single assembly language statement,
27319 @code{nop}, which does nothing.  Despite its lack of run-time effect,
27320 the example will be useful in illustrating the basics of
27321 the Inline Assembler facility.
27322
27323 @smallexample @c ada
27324 @group
27325 with System.Machine_Code; use System.Machine_Code;
27326 procedure Nothing is
27327 begin
27328    Asm ("nop");
27329 end Nothing;
27330 @end group
27331 @end smallexample
27332
27333 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
27334 here it takes one parameter, a @emph{template string} that must be a static
27335 expression and that will form the generated instruction.
27336 @code{Asm} may be regarded as a compile-time procedure that parses
27337 the template string and additional parameters (none here),
27338 from which it generates a sequence of assembly language instructions.
27339
27340 The examples in this chapter will illustrate several of the forms
27341 for invoking @code{Asm}; a complete specification of the syntax
27342 is found in the @cite{GNAT Reference Manual}.
27343
27344 Under the standard GNAT conventions, the @code{Nothing} procedure
27345 should be in a file named @file{nothing.adb}.
27346 You can build the executable in the usual way:
27347 @smallexample
27348 gnatmake nothing
27349 @end smallexample
27350 However, the interesting aspect of this example is not its run-time behavior
27351 but rather the generated assembly code.
27352 To see this output, invoke the compiler as follows:
27353 @smallexample
27354    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
27355 @end smallexample
27356 where the options are:
27357
27358 @table @code
27359 @item -c
27360 compile only (no bind or link)
27361 @item -S
27362 generate assembler listing
27363 @item -fomit-frame-pointer
27364 do not set up separate stack frames
27365 @item -gnatp
27366 do not add runtime checks
27367 @end table
27368
27369 This gives a human-readable assembler version of the code. The resulting
27370 file will have the same name as the Ada source file, but with a @code{.s}
27371 extension. In our example, the file @file{nothing.s} has the following
27372 contents:
27373
27374 @smallexample
27375 @group
27376 .file "nothing.adb"
27377 gcc2_compiled.:
27378 ___gnu_compiled_ada:
27379 .text
27380    .align 4
27381 .globl __ada_nothing
27382 __ada_nothing:
27383 #APP
27384    nop
27385 #NO_APP
27386    jmp L1
27387    .align 2,0x90
27388 L1:
27389    ret
27390 @end group
27391 @end smallexample
27392
27393 The assembly code you included is clearly indicated by
27394 the compiler, between the @code{#APP} and @code{#NO_APP}
27395 delimiters. The character before the 'APP' and 'NOAPP'
27396 can differ on different targets. For example, GNU/Linux uses '#APP' while
27397 on NT you will see '/APP'.
27398
27399 If you make a mistake in your assembler code (such as using the
27400 wrong size modifier, or using a wrong operand for the instruction) GNAT
27401 will report this error in a temporary file, which will be deleted when
27402 the compilation is finished.  Generating an assembler file will help
27403 in such cases, since you can assemble this file separately using the
27404 @emph{as} assembler that comes with gcc.
27405
27406 Assembling the file using the command
27407
27408 @smallexample
27409 as @file{nothing.s}
27410 @end smallexample
27411 @noindent
27412 will give you error messages whose lines correspond to the assembler
27413 input file, so you can easily find and correct any mistakes you made.
27414 If there are no errors, @emph{as} will generate an object file
27415 @file{nothing.out}.
27416
27417 @c ---------------------------------------------------------------------------
27418 @node Output Variables in Inline Assembler
27419 @section Output Variables in Inline Assembler
27420
27421 @noindent
27422 The examples in this section, showing how to access the processor flags,
27423 illustrate how to specify the destination operands for assembly language
27424 statements.
27425
27426 @smallexample @c ada
27427 @group
27428 with Interfaces; use Interfaces;
27429 with Ada.Text_IO; use Ada.Text_IO;
27430 with System.Machine_Code; use System.Machine_Code;
27431 procedure Get_Flags is
27432    Flags : Unsigned_32;
27433    use ASCII;
27434 begin
27435    Asm ("pushfl"          & LF & HT & -- push flags on stack
27436         "popl %%eax"      & LF & HT & -- load eax with flags
27437         "movl %%eax, %0",             -- store flags in variable
27438         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27439    Put_Line ("Flags register:" & Flags'Img);
27440 end Get_Flags;
27441 @end group
27442 @end smallexample
27443
27444 In order to have a nicely aligned assembly listing, we have separated
27445 multiple assembler statements in the Asm template string with linefeed
27446 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
27447 The resulting section of the assembly output file is:
27448
27449 @smallexample
27450 @group
27451 #APP
27452    pushfl
27453    popl %eax
27454    movl %eax, -40(%ebp)
27455 #NO_APP
27456 @end group
27457 @end smallexample
27458
27459 It would have been legal to write the Asm invocation as:
27460
27461 @smallexample
27462 Asm ("pushfl popl %%eax movl %%eax, %0")
27463 @end smallexample
27464
27465 but in the generated assembler file, this would come out as:
27466
27467 @smallexample
27468 #APP
27469    pushfl popl %eax movl %eax, -40(%ebp)
27470 #NO_APP
27471 @end smallexample
27472
27473 which is not so convenient for the human reader.
27474
27475 We use Ada comments
27476 at the end of each line to explain what the assembler instructions
27477 actually do.  This is a useful convention.
27478
27479 When writing Inline Assembler instructions, you need to precede each register
27480 and variable name with a percent sign.  Since the assembler already requires
27481 a percent sign at the beginning of a register name, you need two consecutive
27482 percent signs for such names in the Asm template string, thus @code{%%eax}.
27483 In the generated assembly code, one of the percent signs will be stripped off.
27484
27485 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
27486 variables: operands you later define using @code{Input} or @code{Output}
27487 parameters to @code{Asm}.
27488 An output variable is illustrated in
27489 the third statement in the Asm template string:
27490 @smallexample
27491 movl %%eax, %0
27492 @end smallexample
27493 The intent is to store the contents of the eax register in a variable that can
27494 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
27495 necessarily work, since the compiler might optimize by using a register
27496 to hold Flags, and the expansion of the @code{movl} instruction would not be
27497 aware of this optimization.  The solution is not to store the result directly
27498 but rather to advise the compiler to choose the correct operand form;
27499 that is the purpose of the @code{%0} output variable.
27500
27501 Information about the output variable is supplied in the @code{Outputs}
27502 parameter to @code{Asm}:
27503 @smallexample
27504 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27505 @end smallexample
27506
27507 The output is defined by the @code{Asm_Output} attribute of the target type;
27508 the general format is
27509 @smallexample
27510 Type'Asm_Output (constraint_string, variable_name)
27511 @end smallexample
27512
27513 The constraint string directs the compiler how
27514 to store/access the associated variable.  In the example
27515 @smallexample
27516 Unsigned_32'Asm_Output ("=m", Flags);
27517 @end smallexample
27518 the @code{"m"} (memory) constraint tells the compiler that the variable
27519 @code{Flags} should be stored in a memory variable, thus preventing
27520 the optimizer from keeping it in a register.  In contrast,
27521 @smallexample
27522 Unsigned_32'Asm_Output ("=r", Flags);
27523 @end smallexample
27524 uses the @code{"r"} (register) constraint, telling the compiler to
27525 store the variable in a register.
27526
27527 If the constraint is preceded by the equal character (@strong{=}), it tells
27528 the compiler that the variable will be used to store data into it.
27529
27530 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
27531 allowing the optimizer to choose whatever it deems best.
27532
27533 There are a fairly large number of constraints, but the ones that are
27534 most useful (for the Intel x86 processor) are the following:
27535
27536 @table @code
27537 @item =
27538 output constraint
27539 @item g
27540 global (i.e. can be stored anywhere)
27541 @item m
27542 in memory
27543 @item I
27544 a constant
27545 @item a
27546 use eax
27547 @item b
27548 use ebx
27549 @item c
27550 use ecx
27551 @item d
27552 use edx
27553 @item S
27554 use esi
27555 @item D
27556 use edi
27557 @item r
27558 use one of eax, ebx, ecx or edx
27559 @item q
27560 use one of eax, ebx, ecx, edx, esi or edi
27561 @end table
27562
27563 The full set of constraints is described in the gcc and @emph{as}
27564 documentation; note that it is possible to combine certain constraints
27565 in one constraint string.
27566
27567 You specify the association of an output variable with an assembler operand
27568 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
27569 integer.  Thus in
27570 @smallexample @c ada
27571 @group
27572 Asm ("pushfl"          & LF & HT & -- push flags on stack
27573      "popl %%eax"      & LF & HT & -- load eax with flags
27574      "movl %%eax, %0",             -- store flags in variable
27575      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27576 @end group
27577 @end smallexample
27578 @noindent
27579 @code{%0} will be replaced in the expanded code by the appropriate operand,
27580 whatever
27581 the compiler decided for the @code{Flags} variable.
27582
27583 In general, you may have any number of output variables:
27584 @itemize @bullet
27585 @item
27586 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
27587 @item
27588 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
27589 of @code{Asm_Output} attributes
27590 @end itemize
27591
27592 For example:
27593 @smallexample @c ada
27594 @group
27595 Asm ("movl %%eax, %0" & LF & HT &
27596      "movl %%ebx, %1" & LF & HT &
27597      "movl %%ecx, %2",
27598      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
27599                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
27600                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
27601 @end group
27602 @end smallexample
27603 @noindent
27604 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
27605 in the Ada program.
27606
27607 As a variation on the @code{Get_Flags} example, we can use the constraints
27608 string to direct the compiler to store the eax register into the @code{Flags}
27609 variable, instead of including the store instruction explicitly in the
27610 @code{Asm} template string:
27611
27612 @smallexample @c ada
27613 @group
27614 with Interfaces; use Interfaces;
27615 with Ada.Text_IO; use Ada.Text_IO;
27616 with System.Machine_Code; use System.Machine_Code;
27617 procedure Get_Flags_2 is
27618    Flags : Unsigned_32;
27619    use ASCII;
27620 begin
27621    Asm ("pushfl"      & LF & HT & -- push flags on stack
27622         "popl %%eax",             -- save flags in eax
27623         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
27624    Put_Line ("Flags register:" & Flags'Img);
27625 end Get_Flags_2;
27626 @end group
27627 @end smallexample
27628
27629 @noindent
27630 The @code{"a"} constraint tells the compiler that the @code{Flags}
27631 variable will come from the eax register. Here is the resulting code:
27632
27633 @smallexample
27634 @group
27635 #APP
27636    pushfl
27637    popl %eax
27638 #NO_APP
27639    movl %eax,-40(%ebp)
27640 @end group
27641 @end smallexample
27642
27643 @noindent
27644 The compiler generated the store of eax into Flags after
27645 expanding the assembler code.
27646
27647 Actually, there was no need to pop the flags into the eax register;
27648 more simply, we could just pop the flags directly into the program variable:
27649
27650 @smallexample @c ada
27651 @group
27652 with Interfaces; use Interfaces;
27653 with Ada.Text_IO; use Ada.Text_IO;
27654 with System.Machine_Code; use System.Machine_Code;
27655 procedure Get_Flags_3 is
27656    Flags : Unsigned_32;
27657    use ASCII;
27658 begin
27659    Asm ("pushfl"  & LF & HT & -- push flags on stack
27660         "pop %0",             -- save flags in Flags
27661         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27662    Put_Line ("Flags register:" & Flags'Img);
27663 end Get_Flags_3;
27664 @end group
27665 @end smallexample
27666
27667 @c ---------------------------------------------------------------------------
27668 @node Input Variables in Inline Assembler
27669 @section Input Variables in Inline Assembler
27670
27671 @noindent
27672 The example in this section illustrates how to specify the source operands
27673 for assembly language statements.
27674 The program simply increments its input value by 1:
27675
27676 @smallexample @c ada
27677 @group
27678 with Interfaces; use Interfaces;
27679 with Ada.Text_IO; use Ada.Text_IO;
27680 with System.Machine_Code; use System.Machine_Code;
27681 procedure Increment is
27682
27683    function Incr (Value : Unsigned_32) return Unsigned_32 is
27684       Result : Unsigned_32;
27685    begin
27686       Asm ("incl %0",
27687            Inputs  => Unsigned_32'Asm_Input ("a", Value),
27688            Outputs => Unsigned_32'Asm_Output ("=a", Result));
27689       return Result;
27690    end Incr;
27691
27692    Value : Unsigned_32;
27693
27694 begin
27695    Value := 5;
27696    Put_Line ("Value before is" & Value'Img);
27697    Value := Incr (Value);
27698    Put_Line ("Value after is" & Value'Img);
27699 end Increment;
27700 @end group
27701 @end smallexample
27702
27703 The @code{Outputs} parameter to @code{Asm} specifies
27704 that the result will be in the eax register and that it is to be stored
27705 in the @code{Result} variable.
27706
27707 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
27708 but with an @code{Asm_Input} attribute.
27709 The @code{"="} constraint, indicating an output value, is not present.
27710
27711 You can have multiple input variables, in the same way that you can have more
27712 than one output variable.
27713
27714 The parameter count (%0, %1) etc, now starts at the first input
27715 statement, and continues with the output statements.
27716 When both parameters use the same variable, the
27717 compiler will treat them as the same %n operand, which is the case here.
27718
27719 Just as the @code{Outputs} parameter causes the register to be stored into the
27720 target variable after execution of the assembler statements, so does the
27721 @code{Inputs} parameter cause its variable to be loaded into the register
27722 before execution of the assembler statements.
27723
27724 Thus the effect of the @code{Asm} invocation is:
27725 @enumerate
27726 @item load the 32-bit value of @code{Value} into eax
27727 @item execute the @code{incl %eax} instruction
27728 @item store the contents of eax into the @code{Result} variable
27729 @end enumerate
27730
27731 The resulting assembler file (with @option{-O2} optimization) contains:
27732 @smallexample
27733 @group
27734 _increment__incr.1:
27735    subl $4,%esp
27736    movl 8(%esp),%eax
27737 #APP
27738    incl %eax
27739 #NO_APP
27740    movl %eax,%edx
27741    movl %ecx,(%esp)
27742    addl $4,%esp
27743    ret
27744 @end group
27745 @end smallexample
27746
27747 @c ---------------------------------------------------------------------------
27748 @node Inlining Inline Assembler Code
27749 @section Inlining Inline Assembler Code
27750
27751 @noindent
27752 For a short subprogram such as the @code{Incr} function in the previous
27753 section, the overhead of the call and return (creating / deleting the stack
27754 frame) can be significant, compared to the amount of code in the subprogram
27755 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
27756 which directs the compiler to expand invocations of the subprogram at the
27757 point(s) of call, instead of setting up a stack frame for out-of-line calls.
27758 Here is the resulting program:
27759
27760 @smallexample @c ada
27761 @group
27762 with Interfaces; use Interfaces;
27763 with Ada.Text_IO; use Ada.Text_IO;
27764 with System.Machine_Code; use System.Machine_Code;
27765 procedure Increment_2 is
27766
27767    function Incr (Value : Unsigned_32) return Unsigned_32 is
27768       Result : Unsigned_32;
27769    begin
27770       Asm ("incl %0",
27771            Inputs  => Unsigned_32'Asm_Input ("a", Value),
27772            Outputs => Unsigned_32'Asm_Output ("=a", Result));
27773       return Result;
27774    end Incr;
27775    pragma Inline (Increment);
27776
27777    Value : Unsigned_32;
27778
27779 begin
27780    Value := 5;
27781    Put_Line ("Value before is" & Value'Img);
27782    Value := Increment (Value);
27783    Put_Line ("Value after is" & Value'Img);
27784 end Increment_2;
27785 @end group
27786 @end smallexample
27787
27788 Compile the program with both optimization (@option{-O2}) and inlining
27789 enabled (@option{-gnatpn} instead of @option{-gnatp}).
27790
27791 The @code{Incr} function is still compiled as usual, but at the
27792 point in @code{Increment} where our function used to be called:
27793
27794 @smallexample
27795 @group
27796 pushl %edi
27797 call _increment__incr.1
27798 @end group
27799 @end smallexample
27800
27801 @noindent
27802 the code for the function body directly appears:
27803
27804 @smallexample
27805 @group
27806 movl %esi,%eax
27807 #APP
27808    incl %eax
27809 #NO_APP
27810    movl %eax,%edx
27811 @end group
27812 @end smallexample
27813
27814 @noindent
27815 thus saving the overhead of stack frame setup and an out-of-line call.
27816
27817 @c ---------------------------------------------------------------------------
27818 @node Other Asm Functionality
27819 @section Other @code{Asm} Functionality
27820
27821 @noindent
27822 This section describes two important parameters to the @code{Asm}
27823 procedure: @code{Clobber}, which identifies register usage;
27824 and @code{Volatile}, which inhibits unwanted optimizations.
27825
27826 @menu
27827 * The Clobber Parameter::
27828 * The Volatile Parameter::
27829 @end menu
27830
27831 @c ---------------------------------------------------------------------------
27832 @node The Clobber Parameter
27833 @subsection The @code{Clobber} Parameter
27834
27835 @noindent
27836 One of the dangers of intermixing assembly language and a compiled language
27837 such as Ada is that the compiler needs to be aware of which registers are
27838 being used by the assembly code.  In some cases, such as the earlier examples,
27839 the constraint string is sufficient to indicate register usage (e.g.,
27840 @code{"a"} for
27841 the eax register).  But more generally, the compiler needs an explicit
27842 identification of the registers that are used by the Inline Assembly
27843 statements.
27844
27845 Using a register that the compiler doesn't know about
27846 could be a side effect of an instruction (like @code{mull}
27847 storing its result in both eax and edx).
27848 It can also arise from explicit register usage in your
27849 assembly code; for example:
27850 @smallexample
27851 @group
27852 Asm ("movl %0, %%ebx" & LF & HT &
27853      "movl %%ebx, %1",
27854      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
27855      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
27856 @end group
27857 @end smallexample
27858 @noindent
27859 where the compiler (since it does not analyze the @code{Asm} template string)
27860 does not know you are using the ebx register.
27861
27862 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
27863 to identify the registers that will be used by your assembly code:
27864
27865 @smallexample
27866 @group
27867 Asm ("movl %0, %%ebx" & LF & HT &
27868      "movl %%ebx, %1",
27869      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
27870      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
27871      Clobber => "ebx");
27872 @end group
27873 @end smallexample
27874
27875 The Clobber parameter is a static string expression specifying the
27876 register(s) you are using.  Note that register names are @emph{not} prefixed
27877 by a percent sign. Also, if more than one register is used then their names
27878 are separated by commas; e.g., @code{"eax, ebx"}
27879
27880 The @code{Clobber} parameter has several additional uses:
27881 @enumerate
27882 @item Use ``register'' name @code{cc} to indicate that flags might have changed
27883 @item Use ``register'' name @code{memory} if you changed a memory location
27884 @end enumerate
27885
27886 @c ---------------------------------------------------------------------------
27887 @node The Volatile Parameter
27888 @subsection The @code{Volatile} Parameter
27889 @cindex Volatile parameter
27890
27891 @noindent
27892 Compiler optimizations in the presence of Inline Assembler may sometimes have
27893 unwanted effects.  For example, when an @code{Asm} invocation with an input
27894 variable is inside a loop, the compiler might move the loading of the input
27895 variable outside the loop, regarding it as a one-time initialization.
27896
27897 If this effect is not desired, you can disable such optimizations by setting
27898 the @code{Volatile} parameter to @code{True}; for example:
27899
27900 @smallexample @c ada
27901 @group
27902 Asm ("movl %0, %%ebx" & LF & HT &
27903      "movl %%ebx, %1",
27904      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
27905      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
27906      Clobber  => "ebx",
27907      Volatile => True);
27908 @end group
27909 @end smallexample
27910
27911 By default, @code{Volatile} is set to @code{False} unless there is no
27912 @code{Outputs} parameter.
27913
27914 Although setting @code{Volatile} to @code{True} prevents unwanted
27915 optimizations, it will also disable other optimizations that might be
27916 important for efficiency. In general, you should set @code{Volatile}
27917 to @code{True} only if the compiler's optimizations have created
27918 problems.
27919 @c END OF INLINE ASSEMBLER CHAPTER
27920 @c ===============================
27921
27922 @c ***********************************
27923 @c * Compatibility and Porting Guide *
27924 @c ***********************************
27925 @node Compatibility and Porting Guide
27926 @appendix Compatibility and Porting Guide
27927
27928 @noindent
27929 This chapter describes the compatibility issues that may arise between
27930 GNAT and other Ada compilation systems (including those for Ada 83),
27931 and shows how GNAT can expedite porting
27932 applications developed in other Ada environments.
27933
27934 @menu
27935 * Compatibility with Ada 83::
27936 * Compatibility between Ada 95 and Ada 2005::
27937 * Implementation-dependent characteristics::
27938 * Compatibility with Other Ada Systems::
27939 * Representation Clauses::
27940 @ifclear vms
27941 @c Brief section is only in non-VMS version
27942 @c Full chapter is in VMS version
27943 * Compatibility with HP Ada 83::
27944 @end ifclear
27945 @ifset vms
27946 * Transitioning to 64-Bit GNAT for OpenVMS::
27947 @end ifset
27948 @end menu
27949
27950 @node Compatibility with Ada 83
27951 @section Compatibility with Ada 83
27952 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
27953
27954 @noindent
27955 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
27956 particular, the design intention was that the difficulties associated
27957 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
27958 that occur when moving from one Ada 83 system to another.
27959
27960 However, there are a number of points at which there are minor
27961 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
27962 full details of these issues,
27963 and should be consulted for a complete treatment.
27964 In practice the
27965 following subsections treat the most likely issues to be encountered.
27966
27967 @menu
27968 * Legal Ada 83 programs that are illegal in Ada 95::
27969 * More deterministic semantics::
27970 * Changed semantics::
27971 * Other language compatibility issues::
27972 @end menu
27973
27974 @node Legal Ada 83 programs that are illegal in Ada 95
27975 @subsection Legal Ada 83 programs that are illegal in Ada 95
27976
27977 Some legal Ada 83 programs are illegal (i.e. they will fail to compile) in
27978 Ada 95 and thus also in Ada 2005:
27979
27980 @table @emph
27981 @item Character literals
27982 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
27983 @code{Wide_Character} as a new predefined character type, some uses of
27984 character literals that were legal in Ada 83 are illegal in Ada 95.
27985 For example:
27986 @smallexample @c ada
27987    for Char in 'A' .. 'Z' loop ... end loop;
27988 @end smallexample
27989
27990 @noindent
27991 The problem is that @code{'A'} and @code{'Z'} could be from either
27992 @code{Character} or @code{Wide_Character}.  The simplest correction
27993 is to make the type explicit; e.g.:
27994 @smallexample @c ada
27995    for Char in Character range 'A' .. 'Z' loop ... end loop;
27996 @end smallexample
27997
27998 @item New reserved words
27999 The identifiers @code{abstract}, @code{aliased}, @code{protected},
28000 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
28001 Existing Ada 83 code using any of these identifiers must be edited to
28002 use some alternative name.
28003
28004 @item Freezing rules
28005 The rules in Ada 95 are slightly different with regard to the point at
28006 which entities are frozen, and representation pragmas and clauses are
28007 not permitted past the freeze point.  This shows up most typically in
28008 the form of an error message complaining that a representation item
28009 appears too late, and the appropriate corrective action is to move
28010 the item nearer to the declaration of the entity to which it refers.
28011
28012 A particular case is that representation pragmas
28013 @ifset vms
28014 (including the
28015 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
28016 @end ifset
28017 cannot be applied to a subprogram body.  If necessary, a separate subprogram
28018 declaration must be introduced to which the pragma can be applied.
28019
28020 @item Optional bodies for library packages
28021 In Ada 83, a package that did not require a package body was nevertheless
28022 allowed to have one.  This lead to certain surprises in compiling large
28023 systems (situations in which the body could be unexpectedly ignored by the
28024 binder).  In Ada 95, if a package does not require a body then it is not
28025 permitted to have a body.  To fix this problem, simply remove a redundant
28026 body if it is empty, or, if it is non-empty, introduce a dummy declaration
28027 into the spec that makes the body required.  One approach is to add a private
28028 part to the package declaration (if necessary), and define a parameterless
28029 procedure called @code{Requires_Body}, which must then be given a dummy
28030 procedure body in the package body, which then becomes required.
28031 Another approach (assuming that this does not introduce elaboration
28032 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
28033 since one effect of this pragma is to require the presence of a package body.
28034
28035 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
28036 In Ada 95, the exception @code{Numeric_Error} is a renaming of
28037 @code{Constraint_Error}.
28038 This means that it is illegal to have separate exception handlers for
28039 the two exceptions.  The fix is simply to remove the handler for the
28040 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
28041 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
28042
28043 @item Indefinite subtypes in generics
28044 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
28045 as the actual for a generic formal private type, but then the instantiation
28046 would be illegal if there were any instances of declarations of variables
28047 of this type in the generic body.  In Ada 95, to avoid this clear violation
28048 of the methodological principle known as the ``contract model'',
28049 the generic declaration explicitly indicates whether
28050 or not such instantiations are permitted.  If a generic formal parameter
28051 has explicit unknown discriminants, indicated by using @code{(<>)} after the
28052 type name, then it can be instantiated with indefinite types, but no
28053 stand-alone variables can be declared of this type.  Any attempt to declare
28054 such a variable will result in an illegality at the time the generic is
28055 declared.  If the @code{(<>)} notation is not used, then it is illegal
28056 to instantiate the generic with an indefinite type.
28057 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
28058 It will show up as a compile time error, and
28059 the fix is usually simply to add the @code{(<>)} to the generic declaration.
28060 @end table
28061
28062 @node More deterministic semantics
28063 @subsection More deterministic semantics
28064
28065 @table @emph
28066 @item Conversions
28067 Conversions from real types to integer types round away from 0.  In Ada 83
28068 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
28069 implementation freedom was intended to support unbiased rounding in
28070 statistical applications, but in practice it interfered with portability.
28071 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
28072 is required.  Numeric code may be affected by this change in semantics.
28073 Note, though, that this issue is no worse than already existed in Ada 83
28074 when porting code from one vendor to another.
28075
28076 @item Tasking
28077 The Real-Time Annex introduces a set of policies that define the behavior of
28078 features that were implementation dependent in Ada 83, such as the order in
28079 which open select branches are executed.
28080 @end table
28081
28082 @node Changed semantics
28083 @subsection Changed semantics
28084
28085 @noindent
28086 The worst kind of incompatibility is one where a program that is legal in
28087 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
28088 possible in Ada 83.  Fortunately this is extremely rare, but the one
28089 situation that you should be alert to is the change in the predefined type
28090 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
28091
28092 @table @emph
28093 @item Range of type @code{Character}
28094 The range of @code{Standard.Character} is now the full 256 characters
28095 of Latin-1, whereas in most Ada 83 implementations it was restricted
28096 to 128 characters. Although some of the effects of
28097 this change will be manifest in compile-time rejection of legal
28098 Ada 83 programs it is possible for a working Ada 83 program to have
28099 a different effect in Ada 95, one that was not permitted in Ada 83.
28100 As an example, the expression
28101 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
28102 delivers @code{255} as its value.
28103 In general, you should look at the logic of any
28104 character-processing Ada 83 program and see whether it needs to be adapted
28105 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
28106 character handling package that may be relevant if code needs to be adapted
28107 to account for the additional Latin-1 elements.
28108 The desirable fix is to
28109 modify the program to accommodate the full character set, but in some cases
28110 it may be convenient to define a subtype or derived type of Character that
28111 covers only the restricted range.
28112 @cindex Latin-1
28113 @end table
28114
28115 @node Other language compatibility issues
28116 @subsection Other language compatibility issues
28117
28118 @table @emph
28119 @item @option{-gnat83} switch
28120 All implementations of GNAT provide a switch that causes GNAT to operate
28121 in Ada 83 mode.  In this mode, some but not all compatibility problems
28122 of the type described above are handled automatically.  For example, the
28123 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
28124 as identifiers as in Ada 83.
28125 However,
28126 in practice, it is usually advisable to make the necessary modifications
28127 to the program to remove the need for using this switch.
28128 See @ref{Compiling Different Versions of Ada}.
28129
28130 @item Support for removed Ada 83 pragmas and attributes
28131 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
28132 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
28133 compilers are allowed, but not required, to implement these missing
28134 elements.  In contrast with some other compilers, GNAT implements all
28135 such pragmas and attributes, eliminating this compatibility concern.  These
28136 include @code{pragma Interface} and the floating point type attributes
28137 (@code{Emax}, @code{Mantissa}, etc.), among other items.
28138 @end table
28139
28140
28141 @node Compatibility between Ada 95 and Ada 2005
28142 @section Compatibility between Ada 95 and Ada 2005
28143 @cindex Compatibility between Ada 95 and Ada 2005
28144
28145 @noindent
28146 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
28147 a number of incompatibilities. Several are enumerated below;
28148 for a complete description please see the
28149 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
28150 @cite{Rationale for Ada 2005}.
28151
28152 @table @emph
28153 @item New reserved words.
28154 The words @code{interface}, @code{overriding} and @code{synchronized} are
28155 reserved in Ada 2005.
28156 A pre-Ada 2005 program that uses any of these as an identifier will be
28157 illegal.
28158
28159 @item New declarations in predefined packages.
28160 A number of packages in the predefined environment contain new declarations:
28161 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
28162 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
28163 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
28164 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
28165 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
28166 If an Ada 95 program does a @code{with} and @code{use} of any of these
28167 packages, the new declarations may cause name clashes.
28168
28169 @item Access parameters.
28170 A nondispatching subprogram with an access parameter cannot be renamed
28171 as a dispatching operation.  This was permitted in Ada 95.
28172
28173 @item Access types, discriminants, and constraints.
28174 Rule changes in this area have led to some incompatibilities; for example,
28175 constrained subtypes of some access types are not permitted in Ada 2005.
28176
28177 @item Aggregates for limited types.
28178 The allowance of aggregates for limited types in Ada 2005 raises the
28179 possibility of ambiguities in legal Ada 95 programs, since additional types
28180 now need to be considered in expression resolution.
28181
28182 @item Fixed-point multiplication and division.
28183 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
28184 were legal in Ada 95 and invoked the predefined versions of these operations,
28185 are now ambiguous.
28186 The ambiguity may be resolved either by applying a type conversion to the
28187 expression, or by explicitly invoking the operation from package
28188 @code{Standard}.
28189
28190 @item Return-by-reference types.
28191 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
28192 can declare a function returning a value from an anonymous access type.
28193 @end table
28194
28195
28196 @node Implementation-dependent characteristics
28197 @section Implementation-dependent characteristics
28198 @noindent
28199 Although the Ada language defines the semantics of each construct as
28200 precisely as practical, in some situations (for example for reasons of
28201 efficiency, or where the effect is heavily dependent on the host or target
28202 platform) the implementation is allowed some freedom.  In porting Ada 83
28203 code to GNAT, you need to be aware of whether / how the existing code
28204 exercised such implementation dependencies.  Such characteristics fall into
28205 several categories, and GNAT offers specific support in assisting the
28206 transition from certain Ada 83 compilers.
28207
28208 @menu
28209 * Implementation-defined pragmas::
28210 * Implementation-defined attributes::
28211 * Libraries::
28212 * Elaboration order::
28213 * Target-specific aspects::
28214 @end menu
28215
28216 @node Implementation-defined pragmas
28217 @subsection Implementation-defined pragmas
28218
28219 @noindent
28220 Ada compilers are allowed to supplement the language-defined pragmas, and
28221 these are a potential source of non-portability.  All GNAT-defined pragmas
28222 are described in the GNAT Reference Manual, and these include several that
28223 are specifically intended to correspond to other vendors' Ada 83 pragmas.
28224 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
28225 For
28226 compatibility with HP Ada 83, GNAT supplies the pragmas
28227 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
28228 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
28229 and @code{Volatile}.
28230 Other relevant pragmas include @code{External} and @code{Link_With}.
28231 Some vendor-specific
28232 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
28233 recognized, thus
28234 avoiding compiler rejection of units that contain such pragmas; they are not
28235 relevant in a GNAT context and hence are not otherwise implemented.
28236
28237 @node Implementation-defined attributes
28238 @subsection Implementation-defined attributes
28239
28240 Analogous to pragmas, the set of attributes may be extended by an
28241 implementation.  All GNAT-defined attributes are described in the
28242 @cite{GNAT Reference Manual}, and these include several that are specifically
28243 intended
28244 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
28245 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
28246 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
28247 @code{Type_Class}.
28248
28249 @node Libraries
28250 @subsection Libraries
28251 @noindent
28252 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
28253 code uses vendor-specific libraries then there are several ways to manage
28254 this in Ada 95 or Ada 2005:
28255 @enumerate
28256 @item
28257 If the source code for the libraries (specifications and bodies) are
28258 available, then the libraries can be migrated in the same way as the
28259 application.
28260 @item
28261 If the source code for the specifications but not the bodies are
28262 available, then you can reimplement the bodies.
28263 @item
28264 Some features introduced by Ada 95 obviate the need for library support.  For
28265 example most Ada 83 vendors supplied a package for unsigned integers.  The
28266 Ada 95 modular type feature is the preferred way to handle this need, so
28267 instead of migrating or reimplementing the unsigned integer package it may
28268 be preferable to retrofit the application using modular types.
28269 @end enumerate
28270
28271 @node Elaboration order
28272 @subsection Elaboration order
28273 @noindent
28274 The implementation can choose any elaboration order consistent with the unit
28275 dependency relationship.  This freedom means that some orders can result in
28276 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
28277 to invoke a subprogram its body has been elaborated, or to instantiate a
28278 generic before the generic body has been elaborated.  By default GNAT
28279 attempts to choose a safe order (one that will not encounter access before
28280 elaboration problems) by implicitly inserting @code{Elaborate} or
28281 @code{Elaborate_All} pragmas where
28282 needed.  However, this can lead to the creation of elaboration circularities
28283 and a resulting rejection of the program by gnatbind.  This issue is
28284 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
28285 In brief, there are several
28286 ways to deal with this situation:
28287
28288 @itemize @bullet
28289 @item
28290 Modify the program to eliminate the circularities, e.g. by moving
28291 elaboration-time code into explicitly-invoked procedures
28292 @item
28293 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
28294 @code{Elaborate} pragmas, and then inhibit the generation of implicit
28295 @code{Elaborate_All}
28296 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
28297 (by selectively suppressing elaboration checks via pragma
28298 @code{Suppress(Elaboration_Check)} when it is safe to do so).
28299 @end itemize
28300
28301 @node Target-specific aspects
28302 @subsection Target-specific aspects
28303 @noindent
28304 Low-level applications need to deal with machine addresses, data
28305 representations, interfacing with assembler code, and similar issues.  If
28306 such an Ada 83 application is being ported to different target hardware (for
28307 example where the byte endianness has changed) then you will need to
28308 carefully examine the program logic; the porting effort will heavily depend
28309 on the robustness of the original design.  Moreover, Ada 95 (and thus
28310 Ada 2005) are sometimes
28311 incompatible with typical Ada 83 compiler practices regarding implicit
28312 packing, the meaning of the Size attribute, and the size of access values.
28313 GNAT's approach to these issues is described in @ref{Representation Clauses}.
28314
28315 @node Compatibility with Other Ada Systems
28316 @section Compatibility with Other Ada Systems
28317
28318 @noindent
28319 If programs avoid the use of implementation dependent and
28320 implementation defined features, as documented in the @cite{Ada
28321 Reference Manual}, there should be a high degree of portability between
28322 GNAT and other Ada systems.  The following are specific items which
28323 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
28324 compilers, but do not affect porting code to GNAT@.
28325 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
28326 the following issues may or may not arise for Ada 2005 programs
28327 when other compilers appear.)
28328
28329 @table @emph
28330 @item Ada 83 Pragmas and Attributes
28331 Ada 95 compilers are allowed, but not required, to implement the missing
28332 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
28333 GNAT implements all such pragmas and attributes, eliminating this as
28334 a compatibility concern, but some other Ada 95 compilers reject these
28335 pragmas and attributes.
28336
28337 @item Specialized Needs Annexes
28338 GNAT implements the full set of special needs annexes.  At the
28339 current time, it is the only Ada 95 compiler to do so.  This means that
28340 programs making use of these features may not be portable to other Ada
28341 95 compilation systems.
28342
28343 @item Representation Clauses
28344 Some other Ada 95 compilers implement only the minimal set of
28345 representation clauses required by the Ada 95 reference manual.  GNAT goes
28346 far beyond this minimal set, as described in the next section.
28347 @end table
28348
28349 @node Representation Clauses
28350 @section Representation Clauses
28351
28352 @noindent
28353 The Ada 83 reference manual was quite vague in describing both the minimal
28354 required implementation of representation clauses, and also their precise
28355 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
28356 minimal set of capabilities required is still quite limited.
28357
28358 GNAT implements the full required set of capabilities in
28359 Ada 95 and Ada 2005, but also goes much further, and in particular
28360 an effort has been made to be compatible with existing Ada 83 usage to the
28361 greatest extent possible.
28362
28363 A few cases exist in which Ada 83 compiler behavior is incompatible with
28364 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
28365 intentional or accidental dependence on specific implementation dependent
28366 characteristics of these Ada 83 compilers.  The following is a list of
28367 the cases most likely to arise in existing Ada 83 code.
28368
28369 @table @emph
28370 @item Implicit Packing
28371 Some Ada 83 compilers allowed a Size specification to cause implicit
28372 packing of an array or record.  This could cause expensive implicit
28373 conversions for change of representation in the presence of derived
28374 types, and the Ada design intends to avoid this possibility.
28375 Subsequent AI's were issued to make it clear that such implicit
28376 change of representation in response to a Size clause is inadvisable,
28377 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
28378 Reference Manuals as implementation advice that is followed by GNAT@.
28379 The problem will show up as an error
28380 message rejecting the size clause.  The fix is simply to provide
28381 the explicit pragma @code{Pack}, or for more fine tuned control, provide
28382 a Component_Size clause.
28383
28384 @item Meaning of Size Attribute
28385 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
28386 the minimal number of bits required to hold values of the type.  For example,
28387 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
28388 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
28389 some 32 in this situation.  This problem will usually show up as a compile
28390 time error, but not always.  It is a good idea to check all uses of the
28391 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
28392 Object_Size can provide a useful way of duplicating the behavior of
28393 some Ada 83 compiler systems.
28394
28395 @item Size of Access Types
28396 A common assumption in Ada 83 code is that an access type is in fact a pointer,
28397 and that therefore it will be the same size as a System.Address value.  This
28398 assumption is true for GNAT in most cases with one exception.  For the case of
28399 a pointer to an unconstrained array type (where the bounds may vary from one
28400 value of the access type to another), the default is to use a ``fat pointer'',
28401 which is represented as two separate pointers, one to the bounds, and one to
28402 the array.  This representation has a number of advantages, including improved
28403 efficiency.  However, it may cause some difficulties in porting existing Ada 83
28404 code which makes the assumption that, for example, pointers fit in 32 bits on
28405 a machine with 32-bit addressing.
28406
28407 To get around this problem, GNAT also permits the use of ``thin pointers'' for
28408 access types in this case (where the designated type is an unconstrained array
28409 type).  These thin pointers are indeed the same size as a System.Address value.
28410 To specify a thin pointer, use a size clause for the type, for example:
28411
28412 @smallexample @c ada
28413 type X is access all String;
28414 for X'Size use Standard'Address_Size;
28415 @end smallexample
28416
28417 @noindent
28418 which will cause the type X to be represented using a single pointer.
28419 When using this representation, the bounds are right behind the array.
28420 This representation is slightly less efficient, and does not allow quite
28421 such flexibility in the use of foreign pointers or in using the
28422 Unrestricted_Access attribute to create pointers to non-aliased objects.
28423 But for any standard portable use of the access type it will work in
28424 a functionally correct manner and allow porting of existing code.
28425 Note that another way of forcing a thin pointer representation
28426 is to use a component size clause for the element size in an array,
28427 or a record representation clause for an access field in a record.
28428 @end table
28429
28430 @ifclear vms
28431 @c This brief section is only in the non-VMS version
28432 @c The complete chapter on HP Ada is in the VMS version
28433 @node Compatibility with HP Ada 83
28434 @section Compatibility with HP Ada 83
28435
28436 @noindent
28437 The VMS version of GNAT fully implements all the pragmas and attributes
28438 provided by HP Ada 83, as well as providing the standard HP Ada 83
28439 libraries, including Starlet.  In addition, data layouts and parameter
28440 passing conventions are highly compatible.  This means that porting
28441 existing HP Ada 83 code to GNAT in VMS systems should be easier than
28442 most other porting efforts.  The following are some of the most
28443 significant differences between GNAT and HP Ada 83.
28444
28445 @table @emph
28446 @item Default floating-point representation
28447 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
28448 it is VMS format.  GNAT does implement the necessary pragmas
28449 (Long_Float, Float_Representation) for changing this default.
28450
28451 @item System
28452 The package System in GNAT exactly corresponds to the definition in the
28453 Ada 95 reference manual, which means that it excludes many of the
28454 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
28455 that contains the additional definitions, and a special pragma,
28456 Extend_System allows this package to be treated transparently as an
28457 extension of package System.
28458
28459 @item To_Address
28460 The definitions provided by Aux_DEC are exactly compatible with those
28461 in the HP Ada 83 version of System, with one exception.
28462 HP Ada provides the following declarations:
28463
28464 @smallexample @c ada
28465 TO_ADDRESS (INTEGER)
28466 TO_ADDRESS (UNSIGNED_LONGWORD)
28467 TO_ADDRESS (@i{universal_integer})
28468 @end smallexample
28469
28470 @noindent
28471 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
28472 an extension to Ada 83 not strictly compatible with the reference manual.
28473 In GNAT, we are constrained to be exactly compatible with the standard,
28474 and this means we cannot provide this capability.  In HP Ada 83, the
28475 point of this definition is to deal with a call like:
28476
28477 @smallexample @c ada
28478 TO_ADDRESS (16#12777#);
28479 @end smallexample
28480
28481 @noindent
28482 Normally, according to the Ada 83 standard, one would expect this to be
28483 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
28484 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
28485 definition using @i{universal_integer} takes precedence.
28486
28487 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
28488 is not possible to be 100% compatible.  Since there are many programs using
28489 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
28490 to change the name of the function in the UNSIGNED_LONGWORD case, so the
28491 declarations provided in the GNAT version of AUX_Dec are:
28492
28493 @smallexample @c ada
28494 function To_Address (X : Integer) return Address;
28495 pragma Pure_Function (To_Address);
28496
28497 function To_Address_Long (X : Unsigned_Longword)
28498  return Address;
28499 pragma Pure_Function (To_Address_Long);
28500 @end smallexample
28501
28502 @noindent
28503 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
28504 change the name to TO_ADDRESS_LONG@.
28505
28506 @item Task_Id values
28507 The Task_Id values assigned will be different in the two systems, and GNAT
28508 does not provide a specified value for the Task_Id of the environment task,
28509 which in GNAT is treated like any other declared task.
28510 @end table
28511
28512 @noindent
28513 For full details on these and other less significant compatibility issues,
28514 see appendix E of the HP publication entitled @cite{HP Ada, Technical
28515 Overview and Comparison on HP Platforms}.
28516
28517 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
28518 attributes are recognized, although only a subset of them can sensibly
28519 be implemented.  The description of pragmas in the
28520 @cite{GNAT Reference Manual}
28521 indicates whether or not they are applicable to non-VMS systems.
28522 @end ifclear
28523
28524 @ifset vms
28525 @node Transitioning to 64-Bit GNAT for OpenVMS
28526 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
28527
28528 @noindent
28529 This section is meant to assist users of pre-2006 @value{EDITION}
28530 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
28531 the version of the GNAT technology supplied in 2006 and later for
28532 OpenVMS on both Alpha and I64.
28533
28534 @menu
28535 * Introduction to transitioning::
28536 * Migration of 32 bit code::
28537 * Taking advantage of 64 bit addressing::
28538 * Technical details::
28539 @end menu
28540
28541 @node Introduction to transitioning
28542 @subsection Introduction
28543
28544 @noindent
28545 64-bit @value{EDITION} for Open VMS has been designed to meet
28546 three main goals:
28547
28548 @enumerate
28549 @item
28550 Providing a full conforming implementation of Ada 95 and Ada 2005
28551
28552 @item
28553 Allowing maximum backward compatibility, thus easing migration of existing
28554 Ada source code
28555
28556 @item
28557 Supplying a path for exploiting the full 64-bit address range
28558 @end enumerate
28559
28560 @noindent
28561 Ada's strong typing semantics has made it
28562 impractical to have different 32-bit and 64-bit modes. As soon as
28563 one object could possibly be outside the 32-bit address space, this
28564 would make it necessary for the @code{System.Address} type to be 64 bits.
28565 In particular, this would cause inconsistencies if 32-bit code is
28566 called from 64-bit code that raises an exception.
28567
28568 This issue has been resolved by always using 64-bit addressing
28569 at the system level, but allowing for automatic conversions between
28570 32-bit and 64-bit addresses where required. Thus users who
28571 do not currently require 64-bit addressing capabilities, can
28572 recompile their code with only minimal changes (and indeed
28573 if the code is written in portable Ada, with no assumptions about
28574 the size of the @code{Address} type, then no changes at all are necessary).
28575 At the same time,
28576 this approach provides a simple, gradual upgrade path to future
28577 use of larger memories than available for 32-bit systems.
28578 Also, newly written applications or libraries will by default
28579 be fully compatible with future systems exploiting 64-bit
28580 addressing capabilities.
28581
28582 @ref{Migration of 32 bit code}, will focus on porting applications
28583 that do not require more than 2 GB of
28584 addressable memory. This code will be referred to as
28585 @emph{32-bit code}.
28586 For applications intending to exploit the full 64-bit address space,
28587 @ref{Taking advantage of 64 bit addressing},
28588 will consider further changes that may be required.
28589 Such code will be referred to below as @emph{64-bit code}.
28590
28591 @node Migration of 32 bit code
28592 @subsection Migration of 32-bit code
28593
28594 @menu
28595 * Address types::
28596 * Access types::
28597 * Unchecked conversions::
28598 * Predefined constants::
28599 * Interfacing with C::
28600 * Experience with source compatibility::
28601 @end menu
28602
28603 @node Address types
28604 @subsubsection Address types
28605
28606 @noindent
28607 To solve the problem of mixing 64-bit and 32-bit addressing,
28608 while maintaining maximum backward compatibility, the following
28609 approach has been taken:
28610
28611 @itemize @bullet
28612 @item
28613 @code{System.Address} always has a size of 64 bits
28614
28615 @item
28616 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
28617 @end itemize
28618
28619 @noindent
28620 Since @code{System.Short_Address} is a subtype of @code{System.Address},
28621 a @code{Short_Address}
28622 may be used where an @code{Address} is required, and vice versa, without
28623 needing explicit type conversions.
28624 By virtue of the Open VMS parameter passing conventions,
28625 even imported
28626 and exported subprograms that have 32-bit address parameters are
28627 compatible with those that have 64-bit address parameters.
28628 (See @ref{Making code 64 bit clean} for details.)
28629
28630 The areas that may need attention are those where record types have
28631 been defined that contain components of the type @code{System.Address}, and
28632 where objects of this type are passed to code expecting a record layout with
28633 32-bit addresses.
28634
28635 Different compilers on different platforms cannot be
28636 expected to represent the same type in the same way,
28637 since alignment constraints
28638 and other system-dependent properties affect the compiler's decision.
28639 For that reason, Ada code
28640 generally uses representation clauses to specify the expected
28641 layout where required.
28642
28643 If such a representation clause uses 32 bits for a component having
28644 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
28645 will detect that error and produce a specific diagnostic message.
28646 The developer should then determine whether the representation
28647 should be 64 bits or not and make either of two changes:
28648 change the size to 64 bits and leave the type as @code{System.Address}, or
28649 leave the size as 32 bits and change the type to @code{System.Short_Address}.
28650 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
28651 required in any code setting or accessing the field; the compiler will
28652 automatically perform any needed conversions between address
28653 formats.
28654
28655 @node Access types
28656 @subsubsection Access types
28657
28658 @noindent
28659 By default, objects designated by access values are always
28660 allocated in the 32-bit
28661 address space. Thus legacy code will never contain
28662 any objects that are not addressable with 32-bit addresses, and
28663 the compiler will never raise exceptions as result of mixing
28664 32-bit and 64-bit addresses.
28665
28666 However, the access values themselves are represented in 64 bits, for optimum
28667 performance and future compatibility with 64-bit code. As was
28668 the case with @code{System.Address}, the compiler will give an error message
28669 if an object or record component has a representation clause that
28670 requires the access value to fit in 32 bits. In such a situation,
28671 an explicit size clause for the access type, specifying 32 bits,
28672 will have the desired effect.
28673
28674 General access types (declared with @code{access all}) can never be
28675 32 bits, as values of such types must be able to refer to any object
28676 of the  designated type,
28677 including objects residing outside the 32-bit address range.
28678 Existing Ada 83 code will not contain such type definitions,
28679 however, since general access types were introduced in Ada 95.
28680
28681 @node Unchecked conversions
28682 @subsubsection Unchecked conversions
28683
28684 @noindent
28685 In the case of an @code{Unchecked_Conversion} where the source type is a
28686 64-bit access type or the type @code{System.Address}, and the target
28687 type is a 32-bit type, the compiler will generate a warning.
28688 Even though the generated code will still perform the required
28689 conversions, it is highly recommended in these cases to use
28690 respectively a 32-bit access type or @code{System.Short_Address}
28691 as the source type.
28692
28693 @node Predefined constants
28694 @subsubsection Predefined constants
28695
28696 @noindent
28697 The following table shows the correspondence between pre-2006 versions of
28698 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
28699 (``New''):
28700
28701 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
28702 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
28703 @item   @code{System.Word_Size}          @tab 32      @tab 64
28704 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
28705 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
28706 @item   @code{System.Address_Size}       @tab 32      @tab 64
28707 @end multitable
28708
28709 @noindent
28710 If you need to refer to the specific
28711 memory size of a 32-bit implementation, instead of the
28712 actual memory size, use @code{System.Short_Memory_Size}
28713 rather than @code{System.Memory_Size}.
28714 Similarly, references to @code{System.Address_Size} may need
28715 to be replaced by @code{System.Short_Address'Size}.
28716 The program @command{gnatfind} may be useful for locating
28717 references to the above constants, so that you can verify that they
28718 are still correct.
28719
28720 @node Interfacing with C
28721 @subsubsection Interfacing with C
28722
28723 @noindent
28724 In order to minimize the impact of the transition to 64-bit addresses on
28725 legacy programs, some fundamental types in the @code{Interfaces.C}
28726 package hierarchy continue to be represented in 32 bits.
28727 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
28728 This eases integration with the default HP C layout choices, for example
28729 as found in the system routines in @code{DECC$SHR.EXE}.
28730 Because of this implementation choice, the type fully compatible with
28731 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
28732 Depending on the context the compiler will issue a
28733 warning or an error when type @code{Address} is used, alerting the user to a
28734 potential problem. Otherwise 32-bit programs that use
28735 @code{Interfaces.C} should normally not require code modifications
28736
28737 The other issue arising with C interfacing concerns pragma @code{Convention}.
28738 For VMS 64-bit systems, there is an issue of the appropriate default size
28739 of C convention pointers in the absence of an explicit size clause. The HP
28740 C compiler can choose either 32 or 64 bits depending on compiler options.
28741 GNAT chooses 32-bits rather than 64-bits in the default case where no size
28742 clause is given. This proves a better choice for porting 32-bit legacy
28743 applications. In order to have a 64-bit representation, it is necessary to
28744 specify a size representation clause. For example:
28745
28746 @smallexample @c ada
28747 type int_star is access Interfaces.C.int;
28748 pragma Convention(C, int_star);
28749 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
28750 @end smallexample
28751
28752 @node Experience with source compatibility
28753 @subsubsection Experience with source compatibility
28754
28755 @noindent
28756 The Security Server and STARLET on I64 provide an interesting ``test case''
28757 for source compatibility issues, since it is in such system code
28758 where assumptions about @code{Address} size might be expected to occur.
28759 Indeed, there were a small number of occasions in the Security Server
28760 file @file{jibdef.ads}
28761 where a representation clause for a record type specified
28762 32 bits for a component of type @code{Address}.
28763 All of these errors were detected by the compiler.
28764 The repair was obvious and immediate; to simply replace @code{Address} by
28765 @code{Short_Address}.
28766
28767 In the case of STARLET, there were several record types that should
28768 have had representation clauses but did not.  In these record types
28769 there was an implicit assumption that an @code{Address} value occupied
28770 32 bits.
28771 These compiled without error, but their usage resulted in run-time error
28772 returns from STARLET system calls.
28773 Future GNAT technology enhancements may include a tool that detects and flags
28774 these sorts of potential source code porting problems.
28775
28776 @c ****************************************
28777 @node Taking advantage of 64 bit addressing
28778 @subsection Taking advantage of 64-bit addressing
28779
28780 @menu
28781 * Making code 64 bit clean::
28782 * Allocating memory from the 64 bit storage pool::
28783 * Restrictions on use of 64 bit objects::
28784 * Using 64 bit storage pools by default::
28785 * General access types::
28786 * STARLET and other predefined libraries::
28787 @end menu
28788
28789 @node Making code 64 bit clean
28790 @subsubsection Making code 64-bit clean
28791
28792 @noindent
28793 In order to prevent problems that may occur when (parts of) a
28794 system start using memory outside the 32-bit address range,
28795 we recommend some additional guidelines:
28796
28797 @itemize @bullet
28798 @item
28799 For imported subprograms that take parameters of the
28800 type @code{System.Address}, ensure that these subprograms can
28801 indeed handle 64-bit addresses. If not, or when in doubt,
28802 change the subprogram declaration to specify
28803 @code{System.Short_Address} instead.
28804
28805 @item
28806 Resolve all warnings related to size mismatches in
28807 unchecked conversions. Failing to do so causes
28808 erroneous execution if the source object is outside
28809 the 32-bit address space.
28810
28811 @item
28812 (optional) Explicitly use the 32-bit storage pool
28813 for access types used in a 32-bit context, or use
28814 generic access types where possible
28815 (@pxref{Restrictions on use of 64 bit objects}).
28816 @end itemize
28817
28818 @noindent
28819 If these rules are followed, the compiler will automatically insert
28820 any necessary checks to ensure that no addresses or access values
28821 passed to 32-bit code ever refer to objects outside the 32-bit
28822 address range.
28823 Any attempt to do this will raise @code{Constraint_Error}.
28824
28825 @node Allocating memory from the 64 bit storage pool
28826 @subsubsection Allocating memory from the 64-bit storage pool
28827
28828 @noindent
28829 For any access type @code{T} that potentially requires memory allocations
28830 beyond the 32-bit address space,
28831 use the following representation clause:
28832
28833 @smallexample @c ada
28834    for T'Storage_Pool use System.Pool_64;
28835 @end smallexample
28836
28837 @node Restrictions on use of 64 bit objects
28838 @subsubsection Restrictions on use of 64-bit objects
28839
28840 @noindent
28841 Taking the address of an object allocated from a 64-bit storage pool,
28842 and then passing this address to a subprogram expecting
28843 @code{System.Short_Address},
28844 or assigning it to a variable of type @code{Short_Address}, will cause
28845 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
28846 (@pxref{Making code 64 bit clean}), or checks are suppressed,
28847 no exception is raised and execution
28848 will become erroneous.
28849
28850 @node Using 64 bit storage pools by default
28851 @subsubsection Using 64-bit storage pools by default
28852
28853 @noindent
28854 In some cases it may be desirable to have the compiler allocate
28855 from 64-bit storage pools by default. This may be the case for
28856 libraries that are 64-bit clean, but may be used in both 32-bit
28857 and 64-bit contexts. For these cases the following configuration
28858 pragma may be specified:
28859
28860 @smallexample @c ada
28861   pragma Pool_64_Default;
28862 @end smallexample
28863
28864 @noindent
28865 Any code compiled in the context of this pragma will by default
28866 use the @code{System.Pool_64} storage pool. This default may be overridden
28867 for a specific access type @code{T} by the representation clause:
28868
28869 @smallexample @c ada
28870    for T'Storage_Pool use System.Pool_32;
28871 @end smallexample
28872
28873 @noindent
28874 Any object whose address may be passed to a subprogram with a
28875 @code{Short_Address} argument, or assigned to a variable of type
28876 @code{Short_Address}, needs to be allocated from this pool.
28877
28878 @node General access types
28879 @subsubsection General access types
28880
28881 @noindent
28882 Objects designated by access values from a
28883 general access type (declared with @code{access all}) are never allocated
28884 from a 64-bit storage pool. Code that uses general access types will
28885 accept objects allocated in either 32-bit or 64-bit address spaces,
28886 but never allocate objects outside the 32-bit address space.
28887 Using general access types ensures maximum compatibility with both
28888 32-bit and 64-bit code.
28889
28890 @node STARLET and other predefined libraries
28891 @subsubsection STARLET and other predefined libraries
28892
28893 @noindent
28894 All code that comes as part of GNAT is 64-bit clean, but the
28895 restrictions given in @ref{Restrictions on use of 64 bit objects},
28896 still apply. Look at the package
28897 specifications to see in which contexts objects allocated
28898 in 64-bit address space are acceptable.
28899
28900 @node Technical details
28901 @subsection Technical details
28902
28903 @noindent
28904 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
28905 Ada standard with respect to the type of @code{System.Address}. Previous
28906 versions of GNAT Pro have defined this type as private and implemented it as a
28907 modular type.
28908
28909 In order to allow defining @code{System.Short_Address} as a proper subtype,
28910 and to match the implicit sign extension in parameter passing,
28911 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
28912 visible (i.e., non-private) integer type.
28913 Standard operations on the type, such as the binary operators ``+'', ``-'',
28914 etc., that take @code{Address} operands and return an @code{Address} result,
28915 have been hidden by declaring these
28916 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
28917 ambiguities that would otherwise result from overloading.
28918 (Note that, although @code{Address} is a visible integer type,
28919 good programming practice dictates against exploiting the type's
28920 integer properties such as literals, since this will compromise
28921 code portability.)
28922
28923 Defining @code{Address} as a visible integer type helps achieve
28924 maximum compatibility for existing Ada code,
28925 without sacrificing the capabilities of the 64-bit architecture.
28926 @end ifset
28927
28928 @c ************************************************
28929 @ifset unw
28930 @node Microsoft Windows Topics
28931 @appendix Microsoft Windows Topics
28932 @cindex Windows NT
28933 @cindex Windows 95
28934 @cindex Windows 98
28935
28936 @noindent
28937 This chapter describes topics that are specific to the Microsoft Windows
28938 platforms (NT, 2000, and XP Professional).
28939
28940 @menu
28941 * Using GNAT on Windows::
28942 * Using a network installation of GNAT::
28943 * CONSOLE and WINDOWS subsystems::
28944 * Temporary Files::
28945 * Mixed-Language Programming on Windows::
28946 * Windows Calling Conventions::
28947 * Introduction to Dynamic Link Libraries (DLLs)::
28948 * Using DLLs with GNAT::
28949 * Building DLLs with GNAT::
28950 * Building DLLs with GNAT Project files::
28951 * Building DLLs with gnatdll::
28952 * GNAT and Windows Resources::
28953 * Debugging a DLL::
28954 * Setting Stack Size from gnatlink::
28955 * Setting Heap Size from gnatlink::
28956 @end menu
28957
28958 @node Using GNAT on Windows
28959 @section Using GNAT on Windows
28960
28961 @noindent
28962 One of the strengths of the GNAT technology is that its tool set
28963 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
28964 @code{gdb} debugger, etc.) is used in the same way regardless of the
28965 platform.
28966
28967 On Windows this tool set is complemented by a number of Microsoft-specific
28968 tools that have been provided to facilitate interoperability with Windows
28969 when this is required. With these tools:
28970
28971 @itemize @bullet
28972
28973 @item
28974 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
28975 subsystems.
28976
28977 @item
28978 You can use any Dynamically Linked Library (DLL) in your Ada code (both
28979 relocatable and non-relocatable DLLs are supported).
28980
28981 @item
28982 You can build Ada DLLs for use in other applications. These applications
28983 can be written in a language other than Ada (e.g., C, C++, etc). Again both
28984 relocatable and non-relocatable Ada DLLs are supported.
28985
28986 @item
28987 You can include Windows resources in your Ada application.
28988
28989 @item
28990 You can use or create COM/DCOM objects.
28991 @end itemize
28992
28993 @noindent
28994 Immediately below are listed all known general GNAT-for-Windows restrictions.
28995 Other restrictions about specific features like Windows Resources and DLLs
28996 are listed in separate sections below.
28997
28998 @itemize @bullet
28999
29000 @item
29001 It is not possible to use @code{GetLastError} and @code{SetLastError}
29002 when tasking, protected records, or exceptions are used. In these
29003 cases, in order to implement Ada semantics, the GNAT run-time system
29004 calls certain Win32 routines that set the last error variable to 0 upon
29005 success. It should be possible to use @code{GetLastError} and
29006 @code{SetLastError} when tasking, protected record, and exception
29007 features are not used, but it is not guaranteed to work.
29008
29009 @item
29010 It is not possible to link against Microsoft libraries except for
29011 import libraries. The library must be built to be compatible with
29012 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
29013 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
29014 not be compatible with the GNAT runtime. Even if the library is
29015 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
29016
29017 @item
29018 When the compilation environment is located on FAT32 drives, users may
29019 experience recompilations of the source files that have not changed if
29020 Daylight Saving Time (DST) state has changed since the last time files
29021 were compiled. NTFS drives do not have this problem.
29022
29023 @item
29024 No components of the GNAT toolset use any entries in the Windows
29025 registry. The only entries that can be created are file associations and
29026 PATH settings, provided the user has chosen to create them at installation
29027 time, as well as some minimal book-keeping information needed to correctly
29028 uninstall or integrate different GNAT products.
29029 @end itemize
29030
29031 @node Using a network installation of GNAT
29032 @section Using a network installation of GNAT
29033
29034 @noindent
29035 Make sure the system on which GNAT is installed is accessible from the
29036 current machine, i.e. the install location is shared over the network.
29037 Shared resources are accessed on Windows by means of UNC paths, which
29038 have the format @code{\\server\sharename\path}
29039
29040 In order to use such a network installation, simply add the UNC path of the
29041 @file{bin} directory of your GNAT installation in front of your PATH. For
29042 example, if GNAT is installed in @file{\GNAT} directory of a share location
29043 called @file{c-drive} on a machine @file{LOKI}, the following command will
29044 make it available:
29045
29046 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
29047
29048 Be aware that every compilation using the network installation results in the
29049 transfer of large amounts of data across the network and will likely cause
29050 serious performance penalty.
29051
29052 @node CONSOLE and WINDOWS subsystems
29053 @section CONSOLE and WINDOWS subsystems
29054 @cindex CONSOLE Subsystem
29055 @cindex WINDOWS Subsystem
29056 @cindex -mwindows
29057
29058 @noindent
29059 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
29060 (which is the default subsystem) will always create a console when
29061 launching the application. This is not something desirable when the
29062 application has a Windows GUI. To get rid of this console the
29063 application must be using the @code{WINDOWS} subsystem. To do so
29064 the @option{-mwindows} linker option must be specified.
29065
29066 @smallexample
29067 $ gnatmake winprog -largs -mwindows
29068 @end smallexample
29069
29070 @node Temporary Files
29071 @section Temporary Files
29072 @cindex Temporary files
29073
29074 @noindent
29075 It is possible to control where temporary files gets created by setting
29076 the TMP environment variable. The file will be created:
29077
29078 @itemize
29079 @item Under the directory pointed to by the TMP environment variable if
29080 this directory exists.
29081
29082 @item Under c:\temp, if the TMP environment variable is not set (or not
29083 pointing to a directory) and if this directory exists.
29084
29085 @item Under the current working directory otherwise.
29086 @end itemize
29087
29088 @noindent
29089 This allows you to determine exactly where the temporary
29090 file will be created. This is particularly useful in networked
29091 environments where you may not have write access to some
29092 directories.
29093
29094 @node Mixed-Language Programming on Windows
29095 @section Mixed-Language Programming on Windows
29096
29097 @noindent
29098 Developing pure Ada applications on Windows is no different than on
29099 other GNAT-supported platforms. However, when developing or porting an
29100 application that contains a mix of Ada and C/C++, the choice of your
29101 Windows C/C++ development environment conditions your overall
29102 interoperability strategy.
29103
29104 If you use @command{gcc} to compile the non-Ada part of your application,
29105 there are no Windows-specific restrictions that affect the overall
29106 interoperability with your Ada code. If you plan to use
29107 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
29108 the following limitations:
29109
29110 @itemize @bullet
29111 @item
29112 You cannot link your Ada code with an object or library generated with
29113 Microsoft tools if these use the @code{.tls} section (Thread Local
29114 Storage section) since the GNAT linker does not yet support this section.
29115
29116 @item
29117 You cannot link your Ada code with an object or library generated with
29118 Microsoft tools if these use I/O routines other than those provided in
29119 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
29120 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
29121 libraries can cause a conflict with @code{msvcrt.dll} services. For
29122 instance Visual C++ I/O stream routines conflict with those in
29123 @code{msvcrt.dll}.
29124 @end itemize
29125
29126 @noindent
29127 If you do want to use the Microsoft tools for your non-Ada code and hit one
29128 of the above limitations, you have two choices:
29129
29130 @enumerate
29131 @item
29132 Encapsulate your non Ada code in a DLL to be linked with your Ada
29133 application. In this case, use the Microsoft or whatever environment to
29134 build the DLL and use GNAT to build your executable
29135 (@pxref{Using DLLs with GNAT}).
29136
29137 @item
29138 Or you can encapsulate your Ada code in a DLL to be linked with the
29139 other part of your application. In this case, use GNAT to build the DLL
29140 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
29141 environment to build your executable.
29142 @end enumerate
29143
29144 @node Windows Calling Conventions
29145 @section Windows Calling Conventions
29146 @findex Stdcall
29147 @findex APIENTRY
29148
29149 @menu
29150 * C Calling Convention::
29151 * Stdcall Calling Convention::
29152 * Win32 Calling Convention::
29153 * DLL Calling Convention::
29154 @end menu
29155
29156 @noindent
29157 When a subprogram @code{F} (caller) calls a subprogram @code{G}
29158 (callee), there are several ways to push @code{G}'s parameters on the
29159 stack and there are several possible scenarios to clean up the stack
29160 upon @code{G}'s return. A calling convention is an agreed upon software
29161 protocol whereby the responsibilities between the caller (@code{F}) and
29162 the callee (@code{G}) are clearly defined. Several calling conventions
29163 are available for Windows:
29164
29165 @itemize @bullet
29166 @item
29167 @code{C} (Microsoft defined)
29168
29169 @item
29170 @code{Stdcall} (Microsoft defined)
29171
29172 @item
29173 @code{Win32} (GNAT specific)
29174
29175 @item
29176 @code{DLL} (GNAT specific)
29177 @end itemize
29178
29179 @node C Calling Convention
29180 @subsection @code{C} Calling Convention
29181
29182 @noindent
29183 This is the default calling convention used when interfacing to C/C++
29184 routines compiled with either @command{gcc} or Microsoft Visual C++.
29185
29186 In the @code{C} calling convention subprogram parameters are pushed on the
29187 stack by the caller from right to left. The caller itself is in charge of
29188 cleaning up the stack after the call. In addition, the name of a routine
29189 with @code{C} calling convention is mangled by adding a leading underscore.
29190
29191 The name to use on the Ada side when importing (or exporting) a routine
29192 with @code{C} calling convention is the name of the routine. For
29193 instance the C function:
29194
29195 @smallexample
29196 int get_val (long);
29197 @end smallexample
29198
29199 @noindent
29200 should be imported from Ada as follows:
29201
29202 @smallexample @c ada
29203 @group
29204 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29205 pragma Import (C, Get_Val, External_Name => "get_val");
29206 @end group
29207 @end smallexample
29208
29209 @noindent
29210 Note that in this particular case the @code{External_Name} parameter could
29211 have been omitted since, when missing, this parameter is taken to be the
29212 name of the Ada entity in lower case. When the @code{Link_Name} parameter
29213 is missing, as in the above example, this parameter is set to be the
29214 @code{External_Name} with a leading underscore.
29215
29216 When importing a variable defined in C, you should always use the @code{C}
29217 calling convention unless the object containing the variable is part of a
29218 DLL (in which case you should use the @code{Stdcall} calling
29219 convention, @pxref{Stdcall Calling Convention}).
29220
29221 @node Stdcall Calling Convention
29222 @subsection @code{Stdcall} Calling Convention
29223
29224 @noindent
29225 This convention, which was the calling convention used for Pascal
29226 programs, is used by Microsoft for all the routines in the Win32 API for
29227 efficiency reasons. It must be used to import any routine for which this
29228 convention was specified.
29229
29230 In the @code{Stdcall} calling convention subprogram parameters are pushed
29231 on the stack by the caller from right to left. The callee (and not the
29232 caller) is in charge of cleaning the stack on routine exit. In addition,
29233 the name of a routine with @code{Stdcall} calling convention is mangled by
29234 adding a leading underscore (as for the @code{C} calling convention) and a
29235 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
29236 bytes) of the parameters passed to the routine.
29237
29238 The name to use on the Ada side when importing a C routine with a
29239 @code{Stdcall} calling convention is the name of the C routine. The leading
29240 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
29241 the compiler. For instance the Win32 function:
29242
29243 @smallexample
29244 @b{APIENTRY} int get_val (long);
29245 @end smallexample
29246
29247 @noindent
29248 should be imported from Ada as follows:
29249
29250 @smallexample @c ada
29251 @group
29252 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29253 pragma Import (Stdcall, Get_Val);
29254 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
29255 @end group
29256 @end smallexample
29257
29258 @noindent
29259 As for the @code{C} calling convention, when the @code{External_Name}
29260 parameter is missing, it is taken to be the name of the Ada entity in lower
29261 case. If instead of writing the above import pragma you write:
29262
29263 @smallexample @c ada
29264 @group
29265 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29266 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
29267 @end group
29268 @end smallexample
29269
29270 @noindent
29271 then the imported routine is @code{_retrieve_val@@4}. However, if instead
29272 of specifying the @code{External_Name} parameter you specify the
29273 @code{Link_Name} as in the following example:
29274
29275 @smallexample @c ada
29276 @group
29277 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29278 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
29279 @end group
29280 @end smallexample
29281
29282 @noindent
29283 then the imported routine is @code{retrieve_val}, that is, there is no
29284 decoration at all. No leading underscore and no Stdcall suffix
29285 @code{@@}@code{@i{nn}}.
29286
29287 @noindent
29288 This is especially important as in some special cases a DLL's entry
29289 point name lacks a trailing @code{@@}@code{@i{nn}} while the exported
29290 name generated for a call has it.
29291
29292 @noindent
29293 It is also possible to import variables defined in a DLL by using an
29294 import pragma for a variable. As an example, if a DLL contains a
29295 variable defined as:
29296
29297 @smallexample
29298 int my_var;
29299 @end smallexample
29300
29301 @noindent
29302 then, to access this variable from Ada you should write:
29303
29304 @smallexample @c ada
29305 @group
29306 My_Var : Interfaces.C.int;
29307 pragma Import (Stdcall, My_Var);
29308 @end group
29309 @end smallexample
29310
29311 @noindent
29312 Note that to ease building cross-platform bindings this convention
29313 will be handled as a @code{C} calling convention on non Windows platforms.
29314
29315 @node Win32 Calling Convention
29316 @subsection @code{Win32} Calling Convention
29317
29318 @noindent
29319 This convention, which is GNAT-specific is fully equivalent to the
29320 @code{Stdcall} calling convention described above.
29321
29322 @node DLL Calling Convention
29323 @subsection @code{DLL} Calling Convention
29324
29325 @noindent
29326 This convention, which is GNAT-specific is fully equivalent to the
29327 @code{Stdcall} calling convention described above.
29328
29329 @node Introduction to Dynamic Link Libraries (DLLs)
29330 @section Introduction to Dynamic Link Libraries (DLLs)
29331 @findex DLL
29332
29333 @noindent
29334 A Dynamically Linked Library (DLL) is a library that can be shared by
29335 several applications running under Windows. A DLL can contain any number of
29336 routines and variables.
29337
29338 One advantage of DLLs is that you can change and enhance them without
29339 forcing all the applications that depend on them to be relinked or
29340 recompiled. However, you should be aware than all calls to DLL routines are
29341 slower since, as you will understand below, such calls are indirect.
29342
29343 To illustrate the remainder of this section, suppose that an application
29344 wants to use the services of a DLL @file{API.dll}. To use the services
29345 provided by @file{API.dll} you must statically link against the DLL or
29346 an import library which contains a jump table with an entry for each
29347 routine and variable exported by the DLL. In the Microsoft world this
29348 import library is called @file{API.lib}. When using GNAT this import
29349 library is called either @file{libAPI.a} or @file{libapi.a} (names are
29350 case insensitive).
29351
29352 After you have linked your application with the DLL or the import library
29353 and you run your application, here is what happens:
29354
29355 @enumerate
29356 @item
29357 Your application is loaded into memory.
29358
29359 @item
29360 The DLL @file{API.dll} is mapped into the address space of your
29361 application. This means that:
29362
29363 @itemize @bullet
29364 @item
29365 The DLL will use the stack of the calling thread.
29366
29367 @item
29368 The DLL will use the virtual address space of the calling process.
29369
29370 @item
29371 The DLL will allocate memory from the virtual address space of the calling
29372 process.
29373
29374 @item
29375 Handles (pointers) can be safely exchanged between routines in the DLL
29376 routines and routines in the application using the DLL.
29377 @end itemize
29378
29379 @item
29380 The entries in the jump table (from the import library @file{libAPI.a}
29381 or @file{API.lib} or automatically created when linking against a DLL)
29382 which is part of your application are initialized with the addresses
29383 of the routines and variables in @file{API.dll}.
29384
29385 @item
29386 If present in @file{API.dll}, routines @code{DllMain} or
29387 @code{DllMainCRTStartup} are invoked. These routines typically contain
29388 the initialization code needed for the well-being of the routines and
29389 variables exported by the DLL.
29390 @end enumerate
29391
29392 @noindent
29393 There is an additional point which is worth mentioning. In the Windows
29394 world there are two kind of DLLs: relocatable and non-relocatable
29395 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
29396 in the target application address space. If the addresses of two
29397 non-relocatable DLLs overlap and these happen to be used by the same
29398 application, a conflict will occur and the application will run
29399 incorrectly. Hence, when possible, it is always preferable to use and
29400 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
29401 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
29402 User's Guide) removes the debugging symbols from the DLL but the DLL can
29403 still be relocated.
29404
29405 As a side note, an interesting difference between Microsoft DLLs and
29406 Unix shared libraries, is the fact that on most Unix systems all public
29407 routines are exported by default in a Unix shared library, while under
29408 Windows it is possible (but not required) to list exported routines in
29409 a definition file (@pxref{The Definition File}).
29410
29411 @node Using DLLs with GNAT
29412 @section Using DLLs with GNAT
29413
29414 @menu
29415 * Creating an Ada Spec for the DLL Services::
29416 * Creating an Import Library::
29417 @end menu
29418
29419 @noindent
29420 To use the services of a DLL, say @file{API.dll}, in your Ada application
29421 you must have:
29422
29423 @enumerate
29424 @item
29425 The Ada spec for the routines and/or variables you want to access in
29426 @file{API.dll}. If not available this Ada spec must be built from the C/C++
29427 header files provided with the DLL.
29428
29429 @item
29430 The import library (@file{libAPI.a} or @file{API.lib}). As previously
29431 mentioned an import library is a statically linked library containing the
29432 import table which will be filled at load time to point to the actual
29433 @file{API.dll} routines. Sometimes you don't have an import library for the
29434 DLL you want to use. The following sections will explain how to build
29435 one. Note that this is optional.
29436
29437 @item
29438 The actual DLL, @file{API.dll}.
29439 @end enumerate
29440
29441 @noindent
29442 Once you have all the above, to compile an Ada application that uses the
29443 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
29444 you simply issue the command
29445
29446 @smallexample
29447 $ gnatmake my_ada_app -largs -lAPI
29448 @end smallexample
29449
29450 @noindent
29451 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
29452 tells the GNAT linker to look first for a library named @file{API.lib}
29453 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
29454 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
29455 contains the following pragma
29456
29457 @smallexample @c ada
29458 pragma Linker_Options ("-lAPI");
29459 @end smallexample
29460
29461 @noindent
29462 you do not have to add @option{-largs -lAPI} at the end of the
29463 @command{gnatmake} command.
29464
29465 If any one of the items above is missing you will have to create it
29466 yourself. The following sections explain how to do so using as an
29467 example a fictitious DLL called @file{API.dll}.
29468
29469 @node Creating an Ada Spec for the DLL Services
29470 @subsection Creating an Ada Spec for the DLL Services
29471
29472 @noindent
29473 A DLL typically comes with a C/C++ header file which provides the
29474 definitions of the routines and variables exported by the DLL. The Ada
29475 equivalent of this header file is a package spec that contains definitions
29476 for the imported entities. If the DLL you intend to use does not come with
29477 an Ada spec you have to generate one such spec yourself. For example if
29478 the header file of @file{API.dll} is a file @file{api.h} containing the
29479 following two definitions:
29480
29481 @smallexample
29482 @group
29483 @cartouche
29484 int some_var;
29485 int get (char *);
29486 @end cartouche
29487 @end group
29488 @end smallexample
29489
29490 @noindent
29491 then the equivalent Ada spec could be:
29492
29493 @smallexample @c ada
29494 @group
29495 @cartouche
29496 with Interfaces.C.Strings;
29497 package API is
29498    use Interfaces;
29499
29500    Some_Var : C.int;
29501    function Get (Str : C.Strings.Chars_Ptr) return C.int;
29502
29503 private
29504    pragma Import (C, Get);
29505    pragma Import (DLL, Some_Var);
29506 end API;
29507 @end cartouche
29508 @end group
29509 @end smallexample
29510
29511 @noindent
29512 Note that a variable is
29513 @strong{always imported with a Stdcall convention}. A function
29514 can have @code{C} or @code{Stdcall} convention.
29515 (@pxref{Windows Calling Conventions}).
29516
29517 @node Creating an Import Library
29518 @subsection Creating an Import Library
29519 @cindex Import library
29520
29521 @menu
29522 * The Definition File::
29523 * GNAT-Style Import Library::
29524 * Microsoft-Style Import Library::
29525 @end menu
29526
29527 @noindent
29528 If a Microsoft-style import library @file{API.lib} or a GNAT-style
29529 import library @file{libAPI.a} is available with @file{API.dll} you
29530 can skip this section. You can also skip this section if
29531 @file{API.dll} is built with GNU tools as in this case it is possible
29532 to link directly against the DLL. Otherwise read on.
29533
29534 @node The Definition File
29535 @subsubsection The Definition File
29536 @cindex Definition file
29537 @findex .def
29538
29539 @noindent
29540 As previously mentioned, and unlike Unix systems, the list of symbols
29541 that are exported from a DLL must be provided explicitly in Windows.
29542 The main goal of a definition file is precisely that: list the symbols
29543 exported by a DLL. A definition file (usually a file with a @code{.def}
29544 suffix) has the following structure:
29545
29546 @smallexample
29547 @group
29548 @cartouche
29549 [LIBRARY @i{name}]
29550 [DESCRIPTION @i{string}]
29551 EXPORTS
29552    @i{symbol1}
29553    @i{symbol2}
29554    ...
29555 @end cartouche
29556 @end group
29557 @end smallexample
29558
29559 @table @code
29560 @item LIBRARY @i{name}
29561 This section, which is optional, gives the name of the DLL.
29562
29563 @item DESCRIPTION @i{string}
29564 This section, which is optional, gives a description string that will be
29565 embedded in the import library.
29566
29567 @item EXPORTS
29568 This section gives the list of exported symbols (procedures, functions or
29569 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
29570 section of @file{API.def} looks like:
29571
29572 @smallexample
29573 @group
29574 @cartouche
29575 EXPORTS
29576    some_var
29577    get
29578 @end cartouche
29579 @end group
29580 @end smallexample
29581 @end table
29582
29583 @noindent
29584 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
29585 (@pxref{Windows Calling Conventions}) for a Stdcall
29586 calling convention function in the exported symbols list.
29587
29588 @noindent
29589 There can actually be other sections in a definition file, but these
29590 sections are not relevant to the discussion at hand.
29591
29592 @node GNAT-Style Import Library
29593 @subsubsection GNAT-Style Import Library
29594
29595 @noindent
29596 To create a static import library from @file{API.dll} with the GNAT tools
29597 you should proceed as follows:
29598
29599 @enumerate
29600 @item
29601 Create the definition file @file{API.def} (@pxref{The Definition File}).
29602 For that use the @code{dll2def} tool as follows:
29603
29604 @smallexample
29605 $ dll2def API.dll > API.def
29606 @end smallexample
29607
29608 @noindent
29609 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
29610 to standard output the list of entry points in the DLL. Note that if
29611 some routines in the DLL have the @code{Stdcall} convention
29612 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
29613 suffix then you'll have to edit @file{api.def} to add it, and specify
29614 @code{-k} to @code{gnatdll} when creating the import library.
29615
29616 @noindent
29617 Here are some hints to find the right @code{@@}@i{nn} suffix.
29618
29619 @enumerate
29620 @item
29621 If you have the Microsoft import library (.lib), it is possible to get
29622 the right symbols by using Microsoft @code{dumpbin} tool (see the
29623 corresponding Microsoft documentation for further details).
29624
29625 @smallexample
29626 $ dumpbin /exports api.lib
29627 @end smallexample
29628
29629 @item
29630 If you have a message about a missing symbol at link time the compiler
29631 tells you what symbol is expected. You just have to go back to the
29632 definition file and add the right suffix.
29633 @end enumerate
29634
29635 @item
29636 Build the import library @code{libAPI.a}, using @code{gnatdll}
29637 (@pxref{Using gnatdll}) as follows:
29638
29639 @smallexample
29640 $ gnatdll -e API.def -d API.dll
29641 @end smallexample
29642
29643 @noindent
29644 @code{gnatdll} takes as input a definition file @file{API.def} and the
29645 name of the DLL containing the services listed in the definition file
29646 @file{API.dll}. The name of the static import library generated is
29647 computed from the name of the definition file as follows: if the
29648 definition file name is @i{xyz}@code{.def}, the import library name will
29649 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
29650 @option{-e} could have been removed because the name of the definition
29651 file (before the ``@code{.def}'' suffix) is the same as the name of the
29652 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
29653 @end enumerate
29654
29655 @node Microsoft-Style Import Library
29656 @subsubsection Microsoft-Style Import Library
29657
29658 @noindent
29659 With GNAT you can either use a GNAT-style or Microsoft-style import
29660 library. A Microsoft import library is needed only if you plan to make an
29661 Ada DLL available to applications developed with Microsoft
29662 tools (@pxref{Mixed-Language Programming on Windows}).
29663
29664 To create a Microsoft-style import library for @file{API.dll} you
29665 should proceed as follows:
29666
29667 @enumerate
29668 @item
29669 Create the definition file @file{API.def} from the DLL. For this use either
29670 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
29671 tool (see the corresponding Microsoft documentation for further details).
29672
29673 @item
29674 Build the actual import library using Microsoft's @code{lib} utility:
29675
29676 @smallexample
29677 $ lib -machine:IX86 -def:API.def -out:API.lib
29678 @end smallexample
29679
29680 @noindent
29681 If you use the above command the definition file @file{API.def} must
29682 contain a line giving the name of the DLL:
29683
29684 @smallexample
29685 LIBRARY      "API"
29686 @end smallexample
29687
29688 @noindent
29689 See the Microsoft documentation for further details about the usage of
29690 @code{lib}.
29691 @end enumerate
29692
29693 @node Building DLLs with GNAT
29694 @section Building DLLs with GNAT
29695 @cindex DLLs, building
29696
29697 @noindent
29698 This section explain how to build DLLs using the GNAT built-in DLL
29699 support. With the following procedure it is straight forward to build
29700 and use DLLs with GNAT.
29701
29702 @enumerate
29703
29704 @item building object files
29705
29706 The first step is to build all objects files that are to be included
29707 into the DLL. This is done by using the standard @command{gnatmake} tool.
29708
29709 @item building the DLL
29710
29711 To build the DLL you must use @command{gcc}'s @code{-shared}
29712 option. It is quite simple to use this method:
29713
29714 @smallexample
29715 $ gcc -shared -o api.dll obj1.o obj2.o ...
29716 @end smallexample
29717
29718 It is important to note that in this case all symbols found in the
29719 object files are automatically exported. It is possible to restrict
29720 the set of symbols to export by passing to @command{gcc} a definition
29721 file, @pxref{The Definition File}. For example:
29722
29723 @smallexample
29724 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
29725 @end smallexample
29726
29727 If you use a definition file you must export the elaboration procedures
29728 for every package that required one. Elaboration procedures are named
29729 using the package name followed by "_E".
29730
29731 @item preparing DLL to be used
29732
29733 For the DLL to be used by client programs the bodies must be hidden
29734 from it and the .ali set with read-only attribute. This is very important
29735 otherwise GNAT will recompile all packages and will not actually use
29736 the code in the DLL. For example:
29737
29738 @smallexample
29739 $ mkdir apilib
29740 $ copy *.ads *.ali api.dll apilib
29741 $ attrib +R apilib\*.ali
29742 @end smallexample
29743
29744 @end enumerate
29745
29746 At this point it is possible to use the DLL by directly linking
29747 against it. Note that you must use the GNAT shared runtime when using
29748 GNAT shared libraries. This is achieved by using @code{-shared} binder's
29749 option.
29750
29751 @smallexample
29752 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
29753 @end smallexample
29754
29755 @node Building DLLs with GNAT Project files
29756 @section Building DLLs with GNAT Project files
29757 @cindex DLLs, building
29758
29759 @noindent
29760 There is nothing specific to Windows in this area. @pxref{Library Projects}.
29761
29762 @node Building DLLs with gnatdll
29763 @section Building DLLs with gnatdll
29764 @cindex DLLs, building
29765
29766 @menu
29767 * Limitations When Using Ada DLLs from Ada::
29768 * Exporting Ada Entities::
29769 * Ada DLLs and Elaboration::
29770 * Ada DLLs and Finalization::
29771 * Creating a Spec for Ada DLLs::
29772 * Creating the Definition File::
29773 * Using gnatdll::
29774 @end menu
29775
29776 @noindent
29777 Note that it is preferred to use the built-in GNAT DLL support
29778 (@pxref{Building DLLs with GNAT}) or GNAT Project files
29779 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
29780
29781 This section explains how to build DLLs containing Ada code using
29782 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
29783 remainder of this section.
29784
29785 The steps required to build an Ada DLL that is to be used by Ada as well as
29786 non-Ada applications are as follows:
29787
29788 @enumerate
29789 @item
29790 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
29791 @code{Stdcall} calling convention to avoid any Ada name mangling for the
29792 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
29793 skip this step if you plan to use the Ada DLL only from Ada applications.
29794
29795 @item
29796 Your Ada code must export an initialization routine which calls the routine
29797 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
29798 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
29799 routine exported by the Ada DLL must be invoked by the clients of the DLL
29800 to initialize the DLL.
29801
29802 @item
29803 When useful, the DLL should also export a finalization routine which calls
29804 routine @code{adafinal} generated by @command{gnatbind} to perform the
29805 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
29806 The finalization routine exported by the Ada DLL must be invoked by the
29807 clients of the DLL when the DLL services are no further needed.
29808
29809 @item
29810 You must provide a spec for the services exported by the Ada DLL in each
29811 of the programming languages to which you plan to make the DLL available.
29812
29813 @item
29814 You must provide a definition file listing the exported entities
29815 (@pxref{The Definition File}).
29816
29817 @item
29818 Finally you must use @code{gnatdll} to produce the DLL and the import
29819 library (@pxref{Using gnatdll}).
29820 @end enumerate
29821
29822 @noindent
29823 Note that a relocatable DLL stripped using the @code{strip}
29824 binutils tool will not be relocatable anymore. To build a DLL without
29825 debug information pass @code{-largs -s} to @code{gnatdll}. This
29826 restriction does not apply to a DLL built using a Library Project.
29827 @pxref{Library Projects}.
29828
29829 @node Limitations When Using Ada DLLs from Ada
29830 @subsection Limitations When Using Ada DLLs from Ada
29831
29832 @noindent
29833 When using Ada DLLs from Ada applications there is a limitation users
29834 should be aware of. Because on Windows the GNAT run time is not in a DLL of
29835 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
29836 each Ada DLL includes the services of the GNAT run time that are necessary
29837 to the Ada code inside the DLL. As a result, when an Ada program uses an
29838 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
29839 one in the main program.
29840
29841 It is therefore not possible to exchange GNAT run-time objects between the
29842 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
29843 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
29844 types, etc.
29845
29846 It is completely safe to exchange plain elementary, array or record types,
29847 Windows object handles, etc.
29848
29849 @node Exporting Ada Entities
29850 @subsection Exporting Ada Entities
29851 @cindex Export table
29852
29853 @noindent
29854 Building a DLL is a way to encapsulate a set of services usable from any
29855 application. As a result, the Ada entities exported by a DLL should be
29856 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
29857 any Ada name mangling. As an example here is an Ada package
29858 @code{API}, spec and body, exporting two procedures, a function, and a
29859 variable:
29860
29861 @smallexample @c ada
29862 @group
29863 @cartouche
29864 with Interfaces.C; use Interfaces;
29865 package API is
29866    Count : C.int := 0;
29867    function Factorial (Val : C.int) return C.int;
29868
29869    procedure Initialize_API;
29870    procedure Finalize_API;
29871    --  Initialization & Finalization routines. More in the next section.
29872 private
29873    pragma Export (C, Initialize_API);
29874    pragma Export (C, Finalize_API);
29875    pragma Export (C, Count);
29876    pragma Export (C, Factorial);
29877 end API;
29878 @end cartouche
29879 @end group
29880 @end smallexample
29881
29882 @smallexample @c ada
29883 @group
29884 @cartouche
29885 package body API is
29886    function Factorial (Val : C.int) return C.int is
29887       Fact : C.int := 1;
29888    begin
29889       Count := Count + 1;
29890       for K in 1 .. Val loop
29891          Fact := Fact * K;
29892       end loop;
29893       return Fact;
29894    end Factorial;
29895
29896    procedure Initialize_API is
29897       procedure Adainit;
29898       pragma Import (C, Adainit);
29899    begin
29900       Adainit;
29901    end Initialize_API;
29902
29903    procedure Finalize_API is
29904       procedure Adafinal;
29905       pragma Import (C, Adafinal);
29906    begin
29907       Adafinal;
29908    end Finalize_API;
29909 end API;
29910 @end cartouche
29911 @end group
29912 @end smallexample
29913
29914 @noindent
29915 If the Ada DLL you are building will only be used by Ada applications
29916 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
29917 convention. As an example, the previous package could be written as
29918 follows:
29919
29920 @smallexample @c ada
29921 @group
29922 @cartouche
29923 package API is
29924    Count : Integer := 0;
29925    function Factorial (Val : Integer) return Integer;
29926
29927    procedure Initialize_API;
29928    procedure Finalize_API;
29929    --  Initialization and Finalization routines.
29930 end API;
29931 @end cartouche
29932 @end group
29933 @end smallexample
29934
29935 @smallexample @c ada
29936 @group
29937 @cartouche
29938 package body API is
29939    function Factorial (Val : Integer) return Integer is
29940       Fact : Integer := 1;
29941    begin
29942       Count := Count + 1;
29943       for K in 1 .. Val loop
29944          Fact := Fact * K;
29945       end loop;
29946       return Fact;
29947    end Factorial;
29948
29949    ...
29950    --  The remainder of this package body is unchanged.
29951 end API;
29952 @end cartouche
29953 @end group
29954 @end smallexample
29955
29956 @noindent
29957 Note that if you do not export the Ada entities with a @code{C} or
29958 @code{Stdcall} convention you will have to provide the mangled Ada names
29959 in the definition file of the Ada DLL
29960 (@pxref{Creating the Definition File}).
29961
29962 @node Ada DLLs and Elaboration
29963 @subsection Ada DLLs and Elaboration
29964 @cindex DLLs and elaboration
29965
29966 @noindent
29967 The DLL that you are building contains your Ada code as well as all the
29968 routines in the Ada library that are needed by it. The first thing a
29969 user of your DLL must do is elaborate the Ada code
29970 (@pxref{Elaboration Order Handling in GNAT}).
29971
29972 To achieve this you must export an initialization routine
29973 (@code{Initialize_API} in the previous example), which must be invoked
29974 before using any of the DLL services. This elaboration routine must call
29975 the Ada elaboration routine @code{adainit} generated by the GNAT binder
29976 (@pxref{Binding with Non-Ada Main Programs}). See the body of
29977 @code{Initialize_Api} for an example. Note that the GNAT binder is
29978 automatically invoked during the DLL build process by the @code{gnatdll}
29979 tool (@pxref{Using gnatdll}).
29980
29981 When a DLL is loaded, Windows systematically invokes a routine called
29982 @code{DllMain}. It would therefore be possible to call @code{adainit}
29983 directly from @code{DllMain} without having to provide an explicit
29984 initialization routine. Unfortunately, it is not possible to call
29985 @code{adainit} from the @code{DllMain} if your program has library level
29986 tasks because access to the @code{DllMain} entry point is serialized by
29987 the system (that is, only a single thread can execute ``through'' it at a
29988 time), which means that the GNAT run time will deadlock waiting for the
29989 newly created task to complete its initialization.
29990
29991 @node Ada DLLs and Finalization
29992 @subsection Ada DLLs and Finalization
29993 @cindex DLLs and finalization
29994
29995 @noindent
29996 When the services of an Ada DLL are no longer needed, the client code should
29997 invoke the DLL finalization routine, if available. The DLL finalization
29998 routine is in charge of releasing all resources acquired by the DLL. In the
29999 case of the Ada code contained in the DLL, this is achieved by calling
30000 routine @code{adafinal} generated by the GNAT binder
30001 (@pxref{Binding with Non-Ada Main Programs}).
30002 See the body of @code{Finalize_Api} for an
30003 example. As already pointed out the GNAT binder is automatically invoked
30004 during the DLL build process by the @code{gnatdll} tool
30005 (@pxref{Using gnatdll}).
30006
30007 @node Creating a Spec for Ada DLLs
30008 @subsection Creating a Spec for Ada DLLs
30009
30010 @noindent
30011 To use the services exported by the Ada DLL from another programming
30012 language (e.g. C), you have to translate the specs of the exported Ada
30013 entities in that language. For instance in the case of @code{API.dll},
30014 the corresponding C header file could look like:
30015
30016 @smallexample
30017 @group
30018 @cartouche
30019 extern int *_imp__count;
30020 #define count (*_imp__count)
30021 int factorial (int);
30022 @end cartouche
30023 @end group
30024 @end smallexample
30025
30026 @noindent
30027 It is important to understand that when building an Ada DLL to be used by
30028 other Ada applications, you need two different specs for the packages
30029 contained in the DLL: one for building the DLL and the other for using
30030 the DLL. This is because the @code{DLL} calling convention is needed to
30031 use a variable defined in a DLL, but when building the DLL, the variable
30032 must have either the @code{Ada} or @code{C} calling convention. As an
30033 example consider a DLL comprising the following package @code{API}:
30034
30035 @smallexample @c ada
30036 @group
30037 @cartouche
30038 package API is
30039    Count : Integer := 0;
30040    ...
30041    --  Remainder of the package omitted.
30042 end API;
30043 @end cartouche
30044 @end group
30045 @end smallexample
30046
30047 @noindent
30048 After producing a DLL containing package @code{API}, the spec that
30049 must be used to import @code{API.Count} from Ada code outside of the
30050 DLL is:
30051
30052 @smallexample @c ada
30053 @group
30054 @cartouche
30055 package API is
30056    Count : Integer;
30057    pragma Import (DLL, Count);
30058 end API;
30059 @end cartouche
30060 @end group
30061 @end smallexample
30062
30063 @node Creating the Definition File
30064 @subsection Creating the Definition File
30065
30066 @noindent
30067 The definition file is the last file needed to build the DLL. It lists
30068 the exported symbols. As an example, the definition file for a DLL
30069 containing only package @code{API} (where all the entities are exported
30070 with a @code{C} calling convention) is:
30071
30072 @smallexample
30073 @group
30074 @cartouche
30075 EXPORTS
30076     count
30077     factorial
30078     finalize_api
30079     initialize_api
30080 @end cartouche
30081 @end group
30082 @end smallexample
30083
30084 @noindent
30085 If the @code{C} calling convention is missing from package @code{API},
30086 then the definition file contains the mangled Ada names of the above
30087 entities, which in this case are:
30088
30089 @smallexample
30090 @group
30091 @cartouche
30092 EXPORTS
30093     api__count
30094     api__factorial
30095     api__finalize_api
30096     api__initialize_api
30097 @end cartouche
30098 @end group
30099 @end smallexample
30100
30101 @node Using gnatdll
30102 @subsection Using @code{gnatdll}
30103 @findex gnatdll
30104
30105 @menu
30106 * gnatdll Example::
30107 * gnatdll behind the Scenes::
30108 * Using dlltool::
30109 @end menu
30110
30111 @noindent
30112 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
30113 and non-Ada sources that make up your DLL have been compiled.
30114 @code{gnatdll} is actually in charge of two distinct tasks: build the
30115 static import library for the DLL and the actual DLL. The form of the
30116 @code{gnatdll} command is
30117
30118 @smallexample
30119 @cartouche
30120 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
30121 @end cartouche
30122 @end smallexample
30123
30124 @noindent
30125 where @i{list-of-files} is a list of ALI and object files. The object
30126 file list must be the exact list of objects corresponding to the non-Ada
30127 sources whose services are to be included in the DLL. The ALI file list
30128 must be the exact list of ALI files for the corresponding Ada sources
30129 whose services are to be included in the DLL. If @i{list-of-files} is
30130 missing, only the static import library is generated.
30131
30132 @noindent
30133 You may specify any of the following switches to @code{gnatdll}:
30134
30135 @table @code
30136 @item -a[@var{address}]
30137 @cindex @option{-a} (@code{gnatdll})
30138 Build a non-relocatable DLL at @var{address}. If @var{address} is not
30139 specified the default address @var{0x11000000} will be used. By default,
30140 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
30141 advise the reader to build relocatable DLL.
30142
30143 @item -b @var{address}
30144 @cindex @option{-b} (@code{gnatdll})
30145 Set the relocatable DLL base address. By default the address is
30146 @var{0x11000000}.
30147
30148 @item -bargs @var{opts}
30149 @cindex @option{-bargs} (@code{gnatdll})
30150 Binder options. Pass @var{opts} to the binder.
30151
30152 @item -d @var{dllfile}
30153 @cindex @option{-d} (@code{gnatdll})
30154 @var{dllfile} is the name of the DLL. This switch must be present for
30155 @code{gnatdll} to do anything. The name of the generated import library is
30156 obtained algorithmically from @var{dllfile} as shown in the following
30157 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
30158 @code{libxyz.a}. The name of the definition file to use (if not specified
30159 by option @option{-e}) is obtained algorithmically from @var{dllfile}
30160 as shown in the following example:
30161 if @var{dllfile} is @code{xyz.dll}, the definition
30162 file used is @code{xyz.def}.
30163
30164 @item -e @var{deffile}
30165 @cindex @option{-e} (@code{gnatdll})
30166 @var{deffile} is the name of the definition file.
30167
30168 @item -g
30169 @cindex @option{-g} (@code{gnatdll})
30170 Generate debugging information. This information is stored in the object
30171 file and copied from there to the final DLL file by the linker,
30172 where it can be read by the debugger. You must use the
30173 @option{-g} switch if you plan on using the debugger or the symbolic
30174 stack traceback.
30175
30176 @item -h
30177 @cindex @option{-h} (@code{gnatdll})
30178 Help mode. Displays @code{gnatdll} switch usage information.
30179
30180 @item -Idir
30181 @cindex @option{-I} (@code{gnatdll})
30182 Direct @code{gnatdll} to search the @var{dir} directory for source and
30183 object files needed to build the DLL.
30184 (@pxref{Search Paths and the Run-Time Library (RTL)}).
30185
30186 @item -k
30187 @cindex @option{-k} (@code{gnatdll})
30188 Removes the @code{@@}@i{nn} suffix from the import library's exported
30189 names, but keeps them for the link names. You must specify this
30190 option if you want to use a @code{Stdcall} function in a DLL for which
30191 the @code{@@}@i{nn} suffix has been removed. This is the case for most
30192 of the Windows NT DLL for example. This option has no effect when
30193 @option{-n} option is specified.
30194
30195 @item -l @var{file}
30196 @cindex @option{-l} (@code{gnatdll})
30197 The list of ALI and object files used to build the DLL are listed in
30198 @var{file}, instead of being given in the command line. Each line in
30199 @var{file} contains the name of an ALI or object file.
30200
30201 @item -n
30202 @cindex @option{-n} (@code{gnatdll})
30203 No Import. Do not create the import library.
30204
30205 @item -q
30206 @cindex @option{-q} (@code{gnatdll})
30207 Quiet mode. Do not display unnecessary messages.
30208
30209 @item -v
30210 @cindex @option{-v} (@code{gnatdll})
30211 Verbose mode. Display extra information.
30212
30213 @item -largs @var{opts}
30214 @cindex @option{-largs} (@code{gnatdll})
30215 Linker options. Pass @var{opts} to the linker.
30216 @end table
30217
30218 @node gnatdll Example
30219 @subsubsection @code{gnatdll} Example
30220
30221 @noindent
30222 As an example the command to build a relocatable DLL from @file{api.adb}
30223 once @file{api.adb} has been compiled and @file{api.def} created is
30224
30225 @smallexample
30226 $ gnatdll -d api.dll api.ali
30227 @end smallexample
30228
30229 @noindent
30230 The above command creates two files: @file{libapi.a} (the import
30231 library) and @file{api.dll} (the actual DLL). If you want to create
30232 only the DLL, just type:
30233
30234 @smallexample
30235 $ gnatdll -d api.dll -n api.ali
30236 @end smallexample
30237
30238 @noindent
30239 Alternatively if you want to create just the import library, type:
30240
30241 @smallexample
30242 $ gnatdll -d api.dll
30243 @end smallexample
30244
30245 @node gnatdll behind the Scenes
30246 @subsubsection @code{gnatdll} behind the Scenes
30247
30248 @noindent
30249 This section details the steps involved in creating a DLL. @code{gnatdll}
30250 does these steps for you. Unless you are interested in understanding what
30251 goes on behind the scenes, you should skip this section.
30252
30253 We use the previous example of a DLL containing the Ada package @code{API},
30254 to illustrate the steps necessary to build a DLL. The starting point is a
30255 set of objects that will make up the DLL and the corresponding ALI
30256 files. In the case of this example this means that @file{api.o} and
30257 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
30258 the following:
30259
30260 @enumerate
30261 @item
30262 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
30263 the information necessary to generate relocation information for the
30264 DLL.
30265
30266 @smallexample
30267 @group
30268 $ gnatbind -n api
30269 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
30270 @end group
30271 @end smallexample
30272
30273 @noindent
30274 In addition to the base file, the @command{gnatlink} command generates an
30275 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
30276 asks @command{gnatlink} to generate the routines @code{DllMain} and
30277 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
30278 is loaded into memory.
30279
30280 @item
30281 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
30282 export table (@file{api.exp}). The export table contains the relocation
30283 information in a form which can be used during the final link to ensure
30284 that the Windows loader is able to place the DLL anywhere in memory.
30285
30286 @smallexample
30287 @group
30288 $ dlltool --dllname api.dll --def api.def --base-file api.base \
30289           --output-exp api.exp
30290 @end group
30291 @end smallexample
30292
30293 @item
30294 @code{gnatdll} builds the base file using the new export table. Note that
30295 @command{gnatbind} must be called once again since the binder generated file
30296 has been deleted during the previous call to @command{gnatlink}.
30297
30298 @smallexample
30299 @group
30300 $ gnatbind -n api
30301 $ gnatlink api -o api.jnk api.exp -mdll
30302       -Wl,--base-file,api.base
30303 @end group
30304 @end smallexample
30305
30306 @item
30307 @code{gnatdll} builds the new export table using the new base file and
30308 generates the DLL import library @file{libAPI.a}.
30309
30310 @smallexample
30311 @group
30312 $ dlltool --dllname api.dll --def api.def --base-file api.base \
30313           --output-exp api.exp --output-lib libAPI.a
30314 @end group
30315 @end smallexample
30316
30317 @item
30318 Finally @code{gnatdll} builds the relocatable DLL using the final export
30319 table.
30320
30321 @smallexample
30322 @group
30323 $ gnatbind -n api
30324 $ gnatlink api api.exp -o api.dll -mdll
30325 @end group
30326 @end smallexample
30327 @end enumerate
30328
30329 @node Using dlltool
30330 @subsubsection Using @code{dlltool}
30331
30332 @noindent
30333 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
30334 DLLs and static import libraries. This section summarizes the most
30335 common @code{dlltool} switches. The form of the @code{dlltool} command
30336 is
30337
30338 @smallexample
30339 $ dlltool [@var{switches}]
30340 @end smallexample
30341
30342 @noindent
30343 @code{dlltool} switches include:
30344
30345 @table @option
30346 @item --base-file @var{basefile}
30347 @cindex @option{--base-file} (@command{dlltool})
30348 Read the base file @var{basefile} generated by the linker. This switch
30349 is used to create a relocatable DLL.
30350
30351 @item --def @var{deffile}
30352 @cindex @option{--def} (@command{dlltool})
30353 Read the definition file.
30354
30355 @item --dllname @var{name}
30356 @cindex @option{--dllname} (@command{dlltool})
30357 Gives the name of the DLL. This switch is used to embed the name of the
30358 DLL in the static import library generated by @code{dlltool} with switch
30359 @option{--output-lib}.
30360
30361 @item -k
30362 @cindex @option{-k} (@command{dlltool})
30363 Kill @code{@@}@i{nn} from exported names
30364 (@pxref{Windows Calling Conventions}
30365 for a discussion about @code{Stdcall}-style symbols.
30366
30367 @item --help
30368 @cindex @option{--help} (@command{dlltool})
30369 Prints the @code{dlltool} switches with a concise description.
30370
30371 @item --output-exp @var{exportfile}
30372 @cindex @option{--output-exp} (@command{dlltool})
30373 Generate an export file @var{exportfile}. The export file contains the
30374 export table (list of symbols in the DLL) and is used to create the DLL.
30375
30376 @item --output-lib @i{libfile}
30377 @cindex @option{--output-lib} (@command{dlltool})
30378 Generate a static import library @var{libfile}.
30379
30380 @item -v
30381 @cindex @option{-v} (@command{dlltool})
30382 Verbose mode.
30383
30384 @item --as @i{assembler-name}
30385 @cindex @option{--as} (@command{dlltool})
30386 Use @i{assembler-name} as the assembler. The default is @code{as}.
30387 @end table
30388
30389 @node GNAT and Windows Resources
30390 @section GNAT and Windows Resources
30391 @cindex Resources, windows
30392
30393 @menu
30394 * Building Resources::
30395 * Compiling Resources::
30396 * Using Resources::
30397 @end menu
30398
30399 @noindent
30400 Resources are an easy way to add Windows specific objects to your
30401 application. The objects that can be added as resources include:
30402
30403 @itemize @bullet
30404 @item
30405 menus
30406
30407 @item
30408 accelerators
30409
30410 @item
30411 dialog boxes
30412
30413 @item
30414 string tables
30415
30416 @item
30417 bitmaps
30418
30419 @item
30420 cursors
30421
30422 @item
30423 icons
30424
30425 @item
30426 fonts
30427 @end itemize
30428
30429 @noindent
30430 This section explains how to build, compile and use resources.
30431
30432 @node Building Resources
30433 @subsection Building Resources
30434 @cindex Resources, building
30435
30436 @noindent
30437 A resource file is an ASCII file. By convention resource files have an
30438 @file{.rc} extension.
30439 The easiest way to build a resource file is to use Microsoft tools
30440 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
30441 @code{dlgedit.exe} to build dialogs.
30442 It is always possible to build an @file{.rc} file yourself by writing a
30443 resource script.
30444
30445 It is not our objective to explain how to write a resource file. A
30446 complete description of the resource script language can be found in the
30447 Microsoft documentation.
30448
30449 @node Compiling Resources
30450 @subsection Compiling Resources
30451 @findex rc
30452 @findex windres
30453 @cindex Resources, compiling
30454
30455 @noindent
30456 This section describes how to build a GNAT-compatible (COFF) object file
30457 containing the resources. This is done using the Resource Compiler
30458 @code{windres} as follows:
30459
30460 @smallexample
30461 $ windres -i myres.rc -o myres.o
30462 @end smallexample
30463
30464 @noindent
30465 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
30466 file. You can specify an alternate preprocessor (usually named
30467 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
30468 parameter. A list of all possible options may be obtained by entering
30469 the command @code{windres} @option{--help}.
30470
30471 It is also possible to use the Microsoft resource compiler @code{rc.exe}
30472 to produce a @file{.res} file (binary resource file). See the
30473 corresponding Microsoft documentation for further details. In this case
30474 you need to use @code{windres} to translate the @file{.res} file to a
30475 GNAT-compatible object file as follows:
30476
30477 @smallexample
30478 $ windres -i myres.res -o myres.o
30479 @end smallexample
30480
30481 @node Using Resources
30482 @subsection Using Resources
30483 @cindex Resources, using
30484
30485 @noindent
30486 To include the resource file in your program just add the
30487 GNAT-compatible object file for the resource(s) to the linker
30488 arguments. With @command{gnatmake} this is done by using the @option{-largs}
30489 option:
30490
30491 @smallexample
30492 $ gnatmake myprog -largs myres.o
30493 @end smallexample
30494
30495 @node Debugging a DLL
30496 @section Debugging a DLL
30497 @cindex DLL debugging
30498
30499 @menu
30500 * Program and DLL Both Built with GCC/GNAT::
30501 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
30502 @end menu
30503
30504 @noindent
30505 Debugging a DLL is similar to debugging a standard program. But
30506 we have to deal with two different executable parts: the DLL and the
30507 program that uses it. We have the following four possibilities:
30508
30509 @enumerate 1
30510 @item
30511 The program and the DLL are built with @code{GCC/GNAT}.
30512 @item
30513 The program is built with foreign tools and the DLL is built with
30514 @code{GCC/GNAT}.
30515 @item
30516 The program is built with @code{GCC/GNAT} and the DLL is built with
30517 foreign tools.
30518 @item
30519 @end enumerate
30520
30521 @noindent
30522 In this section we address only cases one and two above.
30523 There is no point in trying to debug
30524 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
30525 information in it. To do so you must use a debugger compatible with the
30526 tools suite used to build the DLL.
30527
30528 @node Program and DLL Both Built with GCC/GNAT
30529 @subsection Program and DLL Both Built with GCC/GNAT
30530
30531 @noindent
30532 This is the simplest case. Both the DLL and the program have @code{GDB}
30533 compatible debugging information. It is then possible to break anywhere in
30534 the process. Let's suppose here that the main procedure is named
30535 @code{ada_main} and that in the DLL there is an entry point named
30536 @code{ada_dll}.
30537
30538 @noindent
30539 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
30540 program must have been built with the debugging information (see GNAT -g
30541 switch). Here are the step-by-step instructions for debugging it:
30542
30543 @enumerate 1
30544 @item Launch @code{GDB} on the main program.
30545
30546 @smallexample
30547 $ gdb -nw ada_main
30548 @end smallexample
30549
30550 @item Start the program and stop at the beginning of the main procedure
30551
30552 @smallexample
30553 (gdb) start
30554 @end smallexample
30555
30556 @noindent
30557 This step is required to be able to set a breakpoint inside the DLL. As long
30558 as the program is not run, the DLL is not loaded. This has the
30559 consequence that the DLL debugging information is also not loaded, so it is not
30560 possible to set a breakpoint in the DLL.
30561
30562 @item Set a breakpoint inside the DLL
30563
30564 @smallexample
30565 (gdb) break ada_dll
30566 (gdb) cont
30567 @end smallexample
30568
30569 @end enumerate
30570
30571 @noindent
30572 At this stage a breakpoint is set inside the DLL. From there on
30573 you can use the standard approach to debug the whole program
30574 (@pxref{Running and Debugging Ada Programs}).
30575
30576 @ignore
30577 @c This used to work, probably because the DLLs were non-relocatable
30578 @c keep this section around until the problem is sorted out.
30579
30580 To break on the @code{DllMain} routine it is not possible to follow
30581 the procedure above. At the time the program stop on @code{ada_main}
30582 the @code{DllMain} routine as already been called. Either you can use
30583 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
30584
30585 @enumerate 1
30586 @item Launch @code{GDB} on the main program.
30587
30588 @smallexample
30589 $ gdb ada_main
30590 @end smallexample
30591
30592 @item Load DLL symbols
30593
30594 @smallexample
30595 (gdb) add-sym api.dll
30596 @end smallexample
30597
30598 @item Set a breakpoint inside the DLL
30599
30600 @smallexample
30601 (gdb) break ada_dll.adb:45
30602 @end smallexample
30603
30604 Note that at this point it is not possible to break using the routine symbol
30605 directly as the program is not yet running. The solution is to break
30606 on the proper line (break in @file{ada_dll.adb} line 45).
30607
30608 @item Start the program
30609
30610 @smallexample
30611 (gdb) run
30612 @end smallexample
30613
30614 @end enumerate
30615 @end ignore
30616
30617 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
30618 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
30619
30620 @menu
30621 * Debugging the DLL Directly::
30622 * Attaching to a Running Process::
30623 @end menu
30624
30625 @noindent
30626 In this case things are slightly more complex because it is not possible to
30627 start the main program and then break at the beginning to load the DLL and the
30628 associated DLL debugging information. It is not possible to break at the
30629 beginning of the program because there is no @code{GDB} debugging information,
30630 and therefore there is no direct way of getting initial control. This
30631 section addresses this issue by describing some methods that can be used
30632 to break somewhere in the DLL to debug it.
30633
30634 @noindent
30635 First suppose that the main procedure is named @code{main} (this is for
30636 example some C code built with Microsoft Visual C) and that there is a
30637 DLL named @code{test.dll} containing an Ada entry point named
30638 @code{ada_dll}.
30639
30640 @noindent
30641 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
30642 been built with debugging information (see GNAT -g option).
30643
30644 @node Debugging the DLL Directly
30645 @subsubsection Debugging the DLL Directly
30646
30647 @enumerate 1
30648 @item
30649 Find out the executable starting address
30650
30651 @smallexample
30652 $ objdump --file-header main.exe
30653 @end smallexample
30654
30655 The starting address is reported on the last line. For example:
30656
30657 @smallexample
30658 main.exe:     file format pei-i386
30659 architecture: i386, flags 0x0000010a:
30660 EXEC_P, HAS_DEBUG, D_PAGED
30661 start address 0x00401010
30662 @end smallexample
30663
30664 @item
30665 Launch the debugger on the executable.
30666
30667 @smallexample
30668 $ gdb main.exe
30669 @end smallexample
30670
30671 @item
30672 Set a breakpoint at the starting address, and launch the program.
30673
30674 @smallexample
30675 $ (gdb) break *0x00401010
30676 $ (gdb) run
30677 @end smallexample
30678
30679 The program will stop at the given address.
30680
30681 @item
30682 Set a breakpoint on a DLL subroutine.
30683
30684 @smallexample
30685 (gdb) break ada_dll.adb:45
30686 @end smallexample
30687
30688 Or if you want to break using a symbol on the DLL, you need first to
30689 select the Ada language (language used by the DLL).
30690
30691 @smallexample
30692 (gdb) set language ada
30693 (gdb) break ada_dll
30694 @end smallexample
30695
30696 @item
30697 Continue the program.
30698
30699 @smallexample
30700 (gdb) cont
30701 @end smallexample
30702
30703 @noindent
30704 This will run the program until it reaches the breakpoint that has been
30705 set. From that point you can use the standard way to debug a program
30706 as described in (@pxref{Running and Debugging Ada Programs}).
30707
30708 @end enumerate
30709
30710 @noindent
30711 It is also possible to debug the DLL by attaching to a running process.
30712
30713 @node Attaching to a Running Process
30714 @subsubsection Attaching to a Running Process
30715 @cindex DLL debugging, attach to process
30716
30717 @noindent
30718 With @code{GDB} it is always possible to debug a running process by
30719 attaching to it. It is possible to debug a DLL this way. The limitation
30720 of this approach is that the DLL must run long enough to perform the
30721 attach operation. It may be useful for instance to insert a time wasting
30722 loop in the code of the DLL to meet this criterion.
30723
30724 @enumerate 1
30725
30726 @item Launch the main program @file{main.exe}.
30727
30728 @smallexample
30729 $ main
30730 @end smallexample
30731
30732 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
30733 that the process PID for @file{main.exe} is 208.
30734
30735 @item Launch gdb.
30736
30737 @smallexample
30738 $ gdb
30739 @end smallexample
30740
30741 @item Attach to the running process to be debugged.
30742
30743 @smallexample
30744 (gdb) attach 208
30745 @end smallexample
30746
30747 @item Load the process debugging information.
30748
30749 @smallexample
30750 (gdb) symbol-file main.exe
30751 @end smallexample
30752
30753 @item Break somewhere in the DLL.
30754
30755 @smallexample
30756 (gdb) break ada_dll
30757 @end smallexample
30758
30759 @item Continue process execution.
30760
30761 @smallexample
30762 (gdb) cont
30763 @end smallexample
30764
30765 @end enumerate
30766
30767 @noindent
30768 This last step will resume the process execution, and stop at
30769 the breakpoint we have set. From there you can use the standard
30770 approach to debug a program as described in
30771 (@pxref{Running and Debugging Ada Programs}).
30772
30773 @node Setting Stack Size from gnatlink
30774 @section Setting Stack Size from @command{gnatlink}
30775
30776 @noindent
30777 It is possible to specify the program stack size at link time. On modern
30778 versions of Windows, starting with XP, this is mostly useful to set the size of
30779 the main stack (environment task). The other task stacks are set with pragma
30780 Storage_Size or with the @command{gnatbind -d} command.
30781
30782 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
30783 reserve size of individual tasks, the link-time stack size applies to all
30784 tasks, and pragma Storage_Size has no effect.
30785 In particular, Stack Overflow checks are made against this
30786 link-time specified size.
30787
30788 This setting can be done with
30789 @command{gnatlink} using either:
30790
30791 @itemize @bullet
30792
30793 @item using @option{-Xlinker} linker option
30794
30795 @smallexample
30796 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
30797 @end smallexample
30798
30799 This sets the stack reserve size to 0x10000 bytes and the stack commit
30800 size to 0x1000 bytes.
30801
30802 @item using @option{-Wl} linker option
30803
30804 @smallexample
30805 $ gnatlink hello -Wl,--stack=0x1000000
30806 @end smallexample
30807
30808 This sets the stack reserve size to 0x1000000 bytes. Note that with
30809 @option{-Wl} option it is not possible to set the stack commit size
30810 because the coma is a separator for this option.
30811
30812 @end itemize
30813
30814 @node Setting Heap Size from gnatlink
30815 @section Setting Heap Size from @command{gnatlink}
30816
30817 @noindent
30818 Under Windows systems, it is possible to specify the program heap size from
30819 @command{gnatlink} using either:
30820
30821 @itemize @bullet
30822
30823 @item using @option{-Xlinker} linker option
30824
30825 @smallexample
30826 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
30827 @end smallexample
30828
30829 This sets the heap reserve size to 0x10000 bytes and the heap commit
30830 size to 0x1000 bytes.
30831
30832 @item using @option{-Wl} linker option
30833
30834 @smallexample
30835 $ gnatlink hello -Wl,--heap=0x1000000
30836 @end smallexample
30837
30838 This sets the heap reserve size to 0x1000000 bytes. Note that with
30839 @option{-Wl} option it is not possible to set the heap commit size
30840 because the coma is a separator for this option.
30841
30842 @end itemize
30843
30844 @end ifset
30845
30846 @c **********************************
30847 @c * GNU Free Documentation License *
30848 @c **********************************
30849 @include fdl.texi
30850 @c GNU Free Documentation License
30851
30852 @node Index,,GNU Free Documentation License, Top
30853 @unnumbered Index
30854
30855 @printindex cp
30856
30857 @contents
30858 @c Put table of contents at end, otherwise it precedes the "title page" in
30859 @c the .txt version
30860 @c Edit the pdf file to move the contents to the beginning, after the title
30861 @c page
30862
30863 @bye