OSDN Git Service

2007-12-06 Robert Dewar <dewar@adacore.com>
[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 * Conditional Compilation::
209 * Inline Assembler::
210 * Compatibility and Porting Guide::
211 @ifset unw
212 * Microsoft Windows Topics::
213 @end ifset
214 * GNU Free Documentation License::
215 * Index::
216
217  --- The Detailed Node Listing ---
218
219 About This Guide
220
221 * What This Guide Contains::
222 * What You Should Know before Reading This Guide::
223 * Related Information::
224 * Conventions::
225
226 Getting Started with GNAT
227
228 * Running GNAT::
229 * Running a Simple Ada Program::
230 * Running a Program with Multiple Units::
231 * Using the gnatmake Utility::
232 @ifset vms
233 * Editing with Emacs::
234 @end ifset
235 @ifclear vms
236 * Introduction to GPS::
237 @end ifclear
238
239 The GNAT Compilation Model
240
241 * Source Representation::
242 * Foreign Language Representation::
243 * File Naming Rules::
244 * Using Other File Names::
245 * Alternative File Naming Schemes::
246 * Generating Object Files::
247 * Source Dependencies::
248 * The Ada Library Information Files::
249 * Binding an Ada Program::
250 * Mixed Language Programming::
251 @ifclear vms
252 * Building Mixed Ada & C++ Programs::
253 * Comparison between GNAT and C/C++ Compilation Models::
254 @end ifclear
255 * Comparison between GNAT and Conventional Ada Library Models::
256 @ifset vms
257 * Placement of temporary files::
258 @end ifset
259
260 Foreign Language Representation
261
262 * Latin-1::
263 * Other 8-Bit Codes::
264 * Wide Character Encodings::
265
266 Compiling Ada Programs With gcc
267
268 * Compiling Programs::
269 * Switches for gcc::
270 * Search Paths and the Run-Time Library (RTL)::
271 * Order of Compilation Issues::
272 * Examples::
273
274 Switches for gcc
275
276 * Output and Error Message Control::
277 * Warning Message Control::
278 * Debugging and Assertion Control::
279 * Validity Checking::
280 * Style Checking::
281 * Run-Time Checks::
282 * Using gcc for Syntax Checking::
283 * Using gcc for Semantic Checking::
284 * Compiling Different Versions of Ada::
285 * Character Set Control::
286 * File Naming Control::
287 * Subprogram Inlining Control::
288 * Auxiliary Output Control::
289 * Debugging Control::
290 * Exception Handling Control::
291 * Units to Sources Mapping Files::
292 * Integrated Preprocessing::
293 @ifset vms
294 * Return Codes::
295 @end ifset
296
297 Binding Ada Programs With gnatbind
298
299 * Running gnatbind::
300 * Switches for gnatbind::
301 * Command-Line Access::
302 * Search Paths for gnatbind::
303 * Examples of gnatbind Usage::
304
305 Switches for gnatbind
306
307 * Consistency-Checking Modes::
308 * Binder Error Message Control::
309 * Elaboration Control::
310 * Output Control::
311 * Binding with Non-Ada Main Programs::
312 * Binding Programs with No Main Subprogram::
313
314 Linking Using gnatlink
315
316 * Running gnatlink::
317 * Switches for gnatlink::
318
319 The GNAT Make Program gnatmake
320
321 * Running gnatmake::
322 * Switches for gnatmake::
323 * Mode Switches for gnatmake::
324 * Notes on the Command Line::
325 * How gnatmake Works::
326 * Examples of gnatmake Usage::
327
328 Improving Performance
329 * Performance Considerations::
330 * Reducing Size of Ada Executables with gnatelim::
331 * Reducing Size of Executables with unused subprogram/data elimination::
332
333 Performance Considerations
334 * Controlling Run-Time Checks::
335 * Use of Restrictions::
336 * Optimization Levels::
337 * Debugging Optimized Code::
338 * Inlining of Subprograms::
339 * Other Optimization Switches::
340 * Optimization and Strict Aliasing::
341 @ifset vms
342 * Coverage Analysis::
343 @end ifset
344
345 Reducing Size of Ada Executables with gnatelim
346 * About gnatelim::
347 * Running gnatelim::
348 * Correcting the List of Eliminate Pragmas::
349 * Making Your Executables Smaller::
350 * Summary of the gnatelim Usage Cycle::
351
352 Reducing Size of Executables with unused subprogram/data elimination
353 * About unused subprogram/data elimination::
354 * Compilation options::
355
356 Renaming Files Using gnatchop
357
358 * Handling Files with Multiple Units::
359 * Operating gnatchop in Compilation Mode::
360 * Command Line for gnatchop::
361 * Switches for gnatchop::
362 * Examples of gnatchop Usage::
363
364 Configuration Pragmas
365
366 * Handling of Configuration Pragmas::
367 * The Configuration Pragmas Files::
368
369 Handling Arbitrary File Naming Conventions Using gnatname
370
371 * Arbitrary File Naming Conventions::
372 * Running gnatname::
373 * Switches for gnatname::
374 * Examples of gnatname Usage::
375
376 GNAT Project Manager
377
378 * Introduction::
379 * Examples of Project Files::
380 * Project File Syntax::
381 * Objects and Sources in Project Files::
382 * Importing Projects::
383 * Project Extension::
384 * Project Hierarchy Extension::
385 * External References in Project Files::
386 * Packages in Project Files::
387 * Variables from Imported Projects::
388 * Naming Schemes::
389 * Library Projects::
390 * Stand-alone Library Projects::
391 * Switches Related to Project Files::
392 * Tools Supporting Project Files::
393 * An Extended Example::
394 * Project File Complete Syntax::
395
396 The Cross-Referencing Tools gnatxref and gnatfind
397
398 * gnatxref Switches::
399 * gnatfind Switches::
400 * Project Files for gnatxref and gnatfind::
401 * Regular Expressions in gnatfind and gnatxref::
402 * Examples of gnatxref Usage::
403 * Examples of gnatfind Usage::
404
405 The GNAT Pretty-Printer gnatpp
406
407 * Switches for gnatpp::
408 * Formatting Rules::
409
410 The GNAT Metrics Tool gnatmetric
411
412 * Switches for gnatmetric::
413
414 File Name Krunching Using gnatkr
415
416 * About gnatkr::
417 * Using gnatkr::
418 * Krunching Method::
419 * Examples of gnatkr Usage::
420
421 Preprocessing Using gnatprep
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 Conditional Compilation
614 * Use of Boolean Constants::
615 * Debugging - A Special Case::
616 * Conditionalizing Declarations::
617 * Use of Alternative Implementations::
618 * Preprocessing::
619
620 Inline Assembler
621
622 * Basic Assembler Syntax::
623 * A Simple Example of Inline Assembler::
624 * Output Variables in Inline Assembler::
625 * Input Variables in Inline Assembler::
626 * Inlining Inline Assembler Code::
627 * Other Asm Functionality::
628
629 Compatibility and Porting Guide
630
631 * Compatibility with Ada 83::
632 * Compatibility between Ada 95 and Ada 2005::
633 * Implementation-dependent characteristics::
634 @ifclear vms
635 @c This brief section is only in the non-VMS version
636 @c The complete chapter on HP Ada issues is in the VMS version
637 * Compatibility with HP Ada 83::
638 @end ifclear
639 * Compatibility with Other Ada Systems::
640 * Representation Clauses::
641 @ifset vms
642 * Transitioning to 64-Bit GNAT for OpenVMS::
643 @end ifset
644
645 @ifset unw
646 Microsoft Windows Topics
647
648 * Using GNAT on Windows::
649 * CONSOLE and WINDOWS subsystems::
650 * Temporary Files::
651 * Mixed-Language Programming on Windows::
652 * Windows Calling Conventions::
653 * Introduction to Dynamic Link Libraries (DLLs)::
654 * Using DLLs with GNAT::
655 * Building DLLs with GNAT::
656 * GNAT and Windows Resources::
657 * Debugging a DLL::
658 * Setting Stack Size from gnatlink::
659 * Setting Heap Size from gnatlink::
660 @end ifset
661
662 * Index::
663 @end menu
664 @end ifnottex
665
666 @node About This Guide
667 @unnumbered About This Guide
668
669 @noindent
670 @ifset vms
671 This guide describes the use of @value{EDITION},
672 a compiler and software development toolset for the full Ada
673 programming language, implemented on OpenVMS for HP's Alpha and
674 Integrity server (I64) platforms.
675 @end ifset
676 @ifclear vms
677 This guide describes the use of @value{EDITION},
678 a compiler and software development
679 toolset for the full Ada programming language.
680 @end ifclear
681 It documents the features of the compiler and tools, and explains
682 how to use them to build Ada applications.
683
684 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
685 Ada 83 compatibility mode.
686 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
687 but you can override with a compiler switch
688 (@pxref{Compiling Different Versions of Ada})
689 to explicitly specify the language version.
690 Throughout this manual, references to ``Ada'' without a year suffix
691 apply to both the Ada 95 and Ada 2005 versions of the language.
692
693
694 @ifclear FSFEDITION
695 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
696 ``GNAT'' in the remainder of this document.
697 @end ifclear
698
699
700
701
702 @menu
703 * What This Guide Contains::
704 * What You Should Know before Reading This Guide::
705 * Related Information::
706 * Conventions::
707 @end menu
708
709 @node What This Guide Contains
710 @unnumberedsec What This Guide Contains
711
712 @noindent
713 This guide contains the following chapters:
714 @itemize @bullet
715
716 @item
717 @ref{Getting Started with GNAT}, describes how to get started compiling
718 and running Ada programs with the GNAT Ada programming environment.
719 @item
720 @ref{The GNAT Compilation Model}, describes the compilation model used
721 by GNAT.
722
723 @item
724 @ref{Compiling Using gcc}, describes how to compile
725 Ada programs with @command{gcc}, the Ada compiler.
726
727 @item
728 @ref{Binding Using gnatbind}, describes how to
729 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
730 utility.
731
732 @item
733 @ref{Linking Using gnatlink},
734 describes @command{gnatlink}, a
735 program that provides for linking using the GNAT run-time library to
736 construct a program. @command{gnatlink} can also incorporate foreign language
737 object units into the executable.
738
739 @item
740 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
741 utility that automatically determines the set of sources
742 needed by an Ada compilation unit, and executes the necessary compilations
743 binding and link.
744
745 @item
746 @ref{Improving Performance}, shows various techniques for making your
747 Ada program run faster or take less space.
748 It discusses the effect of the compiler's optimization switch and
749 also describes the @command{gnatelim} tool and unused subprogram/data
750 elimination.
751
752 @item
753 @ref{Renaming Files Using gnatchop}, describes
754 @code{gnatchop}, a utility that allows you to preprocess a file that
755 contains Ada source code, and split it into one or more new files, one
756 for each compilation unit.
757
758 @item
759 @ref{Configuration Pragmas}, describes the configuration pragmas
760 handled by GNAT.
761
762 @item
763 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
764 shows how to override the default GNAT file naming conventions,
765 either for an individual unit or globally.
766
767 @item
768 @ref{GNAT Project Manager}, describes how to use project files
769 to organize large projects.
770
771 @item
772 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
773 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
774 way to navigate through sources.
775
776 @item
777 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
778 version of an Ada source file with control over casing, indentation,
779 comment placement, and other elements of program presentation style.
780
781 @item
782 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
783 metrics for an Ada source file, such as the number of types and subprograms,
784 and assorted complexity measures.
785
786 @item
787 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
788 file name krunching utility, used to handle shortened
789 file names on operating systems with a limit on the length of names.
790
791 @item
792 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
793 preprocessor utility that allows a single source file to be used to
794 generate multiple or parameterized source files by means of macro
795 substitution.
796
797 @ifset vms
798 @item
799 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
800 a tool for rebuilding the GNAT run time with user-supplied
801 configuration pragmas.
802 @end ifset
803
804 @item
805 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
806 utility that displays information about compiled units, including dependences
807 on the corresponding sources files, and consistency of compilations.
808
809 @item
810 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
811 to delete files that are produced by the compiler, binder and linker.
812
813 @ifclear vms
814 @item
815 @ref{GNAT and Libraries}, describes the process of creating and using
816 Libraries with GNAT. It also describes how to recompile the GNAT run-time
817 library.
818
819 @item
820 @ref{Using the GNU make Utility}, describes some techniques for using
821 the GNAT toolset in Makefiles.
822 @end ifclear
823
824 @item
825 @ref{Memory Management Issues}, describes some useful predefined storage pools
826 and in particular the GNAT Debug Pool facility, which helps detect incorrect
827 memory references.
828 @ifclear vms
829 It also describes @command{gnatmem}, a utility that monitors dynamic
830 allocation and deallocation and helps detect ``memory leaks''.
831 @end ifclear
832
833 @item
834 @ref{Stack Related Facilities}, describes some useful tools associated with
835 stack checking and analysis.
836
837 @item
838 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
839 a utility that checks Ada code against a set of rules.
840
841 @item
842 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
843 a utility that generates empty but compilable bodies for library units.
844
845 @item
846 @ref{Other Utility Programs}, discusses several other GNAT utilities,
847 including @code{gnathtml}.
848
849 @item
850 @ref{Running and Debugging Ada Programs}, describes how to run and debug
851 Ada programs.
852
853 @ifset vms
854 @item
855 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
856 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
857 developed by Digital Equipment Corporation and currently supported by HP.}
858 for OpenVMS Alpha. This product was formerly known as DEC Ada,
859 @cindex DEC Ada
860 and for
861 historical compatibility reasons, the relevant libraries still use the
862 DEC prefix.
863 @end ifset
864
865 @item
866 @ref{Platform-Specific Information for the Run-Time Libraries},
867 describes the various run-time
868 libraries supported by GNAT on various platforms and explains how to
869 choose a particular library.
870
871 @item
872 @ref{Example of Binder Output File}, shows the source code for the binder
873 output file for a sample program.
874
875 @item
876 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
877 you deal with elaboration order issues.
878
879 @item
880 @ref{Conditional Compilation}, describes how to model conditional compilation,
881 both with Ada in general and with GNAT facilities in particular.
882
883 @item
884 @ref{Inline Assembler}, shows how to use the inline assembly facility
885 in an Ada program.
886
887 @item
888 @ref{Compatibility and Porting Guide}, contains sections on compatibility
889 of GNAT with other Ada development environments (including Ada 83 systems),
890 to assist in porting code from those environments.
891
892 @ifset unw
893 @item
894 @ref{Microsoft Windows Topics}, presents information relevant to the
895 Microsoft Windows platform.
896 @end ifset
897 @end itemize
898
899 @c *************************************************
900 @node What You Should Know before Reading This Guide
901 @c *************************************************
902 @unnumberedsec What You Should Know before Reading This Guide
903
904 @cindex Ada 95 Language Reference Manual
905 @cindex Ada 2005 Language Reference Manual
906 @noindent
907 This guide assumes a basic familiarity with the Ada 95 language, as
908 described in the International Standard ANSI/ISO/IEC-8652:1995, January
909 1995.
910 It does not require knowledge of the new features introduced by Ada 2005,
911 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
912 and Amendment 1).
913 Both reference manuals are included in the GNAT documentation
914 package.
915
916 @node Related Information
917 @unnumberedsec Related Information
918
919 @noindent
920 For further information about related tools, refer to the following
921 documents:
922
923 @itemize @bullet
924 @item
925 @cite{GNAT Reference Manual}, which contains all reference
926 material for the GNAT implementation of Ada.
927
928 @ifset unw
929 @item
930 @cite{Using the GNAT Programming Studio}, which describes the GPS
931 Integrated Development Environment.
932
933 @item
934 @cite{GNAT Programming Studio Tutorial}, which introduces the
935 main GPS features through examples.
936 @end ifset
937
938 @item
939 @cite{Ada 95 Reference Manual}, which contains reference
940 material for the Ada 95 programming language.
941
942 @item
943 @cite{Ada 2005 Reference Manual}, which contains reference
944 material for the Ada 2005 programming language.
945
946 @item
947 @cite{Debugging with GDB}
948 @ifset vms
949 , located in the GNU:[DOCS] directory,
950 @end ifset
951 contains all details on the use of the GNU source-level debugger.
952
953 @item
954 @cite{GNU Emacs Manual}
955 @ifset vms
956 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
957 @end ifset
958 contains full information on the extensible editor and programming
959 environment Emacs.
960
961 @end itemize
962
963 @c **************
964 @node Conventions
965 @unnumberedsec Conventions
966 @cindex Conventions
967 @cindex Typographical conventions
968
969 @noindent
970 Following are examples of the typographical and graphic conventions used
971 in this guide:
972
973 @itemize @bullet
974 @item
975 @code{Functions}, @code{utility program names}, @code{standard names},
976 and @code{classes}.
977
978 @item
979 @samp{Option flags}
980
981 @item
982 @file{File Names}, @file{button names}, and @file{field names}.
983
984 @item
985 @var{Variables}.
986
987 @item
988 @emph{Emphasis}.
989
990 @item
991 [optional information or parameters]
992
993 @item
994 Examples are described by text
995 @smallexample
996 and then shown this way.
997 @end smallexample
998 @end itemize
999
1000 @noindent
1001 Commands that are entered by the user are preceded in this manual by the
1002 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1003 uses this sequence as a prompt, then the commands will appear exactly as
1004 you see them in the manual. If your system uses some other prompt, then
1005 the command will appear with the @code{$} replaced by whatever prompt
1006 character you are using.
1007
1008 @ifset unw
1009 Full file names are shown with the ``@code{/}'' character
1010 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1011 If you are using GNAT on a Windows platform, please note that
1012 the ``@code{\}'' character should be used instead.
1013 @end ifset
1014
1015 @c ****************************
1016 @node Getting Started with GNAT
1017 @chapter Getting Started with GNAT
1018
1019 @noindent
1020 This chapter describes some simple ways of using GNAT to build
1021 executable Ada programs.
1022 @ifset unw
1023 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1024 show how to use the command line environment.
1025 @ref{Introduction to GPS}, provides a brief
1026 introduction to the GNAT Programming Studio, a visually-oriented
1027 Integrated Development Environment for GNAT.
1028 GPS offers a graphical ``look and feel'', support for development in
1029 other programming languages, comprehensive browsing features, and
1030 many other capabilities.
1031 For information on GPS please refer to
1032 @cite{Using the GNAT Programming Studio}.
1033 @end ifset
1034
1035 @menu
1036 * Running GNAT::
1037 * Running a Simple Ada Program::
1038 * Running a Program with Multiple Units::
1039 * Using the gnatmake Utility::
1040 @ifset vms
1041 * Editing with Emacs::
1042 @end ifset
1043 @ifclear vms
1044 * Introduction to GPS::
1045 @end ifclear
1046 @end menu
1047
1048 @node Running GNAT
1049 @section Running GNAT
1050
1051 @noindent
1052 Three steps are needed to create an executable file from an Ada source
1053 file:
1054
1055 @enumerate
1056 @item
1057 The source file(s) must be compiled.
1058 @item
1059 The file(s) must be bound using the GNAT binder.
1060 @item
1061 All appropriate object files must be linked to produce an executable.
1062 @end enumerate
1063
1064 @noindent
1065 All three steps are most commonly handled by using the @command{gnatmake}
1066 utility program that, given the name of the main program, automatically
1067 performs the necessary compilation, binding and linking steps.
1068
1069 @node Running a Simple Ada Program
1070 @section Running a Simple Ada Program
1071
1072 @noindent
1073 Any text editor may be used to prepare an Ada program.
1074 (If @code{Emacs} is
1075 used, the optional Ada mode may be helpful in laying out the program.)
1076 The
1077 program text is a normal text file. We will assume in our initial
1078 example that you have used your editor to prepare the following
1079 standard format text file:
1080
1081 @smallexample @c ada
1082 @cartouche
1083 with Ada.Text_IO; use Ada.Text_IO;
1084 procedure Hello is
1085 begin
1086    Put_Line ("Hello WORLD!");
1087 end Hello;
1088 @end cartouche
1089 @end smallexample
1090
1091 @noindent
1092 This file should be named @file{hello.adb}.
1093 With the normal default file naming conventions, GNAT requires
1094 that each file
1095 contain a single compilation unit whose file name is the
1096 unit name,
1097 with periods replaced by hyphens; the
1098 extension is @file{ads} for a
1099 spec and @file{adb} for a body.
1100 You can override this default file naming convention by use of the
1101 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1102 Alternatively, if you want to rename your files according to this default
1103 convention, which is probably more convenient if you will be using GNAT
1104 for all your compilations, then the @code{gnatchop} utility
1105 can be used to generate correctly-named source files
1106 (@pxref{Renaming Files Using gnatchop}).
1107
1108 You can compile the program using the following command (@code{$} is used
1109 as the command prompt in the examples in this document):
1110
1111 @smallexample
1112 $ gcc -c hello.adb
1113 @end smallexample
1114
1115 @noindent
1116 @command{gcc} is the command used to run the compiler. This compiler is
1117 capable of compiling programs in several languages, including Ada and
1118 C. It assumes that you have given it an Ada program if the file extension is
1119 either @file{.ads} or @file{.adb}, and it will then call
1120 the GNAT compiler to compile the specified file.
1121
1122 @ifclear vms
1123 The @option{-c} switch is required. It tells @command{gcc} to only do a
1124 compilation. (For C programs, @command{gcc} can also do linking, but this
1125 capability is not used directly for Ada programs, so the @option{-c}
1126 switch must always be present.)
1127 @end ifclear
1128
1129 This compile command generates a file
1130 @file{hello.o}, which is the object
1131 file corresponding to your Ada program. It also generates
1132 an ``Ada Library Information'' file @file{hello.ali},
1133 which contains additional information used to check
1134 that an Ada program is consistent.
1135 To build an executable file,
1136 use @code{gnatbind} to bind the program
1137 and @command{gnatlink} to link it. The
1138 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1139 @file{ALI} file, but the default extension of @file{.ali} can
1140 be omitted. This means that in the most common case, the argument
1141 is simply the name of the main program:
1142
1143 @smallexample
1144 $ gnatbind hello
1145 $ gnatlink hello
1146 @end smallexample
1147
1148 @noindent
1149 A simpler method of carrying out these steps is to use
1150 @command{gnatmake},
1151 a master program that invokes all the required
1152 compilation, binding and linking tools in the correct order. In particular,
1153 @command{gnatmake} automatically recompiles any sources that have been
1154 modified since they were last compiled, or sources that depend
1155 on such modified sources, so that ``version skew'' is avoided.
1156 @cindex Version skew (avoided by @command{gnatmake})
1157
1158 @smallexample
1159 $ gnatmake hello.adb
1160 @end smallexample
1161
1162 @noindent
1163 The result is an executable program called @file{hello}, which can be
1164 run by entering:
1165
1166 @smallexample
1167 $ ^hello^RUN HELLO^
1168 @end smallexample
1169
1170 @noindent
1171 assuming that the current directory is on the search path
1172 for executable programs.
1173
1174 @noindent
1175 and, if all has gone well, you will see
1176
1177 @smallexample
1178 Hello WORLD!
1179 @end smallexample
1180
1181 @noindent
1182 appear in response to this command.
1183
1184 @c ****************************************
1185 @node Running a Program with Multiple Units
1186 @section Running a Program with Multiple Units
1187
1188 @noindent
1189 Consider a slightly more complicated example that has three files: a
1190 main program, and the spec and body of a package:
1191
1192 @smallexample @c ada
1193 @cartouche
1194 @group
1195 package Greetings is
1196    procedure Hello;
1197    procedure Goodbye;
1198 end Greetings;
1199
1200 with Ada.Text_IO; use Ada.Text_IO;
1201 package body Greetings is
1202    procedure Hello is
1203    begin
1204       Put_Line ("Hello WORLD!");
1205    end Hello;
1206
1207    procedure Goodbye is
1208    begin
1209       Put_Line ("Goodbye WORLD!");
1210    end Goodbye;
1211 end Greetings;
1212 @end group
1213
1214 @group
1215 with Greetings;
1216 procedure Gmain is
1217 begin
1218    Greetings.Hello;
1219    Greetings.Goodbye;
1220 end Gmain;
1221 @end group
1222 @end cartouche
1223 @end smallexample
1224
1225 @noindent
1226 Following the one-unit-per-file rule, place this program in the
1227 following three separate files:
1228
1229 @table @file
1230 @item greetings.ads
1231 spec of package @code{Greetings}
1232
1233 @item greetings.adb
1234 body of package @code{Greetings}
1235
1236 @item gmain.adb
1237 body of main program
1238 @end table
1239
1240 @noindent
1241 To build an executable version of
1242 this program, we could use four separate steps to compile, bind, and link
1243 the program, as follows:
1244
1245 @smallexample
1246 $ gcc -c gmain.adb
1247 $ gcc -c greetings.adb
1248 $ gnatbind gmain
1249 $ gnatlink gmain
1250 @end smallexample
1251
1252 @noindent
1253 Note that there is no required order of compilation when using GNAT.
1254 In particular it is perfectly fine to compile the main program first.
1255 Also, it is not necessary to compile package specs in the case where
1256 there is an accompanying body; you only need to compile the body. If you want
1257 to submit these files to the compiler for semantic checking and not code
1258 generation, then use the
1259 @option{-gnatc} switch:
1260
1261 @smallexample
1262 $ gcc -c greetings.ads -gnatc
1263 @end smallexample
1264
1265 @noindent
1266 Although the compilation can be done in separate steps as in the
1267 above example, in practice it is almost always more convenient
1268 to use the @command{gnatmake} tool. All you need to know in this case
1269 is the name of the main program's source file. The effect of the above four
1270 commands can be achieved with a single one:
1271
1272 @smallexample
1273 $ gnatmake gmain.adb
1274 @end smallexample
1275
1276 @noindent
1277 In the next section we discuss the advantages of using @command{gnatmake} in
1278 more detail.
1279
1280 @c *****************************
1281 @node Using the gnatmake Utility
1282 @section Using the @command{gnatmake} Utility
1283
1284 @noindent
1285 If you work on a program by compiling single components at a time using
1286 @command{gcc}, you typically keep track of the units you modify. In order to
1287 build a consistent system, you compile not only these units, but also any
1288 units that depend on the units you have modified.
1289 For example, in the preceding case,
1290 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1291 you edit @file{greetings.ads}, you must recompile both
1292 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1293 units that depend on @file{greetings.ads}.
1294
1295 @code{gnatbind} will warn you if you forget one of these compilation
1296 steps, so that it is impossible to generate an inconsistent program as a
1297 result of forgetting to do a compilation. Nevertheless it is tedious and
1298 error-prone to keep track of dependencies among units.
1299 One approach to handle the dependency-bookkeeping is to use a
1300 makefile. However, makefiles present maintenance problems of their own:
1301 if the dependencies change as you change the program, you must make
1302 sure that the makefile is kept up-to-date manually, which is also an
1303 error-prone process.
1304
1305 The @command{gnatmake} utility takes care of these details automatically.
1306 Invoke it using either one of the following forms:
1307
1308 @smallexample
1309 $ gnatmake gmain.adb
1310 $ gnatmake ^gmain^GMAIN^
1311 @end smallexample
1312
1313 @noindent
1314 The argument is the name of the file containing the main program;
1315 you may omit the extension. @command{gnatmake}
1316 examines the environment, automatically recompiles any files that need
1317 recompiling, and binds and links the resulting set of object files,
1318 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1319 In a large program, it
1320 can be extremely helpful to use @command{gnatmake}, because working out by hand
1321 what needs to be recompiled can be difficult.
1322
1323 Note that @command{gnatmake}
1324 takes into account all the Ada rules that
1325 establish dependencies among units. These include dependencies that result
1326 from inlining subprogram bodies, and from
1327 generic instantiation. Unlike some other
1328 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1329 found by the compiler on a previous compilation, which may possibly
1330 be wrong when sources change. @command{gnatmake} determines the exact set of
1331 dependencies from scratch each time it is run.
1332
1333 @ifset vms
1334 @node Editing with Emacs
1335 @section Editing with Emacs
1336 @cindex Emacs
1337
1338 @noindent
1339 Emacs is an extensible self-documenting text editor that is available in a
1340 separate VMSINSTAL kit.
1341
1342 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1343 click on the Emacs Help menu and run the Emacs Tutorial.
1344 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1345 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1346
1347 Documentation on Emacs and other tools is available in Emacs under the
1348 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1349 use the middle mouse button to select a topic (e.g. Emacs).
1350
1351 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1352 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1353 get to the Emacs manual.
1354 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1355 prompt.
1356
1357 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1358 which is sufficiently extensible to provide for a complete programming
1359 environment and shell for the sophisticated user.
1360 @end ifset
1361
1362 @ifclear vms
1363 @node Introduction to GPS
1364 @section Introduction to GPS
1365 @cindex GPS (GNAT Programming Studio)
1366 @cindex GNAT Programming Studio (GPS)
1367 @noindent
1368 Although the command line interface (@command{gnatmake}, etc.) alone
1369 is sufficient, a graphical Interactive Development
1370 Environment can make it easier for you to compose, navigate, and debug
1371 programs.  This section describes the main features of GPS
1372 (``GNAT Programming Studio''), the GNAT graphical IDE.
1373 You will see how to use GPS to build and debug an executable, and
1374 you will also learn some of the basics of the GNAT ``project'' facility.
1375
1376 GPS enables you to do much more than is presented here;
1377 e.g., you can produce a call graph, interface to a third-party
1378 Version Control System, and inspect the generated assembly language
1379 for a program.
1380 Indeed, GPS also supports languages other than Ada.
1381 Such additional information, and an explanation of all of the GPS menu
1382 items. may be found in the on-line help, which includes
1383 a user's guide and a tutorial (these are also accessible from the GNAT
1384 startup menu).
1385
1386 @menu
1387 * Building a New Program with GPS::
1388 * Simple Debugging with GPS::
1389 @end menu
1390
1391 @node Building a New Program with GPS
1392 @subsection Building a New Program with GPS
1393 @noindent
1394 GPS invokes the GNAT compilation tools using information
1395 contained in a @emph{project} (also known as a @emph{project file}):
1396 a collection of properties such
1397 as source directories, identities of main subprograms, tool switches, etc.,
1398 and their associated values.
1399 See @ref{GNAT Project Manager} for details.
1400 In order to run GPS, you will need to either create a new project
1401 or else open an existing one.
1402
1403 This section will explain how you can use GPS to create a project,
1404 to associate Ada source files with a project, and to build and run
1405 programs.
1406
1407 @enumerate
1408 @item @emph{Creating a project}
1409
1410 Invoke GPS, either from the command line or the platform's IDE.
1411 After it starts, GPS will display a ``Welcome'' screen with three
1412 radio buttons:
1413
1414 @itemize @bullet
1415 @item
1416 @code{Start with default project in directory}
1417
1418 @item
1419 @code{Create new project with wizard}
1420
1421 @item
1422 @code{Open existing project}
1423 @end itemize
1424
1425 @noindent
1426 Select @code{Create new project with wizard} and press @code{OK}.
1427 A new window will appear.  In the text box labeled with
1428 @code{Enter the name of the project to create}, type @file{sample}
1429 as the project name.
1430 In the next box, browse to choose the directory in which you
1431 would like to create the project file.
1432 After selecting an appropriate directory, press @code{Forward}.
1433
1434 A window will appear with the title
1435 @code{Version Control System Configuration}.
1436 Simply press @code{Forward}.
1437
1438 A window will appear with the title
1439 @code{Please select the source directories for this project}.
1440 The directory that you specified for the project file will be selected
1441 by default as the one to use for sources; simply press @code{Forward}.
1442
1443 A window will appear with the title
1444 @code{Please select the build directory for this project}.
1445 The directory that you specified for the project file will be selected
1446 by default for object files and executables;
1447 simply press @code{Forward}.
1448
1449 A window will appear with the title
1450 @code{Please select the main units for this project}.
1451 You will supply this information later, after creating the source file.
1452 Simply press @code{Forward} for now.
1453
1454 A window will appear with the title
1455 @code{Please select the switches to build the project}.
1456 Press @code{Apply}.  This will create a project file named
1457 @file{sample.prj} in the directory that you had specified.
1458
1459 @item @emph{Creating and saving the source file}
1460
1461 After you create the new project, a GPS window will appear, which is
1462 partitioned into two main sections:
1463
1464 @itemize @bullet
1465 @item
1466 A @emph{Workspace area}, initially greyed out, which you will use for
1467 creating and editing source files
1468
1469 @item
1470 Directly below, a @emph{Messages area}, which initially displays a
1471 ``Welcome'' message.
1472 (If the Messages area is not visible, drag its border upward to expand it.)
1473 @end itemize
1474
1475 @noindent
1476 Select @code{File} on the menu bar, and then the @code{New} command.
1477 The Workspace area will become white, and you can now
1478 enter the source program explicitly.
1479 Type the following text
1480
1481 @smallexample @c ada
1482 @group
1483 with Ada.Text_IO; use Ada.Text_IO;
1484 procedure Hello is
1485 begin
1486   Put_Line("Hello from GPS!");
1487 end Hello;
1488 @end group
1489 @end smallexample
1490
1491 @noindent
1492 Select @code{File}, then @code{Save As}, and enter the source file name
1493 @file{hello.adb}.
1494 The file will be saved in the same directory you specified as the
1495 location of the default project file.
1496
1497 @item @emph{Updating the project file}
1498
1499 You need to add the new source file to the project.
1500 To do this, select
1501 the @code{Project} menu and then @code{Edit project properties}.
1502 Click the @code{Main files} tab on the left, and then the
1503 @code{Add} button.
1504 Choose @file{hello.adb} from the list, and press @code{Open}.
1505 The project settings window will reflect this action.
1506 Click @code{OK}.
1507
1508 @item @emph{Building and running the program}
1509
1510 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1511 and select @file{hello.adb}.
1512 The Messages window will display the resulting invocations of @command{gcc},
1513 @command{gnatbind}, and @command{gnatlink}
1514 (reflecting the default switch settings from the
1515 project file that you created) and then a ``successful compilation/build''
1516 message.
1517
1518 To run the program, choose the @code{Build} menu, then @code{Run}, and
1519 select @command{hello}.
1520 An @emph{Arguments Selection} window will appear.
1521 There are no command line arguments, so just click @code{OK}.
1522
1523 The Messages window will now display the program's output (the string
1524 @code{Hello from GPS}), and at the bottom of the GPS window a status
1525 update is displayed (@code{Run: hello}).
1526 Close the GPS window (or select @code{File}, then @code{Exit}) to
1527 terminate this GPS session.
1528 @end enumerate
1529
1530 @node Simple Debugging with GPS
1531 @subsection Simple Debugging with GPS
1532 @noindent
1533 This section illustrates basic debugging techniques (setting breakpoints,
1534 examining/modifying variables, single stepping).
1535
1536 @enumerate
1537 @item @emph{Opening a project}
1538
1539 Start GPS and select @code{Open existing project}; browse to
1540 specify the project file @file{sample.prj} that you had created in the
1541 earlier example.
1542
1543 @item @emph{Creating a source file}
1544
1545 Select @code{File}, then @code{New}, and type in the following program:
1546
1547 @smallexample @c ada
1548 @group
1549 with Ada.Text_IO; use Ada.Text_IO;
1550 procedure Example is
1551    Line : String (1..80);
1552    N    : Natural;
1553 begin
1554    Put_Line("Type a line of text at each prompt; an empty line to exit");
1555    loop
1556       Put(": ");
1557       Get_Line (Line, N);
1558       Put_Line (Line (1..N) );
1559       exit when N=0;
1560    end loop;
1561 end Example;
1562 @end group
1563 @end smallexample
1564
1565 @noindent
1566 Select @code{File}, then @code{Save as}, and enter the file name
1567 @file{example.adb}.
1568
1569 @item @emph{Updating the project file}
1570
1571 Add @code{Example} as a new main unit for the project:
1572 @enumerate a
1573 @item
1574 Select @code{Project}, then @code{Edit Project Properties}.
1575
1576 @item
1577 Select the @code{Main files} tab, click @code{Add}, then
1578 select the file @file{example.adb} from the list, and
1579 click @code{Open}.
1580 You will see the file name appear in the list of main units
1581
1582 @item
1583 Click @code{OK}
1584 @end enumerate
1585
1586 @item @emph{Building/running the executable}
1587
1588 To build the executable
1589 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1590
1591 Run the program to see its effect (in the Messages area).
1592 Each line that you enter is displayed; an empty line will
1593 cause the loop to exit and the program to terminate.
1594
1595 @item @emph{Debugging the program}
1596
1597 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1598 which are required for debugging, are on by default when you create
1599 a new project.
1600 Thus unless you intentionally remove these settings, you will be able
1601 to debug any program that you develop using GPS.
1602
1603 @enumerate a
1604 @item @emph{Initializing}
1605
1606 Select @code{Debug}, then @code{Initialize}, then @file{example}
1607
1608 @item @emph{Setting a breakpoint}
1609
1610 After performing the initialization step, you will observe a small
1611 icon to the right of each line number.
1612 This serves as a toggle for breakpoints; clicking the icon will
1613 set a breakpoint at the corresponding line (the icon will change to
1614 a red circle with an ``x''), and clicking it again
1615 will remove the breakpoint / reset the icon.
1616
1617 For purposes of this example, set a breakpoint at line 10 (the
1618 statement @code{Put_Line@ (Line@ (1..N));}
1619
1620 @item @emph{Starting program execution}
1621
1622 Select @code{Debug}, then @code{Run}.  When the
1623 @code{Program Arguments} window appears, click @code{OK}.
1624 A console window will appear; enter some line of text,
1625 e.g. @code{abcde}, at the prompt.
1626 The program will pause execution when it gets to the
1627 breakpoint, and the corresponding line is highlighted.
1628
1629 @item @emph{Examining a variable}
1630
1631 Move the mouse over one of the occurrences of the variable @code{N}.
1632 You will see the value (5) displayed, in ``tool tip'' fashion.
1633 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1634 You will see information about @code{N} appear in the @code{Debugger Data}
1635 pane, showing the value as 5.
1636
1637 @item @emph{Assigning a new value to a variable}
1638
1639 Right click on the @code{N} in the @code{Debugger Data} pane, and
1640 select @code{Set value of N}.
1641 When the input window appears, enter the value @code{4} and click
1642 @code{OK}.
1643 This value does not automatically appear in the @code{Debugger Data}
1644 pane; to see it, right click again on the @code{N} in the
1645 @code{Debugger Data} pane and select @code{Update value}.
1646 The new value, 4, will appear in red.
1647
1648 @item @emph{Single stepping}
1649
1650 Select @code{Debug}, then @code{Next}.
1651 This will cause the next statement to be executed, in this case the
1652 call of @code{Put_Line} with the string slice.
1653 Notice in the console window that the displayed string is simply
1654 @code{abcd} and not @code{abcde} which you had entered.
1655 This is because the upper bound of the slice is now 4 rather than 5.
1656
1657 @item @emph{Removing a breakpoint}
1658
1659 Toggle the breakpoint icon at line 10.
1660
1661 @item @emph{Resuming execution from a breakpoint}
1662
1663 Select @code{Debug}, then @code{Continue}.
1664 The program will reach the next iteration of the loop, and
1665 wait for input after displaying the prompt.
1666 This time, just hit the @kbd{Enter} key.
1667 The value of @code{N} will be 0, and the program will terminate.
1668 The console window will disappear.
1669 @end enumerate
1670 @end enumerate
1671 @end ifclear
1672
1673 @node The GNAT Compilation Model
1674 @chapter The GNAT Compilation Model
1675 @cindex GNAT compilation model
1676 @cindex Compilation model
1677
1678 @menu
1679 * Source Representation::
1680 * Foreign Language Representation::
1681 * File Naming Rules::
1682 * Using Other File Names::
1683 * Alternative File Naming Schemes::
1684 * Generating Object Files::
1685 * Source Dependencies::
1686 * The Ada Library Information Files::
1687 * Binding an Ada Program::
1688 * Mixed Language Programming::
1689 @ifclear vms
1690 * Building Mixed Ada & C++ Programs::
1691 * Comparison between GNAT and C/C++ Compilation Models::
1692 @end ifclear
1693 * Comparison between GNAT and Conventional Ada Library Models::
1694 @ifset vms
1695 * Placement of temporary files::
1696 @end ifset
1697 @end menu
1698
1699 @noindent
1700 This chapter describes the compilation model used by GNAT. Although
1701 similar to that used by other languages, such as C and C++, this model
1702 is substantially different from the traditional Ada compilation models,
1703 which are based on a library. The model is initially described without
1704 reference to the library-based model. If you have not previously used an
1705 Ada compiler, you need only read the first part of this chapter. The
1706 last section describes and discusses the differences between the GNAT
1707 model and the traditional Ada compiler models. If you have used other
1708 Ada compilers, this section will help you to understand those
1709 differences, and the advantages of the GNAT model.
1710
1711 @node Source Representation
1712 @section Source Representation
1713 @cindex Latin-1
1714
1715 @noindent
1716 Ada source programs are represented in standard text files, using
1717 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1718 7-bit ASCII set, plus additional characters used for
1719 representing foreign languages (@pxref{Foreign Language Representation}
1720 for support of non-USA character sets). The format effector characters
1721 are represented using their standard ASCII encodings, as follows:
1722
1723 @table @code
1724 @item VT
1725 @findex VT
1726 Vertical tab, @code{16#0B#}
1727
1728 @item HT
1729 @findex HT
1730 Horizontal tab, @code{16#09#}
1731
1732 @item CR
1733 @findex CR
1734 Carriage return, @code{16#0D#}
1735
1736 @item LF
1737 @findex LF
1738 Line feed, @code{16#0A#}
1739
1740 @item FF
1741 @findex FF
1742 Form feed, @code{16#0C#}
1743 @end table
1744
1745 @noindent
1746 Source files are in standard text file format. In addition, GNAT will
1747 recognize a wide variety of stream formats, in which the end of
1748 physical lines is marked by any of the following sequences:
1749 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1750 in accommodating files that are imported from other operating systems.
1751
1752 @cindex End of source file
1753 @cindex Source file, end
1754 @findex SUB
1755 The end of a source file is normally represented by the physical end of
1756 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1757 recognized as signalling the end of the source file. Again, this is
1758 provided for compatibility with other operating systems where this
1759 code is used to represent the end of file.
1760
1761 Each file contains a single Ada compilation unit, including any pragmas
1762 associated with the unit. For example, this means you must place a
1763 package declaration (a package @dfn{spec}) and the corresponding body in
1764 separate files. An Ada @dfn{compilation} (which is a sequence of
1765 compilation units) is represented using a sequence of files. Similarly,
1766 you will place each subunit or child unit in a separate file.
1767
1768 @node Foreign Language Representation
1769 @section Foreign Language Representation
1770
1771 @noindent
1772 GNAT supports the standard character sets defined in Ada as well as
1773 several other non-standard character sets for use in localized versions
1774 of the compiler (@pxref{Character Set Control}).
1775 @menu
1776 * Latin-1::
1777 * Other 8-Bit Codes::
1778 * Wide Character Encodings::
1779 @end menu
1780
1781 @node Latin-1
1782 @subsection Latin-1
1783 @cindex Latin-1
1784
1785 @noindent
1786 The basic character set is Latin-1. This character set is defined by ISO
1787 standard 8859, part 1. The lower half (character codes @code{16#00#}
1788 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1789 is used to represent additional characters. These include extended letters
1790 used by European languages, such as French accents, the vowels with umlauts
1791 used in German, and the extra letter A-ring used in Swedish.
1792
1793 @findex Ada.Characters.Latin_1
1794 For a complete list of Latin-1 codes and their encodings, see the source
1795 file of library unit @code{Ada.Characters.Latin_1} in file
1796 @file{a-chlat1.ads}.
1797 You may use any of these extended characters freely in character or
1798 string literals. In addition, the extended characters that represent
1799 letters can be used in identifiers.
1800
1801 @node Other 8-Bit Codes
1802 @subsection Other 8-Bit Codes
1803
1804 @noindent
1805 GNAT also supports several other 8-bit coding schemes:
1806
1807 @table @asis
1808 @item ISO 8859-2 (Latin-2)
1809 @cindex Latin-2
1810 @cindex ISO 8859-2
1811 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1812 equivalence.
1813
1814 @item ISO 8859-3 (Latin-3)
1815 @cindex Latin-3
1816 @cindex ISO 8859-3
1817 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1818 equivalence.
1819
1820 @item ISO 8859-4 (Latin-4)
1821 @cindex Latin-4
1822 @cindex ISO 8859-4
1823 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1824 equivalence.
1825
1826 @item ISO 8859-5 (Cyrillic)
1827 @cindex ISO 8859-5
1828 @cindex Cyrillic
1829 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1830 lowercase equivalence.
1831
1832 @item ISO 8859-15 (Latin-9)
1833 @cindex ISO 8859-15
1834 @cindex Latin-9
1835 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1836 lowercase equivalence
1837
1838 @item IBM PC (code page 437)
1839 @cindex code page 437
1840 This code page is the normal default for PCs in the U.S. It corresponds
1841 to the original IBM PC character set. This set has some, but not all, of
1842 the extended Latin-1 letters, but these letters do not have the same
1843 encoding as Latin-1. In this mode, these letters are allowed in
1844 identifiers with uppercase and lowercase equivalence.
1845
1846 @item IBM PC (code page 850)
1847 @cindex code page 850
1848 This code page is a modification of 437 extended to include all the
1849 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1850 mode, all these letters are allowed in identifiers with uppercase and
1851 lowercase equivalence.
1852
1853 @item Full Upper 8-bit
1854 Any character in the range 80-FF allowed in identifiers, and all are
1855 considered distinct. In other words, there are no uppercase and lowercase
1856 equivalences in this range. This is useful in conjunction with
1857 certain encoding schemes used for some foreign character sets (e.g.
1858 the typical method of representing Chinese characters on the PC).
1859
1860 @item No Upper-Half
1861 No upper-half characters in the range 80-FF are allowed in identifiers.
1862 This gives Ada 83 compatibility for identifier names.
1863 @end table
1864
1865 @noindent
1866 For precise data on the encodings permitted, and the uppercase and lowercase
1867 equivalences that are recognized, see the file @file{csets.adb} in
1868 the GNAT compiler sources. You will need to obtain a full source release
1869 of GNAT to obtain this file.
1870
1871 @node Wide Character Encodings
1872 @subsection Wide Character Encodings
1873
1874 @noindent
1875 GNAT allows wide character codes to appear in character and string
1876 literals, and also optionally in identifiers, by means of the following
1877 possible encoding schemes:
1878
1879 @table @asis
1880
1881 @item Hex Coding
1882 In this encoding, a wide character is represented by the following five
1883 character sequence:
1884
1885 @smallexample
1886 ESC a b c d
1887 @end smallexample
1888
1889 @noindent
1890 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1891 characters (using uppercase letters) of the wide character code. For
1892 example, ESC A345 is used to represent the wide character with code
1893 @code{16#A345#}.
1894 This scheme is compatible with use of the full Wide_Character set.
1895
1896 @item Upper-Half Coding
1897 @cindex Upper-Half Coding
1898 The wide character with encoding @code{16#abcd#} where the upper bit is on
1899 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1900 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1901 character, but is not required to be in the upper half. This method can
1902 be also used for shift-JIS or EUC, where the internal coding matches the
1903 external coding.
1904
1905 @item Shift JIS Coding
1906 @cindex Shift JIS Coding
1907 A wide character is represented by a two-character sequence,
1908 @code{16#ab#} and
1909 @code{16#cd#}, with the restrictions described for upper-half encoding as
1910 described above. The internal character code is the corresponding JIS
1911 character according to the standard algorithm for Shift-JIS
1912 conversion. Only characters defined in the JIS code set table can be
1913 used with this encoding method.
1914
1915 @item EUC Coding
1916 @cindex EUC Coding
1917 A wide character is represented by a two-character sequence
1918 @code{16#ab#} and
1919 @code{16#cd#}, with both characters being in the upper half. The internal
1920 character code is the corresponding JIS character according to the EUC
1921 encoding algorithm. Only characters defined in the JIS code set table
1922 can be used with this encoding method.
1923
1924 @item UTF-8 Coding
1925 A wide character is represented using
1926 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1927 10646-1/Am.2. Depending on the character value, the representation
1928 is a one, two, or three byte sequence:
1929 @smallexample
1930 @iftex
1931 @leftskip=.7cm
1932 @end iftex
1933 16#0000#-16#007f#: 2#0xxxxxxx#
1934 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1935 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1936
1937 @end smallexample
1938
1939 @noindent
1940 where the xxx bits correspond to the left-padded bits of the
1941 16-bit character value. Note that all lower half ASCII characters
1942 are represented as ASCII bytes and all upper half characters and
1943 other wide characters are represented as sequences of upper-half
1944 (The full UTF-8 scheme allows for encoding 31-bit characters as
1945 6-byte sequences, but in this implementation, all UTF-8 sequences
1946 of four or more bytes length will be treated as illegal).
1947 @item Brackets Coding
1948 In this encoding, a wide character is represented by the following eight
1949 character sequence:
1950
1951 @smallexample
1952 [ " a b c d " ]
1953 @end smallexample
1954
1955 @noindent
1956 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1957 characters (using uppercase letters) of the wide character code. For
1958 example, [``A345''] is used to represent the wide character with code
1959 @code{16#A345#}. It is also possible (though not required) to use the
1960 Brackets coding for upper half characters. For example, the code
1961 @code{16#A3#} can be represented as @code{[``A3'']}.
1962
1963 This scheme is compatible with use of the full Wide_Character set,
1964 and is also the method used for wide character encoding in the standard
1965 ACVC (Ada Compiler Validation Capability) test suite distributions.
1966
1967 @end table
1968
1969 @noindent
1970 Note: Some of these coding schemes do not permit the full use of the
1971 Ada character set. For example, neither Shift JIS, nor EUC allow the
1972 use of the upper half of the Latin-1 set.
1973
1974 @node File Naming Rules
1975 @section File Naming Rules
1976
1977 @noindent
1978 The default file name is determined by the name of the unit that the
1979 file contains. The name is formed by taking the full expanded name of
1980 the unit and replacing the separating dots with hyphens and using
1981 ^lowercase^uppercase^ for all letters.
1982
1983 An exception arises if the file name generated by the above rules starts
1984 with one of the characters
1985 @ifset vms
1986 A,G,I, or S,
1987 @end ifset
1988 @ifclear vms
1989 a,g,i, or s,
1990 @end ifclear
1991 and the second character is a
1992 minus. In this case, the character ^tilde^dollar sign^ is used in place
1993 of the minus. The reason for this special rule is to avoid clashes with
1994 the standard names for child units of the packages System, Ada,
1995 Interfaces, and GNAT, which use the prefixes
1996 @ifset vms
1997 S- A- I- and G-
1998 @end ifset
1999 @ifclear vms
2000 s- a- i- and g-
2001 @end ifclear
2002 respectively.
2003
2004 The file extension is @file{.ads} for a spec and
2005 @file{.adb} for a body. The following list shows some
2006 examples of these rules.
2007
2008 @table @file
2009 @item main.ads
2010 Main (spec)
2011 @item main.adb
2012 Main (body)
2013 @item arith_functions.ads
2014 Arith_Functions (package spec)
2015 @item arith_functions.adb
2016 Arith_Functions (package body)
2017 @item func-spec.ads
2018 Func.Spec (child package spec)
2019 @item func-spec.adb
2020 Func.Spec (child package body)
2021 @item main-sub.adb
2022 Sub (subunit of Main)
2023 @item ^a~bad.adb^A$BAD.ADB^
2024 A.Bad (child package body)
2025 @end table
2026
2027 @noindent
2028 Following these rules can result in excessively long
2029 file names if corresponding
2030 unit names are long (for example, if child units or subunits are
2031 heavily nested). An option is available to shorten such long file names
2032 (called file name ``krunching''). This may be particularly useful when
2033 programs being developed with GNAT are to be used on operating systems
2034 with limited file name lengths. @xref{Using gnatkr}.
2035
2036 Of course, no file shortening algorithm can guarantee uniqueness over
2037 all possible unit names; if file name krunching is used, it is your
2038 responsibility to ensure no name clashes occur. Alternatively you
2039 can specify the exact file names that you want used, as described
2040 in the next section. Finally, if your Ada programs are migrating from a
2041 compiler with a different naming convention, you can use the gnatchop
2042 utility to produce source files that follow the GNAT naming conventions.
2043 (For details @pxref{Renaming Files Using gnatchop}.)
2044
2045 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2046 systems, case is not significant. So for example on @code{Windows XP}
2047 if the canonical name is @code{main-sub.adb}, you can use the file name
2048 @code{Main-Sub.adb} instead. However, case is significant for other
2049 operating systems, so for example, if you want to use other than
2050 canonically cased file names on a Unix system, you need to follow
2051 the procedures described in the next section.
2052
2053 @node Using Other File Names
2054 @section Using Other File Names
2055 @cindex File names
2056
2057 @noindent
2058 In the previous section, we have described the default rules used by
2059 GNAT to determine the file name in which a given unit resides. It is
2060 often convenient to follow these default rules, and if you follow them,
2061 the compiler knows without being explicitly told where to find all
2062 the files it needs.
2063
2064 However, in some cases, particularly when a program is imported from
2065 another Ada compiler environment, it may be more convenient for the
2066 programmer to specify which file names contain which units. GNAT allows
2067 arbitrary file names to be used by means of the Source_File_Name pragma.
2068 The form of this pragma is as shown in the following examples:
2069 @cindex Source_File_Name pragma
2070
2071 @smallexample @c ada
2072 @cartouche
2073 pragma Source_File_Name (My_Utilities.Stacks,
2074   Spec_File_Name => "myutilst_a.ada");
2075 pragma Source_File_name (My_Utilities.Stacks,
2076   Body_File_Name => "myutilst.ada");
2077 @end cartouche
2078 @end smallexample
2079
2080 @noindent
2081 As shown in this example, the first argument for the pragma is the unit
2082 name (in this example a child unit). The second argument has the form
2083 of a named association. The identifier
2084 indicates whether the file name is for a spec or a body;
2085 the file name itself is given by a string literal.
2086
2087 The source file name pragma is a configuration pragma, which means that
2088 normally it will be placed in the @file{gnat.adc}
2089 file used to hold configuration
2090 pragmas that apply to a complete compilation environment.
2091 For more details on how the @file{gnat.adc} file is created and used
2092 see @ref{Handling of Configuration Pragmas}.
2093 @cindex @file{gnat.adc}
2094
2095 @ifclear vms
2096 GNAT allows completely arbitrary file names to be specified using the
2097 source file name pragma. However, if the file name specified has an
2098 extension other than @file{.ads} or @file{.adb} it is necessary to use
2099 a special syntax when compiling the file. The name in this case must be
2100 preceded by the special sequence @code{-x} followed by a space and the name
2101 of the language, here @code{ada}, as in:
2102
2103 @smallexample
2104 $ gcc -c -x ada peculiar_file_name.sim
2105 @end smallexample
2106 @end ifclear
2107
2108 @noindent
2109 @command{gnatmake} handles non-standard file names in the usual manner (the
2110 non-standard file name for the main program is simply used as the
2111 argument to gnatmake). Note that if the extension is also non-standard,
2112 then it must be included in the gnatmake command, it may not be omitted.
2113
2114 @node Alternative File Naming Schemes
2115 @section Alternative File Naming Schemes
2116 @cindex File naming schemes, alternative
2117 @cindex File names
2118
2119 In the previous section, we described the use of the @code{Source_File_Name}
2120 pragma to allow arbitrary names to be assigned to individual source files.
2121 However, this approach requires one pragma for each file, and especially in
2122 large systems can result in very long @file{gnat.adc} files, and also create
2123 a maintenance problem.
2124
2125 GNAT also provides a facility for specifying systematic file naming schemes
2126 other than the standard default naming scheme previously described. An
2127 alternative scheme for naming is specified by the use of
2128 @code{Source_File_Name} pragmas having the following format:
2129 @cindex Source_File_Name pragma
2130
2131 @smallexample @c ada
2132 pragma Source_File_Name (
2133    Spec_File_Name  => FILE_NAME_PATTERN
2134  [,Casing          => CASING_SPEC]
2135  [,Dot_Replacement => STRING_LITERAL]);
2136
2137 pragma Source_File_Name (
2138    Body_File_Name  => FILE_NAME_PATTERN
2139  [,Casing          => CASING_SPEC]
2140  [,Dot_Replacement => STRING_LITERAL]);
2141
2142 pragma Source_File_Name (
2143    Subunit_File_Name  => FILE_NAME_PATTERN
2144  [,Casing             => CASING_SPEC]
2145  [,Dot_Replacement    => STRING_LITERAL]);
2146
2147 FILE_NAME_PATTERN ::= STRING_LITERAL
2148 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2149 @end smallexample
2150
2151 @noindent
2152 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2153 It contains a single asterisk character, and the unit name is substituted
2154 systematically for this asterisk. The optional parameter
2155 @code{Casing} indicates
2156 whether the unit name is to be all upper-case letters, all lower-case letters,
2157 or mixed-case. If no
2158 @code{Casing} parameter is used, then the default is all
2159 ^lower-case^upper-case^.
2160
2161 The optional @code{Dot_Replacement} string is used to replace any periods
2162 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2163 argument is used then separating dots appear unchanged in the resulting
2164 file name.
2165 Although the above syntax indicates that the
2166 @code{Casing} argument must appear
2167 before the @code{Dot_Replacement} argument, but it
2168 is also permissible to write these arguments in the opposite order.
2169
2170 As indicated, it is possible to specify different naming schemes for
2171 bodies, specs, and subunits. Quite often the rule for subunits is the
2172 same as the rule for bodies, in which case, there is no need to give
2173 a separate @code{Subunit_File_Name} rule, and in this case the
2174 @code{Body_File_name} rule is used for subunits as well.
2175
2176 The separate rule for subunits can also be used to implement the rather
2177 unusual case of a compilation environment (e.g. a single directory) which
2178 contains a subunit and a child unit with the same unit name. Although
2179 both units cannot appear in the same partition, the Ada Reference Manual
2180 allows (but does not require) the possibility of the two units coexisting
2181 in the same environment.
2182
2183 The file name translation works in the following steps:
2184
2185 @itemize @bullet
2186
2187 @item
2188 If there is a specific @code{Source_File_Name} pragma for the given unit,
2189 then this is always used, and any general pattern rules are ignored.
2190
2191 @item
2192 If there is a pattern type @code{Source_File_Name} pragma that applies to
2193 the unit, then the resulting file name will be used if the file exists. If
2194 more than one pattern matches, the latest one will be tried first, and the
2195 first attempt resulting in a reference to a file that exists will be used.
2196
2197 @item
2198 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2199 for which the corresponding file exists, then the standard GNAT default
2200 naming rules are used.
2201
2202 @end itemize
2203
2204 @noindent
2205 As an example of the use of this mechanism, consider a commonly used scheme
2206 in which file names are all lower case, with separating periods copied
2207 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2208 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2209 two pragmas appear:
2210
2211 @smallexample @c ada
2212 pragma Source_File_Name
2213   (Spec_File_Name => "*.1.ada");
2214 pragma Source_File_Name
2215   (Body_File_Name => "*.2.ada");
2216 @end smallexample
2217
2218 @noindent
2219 The default GNAT scheme is actually implemented by providing the following
2220 default pragmas internally:
2221
2222 @smallexample @c ada
2223 pragma Source_File_Name
2224   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2225 pragma Source_File_Name
2226   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2227 @end smallexample
2228
2229 @noindent
2230 Our final example implements a scheme typically used with one of the
2231 Ada 83 compilers, where the separator character for subunits was ``__''
2232 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2233 by adding @file{.ADA}, and subunits by
2234 adding @file{.SEP}. All file names were
2235 upper case. Child units were not present of course since this was an
2236 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2237 the same double underscore separator for child units.
2238
2239 @smallexample @c ada
2240 pragma Source_File_Name
2241   (Spec_File_Name => "*_.ADA",
2242    Dot_Replacement => "__",
2243    Casing = Uppercase);
2244 pragma Source_File_Name
2245   (Body_File_Name => "*.ADA",
2246    Dot_Replacement => "__",
2247    Casing = Uppercase);
2248 pragma Source_File_Name
2249   (Subunit_File_Name => "*.SEP",
2250    Dot_Replacement => "__",
2251    Casing = Uppercase);
2252 @end smallexample
2253
2254 @node Generating Object Files
2255 @section Generating Object Files
2256
2257 @noindent
2258 An Ada program consists of a set of source files, and the first step in
2259 compiling the program is to generate the corresponding object files.
2260 These are generated by compiling a subset of these source files.
2261 The files you need to compile are the following:
2262
2263 @itemize @bullet
2264 @item
2265 If a package spec has no body, compile the package spec to produce the
2266 object file for the package.
2267
2268 @item
2269 If a package has both a spec and a body, compile the body to produce the
2270 object file for the package. The source file for the package spec need
2271 not be compiled in this case because there is only one object file, which
2272 contains the code for both the spec and body of the package.
2273
2274 @item
2275 For a subprogram, compile the subprogram body to produce the object file
2276 for the subprogram. The spec, if one is present, is as usual in a
2277 separate file, and need not be compiled.
2278
2279 @item
2280 @cindex Subunits
2281 In the case of subunits, only compile the parent unit. A single object
2282 file is generated for the entire subunit tree, which includes all the
2283 subunits.
2284
2285 @item
2286 Compile child units independently of their parent units
2287 (though, of course, the spec of all the ancestor unit must be present in order
2288 to compile a child unit).
2289
2290 @item
2291 @cindex Generics
2292 Compile generic units in the same manner as any other units. The object
2293 files in this case are small dummy files that contain at most the
2294 flag used for elaboration checking. This is because GNAT always handles generic
2295 instantiation by means of macro expansion. However, it is still necessary to
2296 compile generic units, for dependency checking and elaboration purposes.
2297 @end itemize
2298
2299 @noindent
2300 The preceding rules describe the set of files that must be compiled to
2301 generate the object files for a program. Each object file has the same
2302 name as the corresponding source file, except that the extension is
2303 @file{.o} as usual.
2304
2305 You may wish to compile other files for the purpose of checking their
2306 syntactic and semantic correctness. For example, in the case where a
2307 package has a separate spec and body, you would not normally compile the
2308 spec. However, it is convenient in practice to compile the spec to make
2309 sure it is error-free before compiling clients of this spec, because such
2310 compilations will fail if there is an error in the spec.
2311
2312 GNAT provides an option for compiling such files purely for the
2313 purposes of checking correctness; such compilations are not required as
2314 part of the process of building a program. To compile a file in this
2315 checking mode, use the @option{-gnatc} switch.
2316
2317 @node Source Dependencies
2318 @section Source Dependencies
2319
2320 @noindent
2321 A given object file clearly depends on the source file which is compiled
2322 to produce it. Here we are using @dfn{depends} in the sense of a typical
2323 @code{make} utility; in other words, an object file depends on a source
2324 file if changes to the source file require the object file to be
2325 recompiled.
2326 In addition to this basic dependency, a given object may depend on
2327 additional source files as follows:
2328
2329 @itemize @bullet
2330 @item
2331 If a file being compiled @code{with}'s a unit @var{X}, the object file
2332 depends on the file containing the spec of unit @var{X}. This includes
2333 files that are @code{with}'ed implicitly either because they are parents
2334 of @code{with}'ed child units or they are run-time units required by the
2335 language constructs used in a particular unit.
2336
2337 @item
2338 If a file being compiled instantiates a library level generic unit, the
2339 object file depends on both the spec and body files for this generic
2340 unit.
2341
2342 @item
2343 If a file being compiled instantiates a generic unit defined within a
2344 package, the object file depends on the body file for the package as
2345 well as the spec file.
2346
2347 @item
2348 @findex Inline
2349 @cindex @option{-gnatn} switch
2350 If a file being compiled contains a call to a subprogram for which
2351 pragma @code{Inline} applies and inlining is activated with the
2352 @option{-gnatn} switch, the object file depends on the file containing the
2353 body of this subprogram as well as on the file containing the spec. Note
2354 that for inlining to actually occur as a result of the use of this switch,
2355 it is necessary to compile in optimizing mode.
2356
2357 @cindex @option{-gnatN} switch
2358 The use of @option{-gnatN} activates a more extensive inlining optimization
2359 that is performed by the front end of the compiler. This inlining does
2360 not require that the code generation be optimized. Like @option{-gnatn},
2361 the use of this switch generates additional dependencies.
2362 Note that
2363 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2364 to specify both options.
2365
2366 @item
2367 If an object file @file{O} depends on the proper body of a subunit through
2368 inlining or instantiation, it depends on the parent unit of the subunit.
2369 This means that any modification of the parent unit or one of its subunits
2370 affects the compilation of @file{O}.
2371
2372 @item
2373 The object file for a parent unit depends on all its subunit body files.
2374
2375 @item
2376 The previous two rules meant that for purposes of computing dependencies and
2377 recompilation, a body and all its subunits are treated as an indivisible whole.
2378
2379 @noindent
2380 These rules are applied transitively: if unit @code{A} @code{with}'s
2381 unit @code{B}, whose elaboration calls an inlined procedure in package
2382 @code{C}, the object file for unit @code{A} will depend on the body of
2383 @code{C}, in file @file{c.adb}.
2384
2385 The set of dependent files described by these rules includes all the
2386 files on which the unit is semantically dependent, as dictated by the
2387 Ada language standard. However, it is a superset of what the
2388 standard describes, because it includes generic, inline, and subunit
2389 dependencies.
2390
2391 An object file must be recreated by recompiling the corresponding source
2392 file if any of the source files on which it depends are modified. For
2393 example, if the @code{make} utility is used to control compilation,
2394 the rule for an Ada object file must mention all the source files on
2395 which the object file depends, according to the above definition.
2396 The determination of the necessary
2397 recompilations is done automatically when one uses @command{gnatmake}.
2398 @end itemize
2399
2400 @node The Ada Library Information Files
2401 @section The Ada Library Information Files
2402 @cindex Ada Library Information files
2403 @cindex @file{ALI} files
2404
2405 @noindent
2406 Each compilation actually generates two output files. The first of these
2407 is the normal object file that has a @file{.o} extension. The second is a
2408 text file containing full dependency information. It has the same
2409 name as the source file, but an @file{.ali} extension.
2410 This file is known as the Ada Library Information (@file{ALI}) file.
2411 The following information is contained in the @file{ALI} file.
2412
2413 @itemize @bullet
2414 @item
2415 Version information (indicates which version of GNAT was used to compile
2416 the unit(s) in question)
2417
2418 @item
2419 Main program information (including priority and time slice settings,
2420 as well as the wide character encoding used during compilation).
2421
2422 @item
2423 List of arguments used in the @command{gcc} command for the compilation
2424
2425 @item
2426 Attributes of the unit, including configuration pragmas used, an indication
2427 of whether the compilation was successful, exception model used etc.
2428
2429 @item
2430 A list of relevant restrictions applying to the unit (used for consistency)
2431 checking.
2432
2433 @item
2434 Categorization information (e.g. use of pragma @code{Pure}).
2435
2436 @item
2437 Information on all @code{with}'ed units, including presence of
2438 @code{Elaborate} or @code{Elaborate_All} pragmas.
2439
2440 @item
2441 Information from any @code{Linker_Options} pragmas used in the unit
2442
2443 @item
2444 Information on the use of @code{Body_Version} or @code{Version}
2445 attributes in the unit.
2446
2447 @item
2448 Dependency information. This is a list of files, together with
2449 time stamp and checksum information. These are files on which
2450 the unit depends in the sense that recompilation is required
2451 if any of these units are modified.
2452
2453 @item
2454 Cross-reference data. Contains information on all entities referenced
2455 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2456 provide cross-reference information.
2457
2458 @end itemize
2459
2460 @noindent
2461 For a full detailed description of the format of the @file{ALI} file,
2462 see the source of the body of unit @code{Lib.Writ}, contained in file
2463 @file{lib-writ.adb} in the GNAT compiler sources.
2464
2465 @node Binding an Ada Program
2466 @section Binding an Ada Program
2467
2468 @noindent
2469 When using languages such as C and C++, once the source files have been
2470 compiled the only remaining step in building an executable program
2471 is linking the object modules together. This means that it is possible to
2472 link an inconsistent version of a program, in which two units have
2473 included different versions of the same header.
2474
2475 The rules of Ada do not permit such an inconsistent program to be built.
2476 For example, if two clients have different versions of the same package,
2477 it is illegal to build a program containing these two clients.
2478 These rules are enforced by the GNAT binder, which also determines an
2479 elaboration order consistent with the Ada rules.
2480
2481 The GNAT binder is run after all the object files for a program have
2482 been created. It is given the name of the main program unit, and from
2483 this it determines the set of units required by the program, by reading the
2484 corresponding ALI files. It generates error messages if the program is
2485 inconsistent or if no valid order of elaboration exists.
2486
2487 If no errors are detected, the binder produces a main program, in Ada by
2488 default, that contains calls to the elaboration procedures of those
2489 compilation unit that require them, followed by
2490 a call to the main program. This Ada program is compiled to generate the
2491 object file for the main program. The name of
2492 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2493 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2494 main program unit.
2495
2496 Finally, the linker is used to build the resulting executable program,
2497 using the object from the main program from the bind step as well as the
2498 object files for the Ada units of the program.
2499
2500 @node Mixed Language Programming
2501 @section Mixed Language Programming
2502 @cindex Mixed Language Programming
2503
2504 @noindent
2505 This section describes how to develop a mixed-language program,
2506 specifically one that comprises units in both Ada and C.
2507
2508 @menu
2509 * Interfacing to C::
2510 * Calling Conventions::
2511 @end menu
2512
2513 @node Interfacing to C
2514 @subsection Interfacing to C
2515 @noindent
2516 Interfacing Ada with a foreign language such as C involves using
2517 compiler directives to import and/or export entity definitions in each
2518 language---using @code{extern} statements in C, for instance, and the
2519 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2520 A full treatment of these topics is provided in Appendix B, section 1
2521 of the Ada Reference Manual.
2522
2523 There are two ways to build a program using GNAT that contains some Ada
2524 sources and some foreign language sources, depending on whether or not
2525 the main subprogram is written in Ada.  Here is a source example with
2526 the main subprogram in Ada:
2527
2528 @smallexample
2529 /* file1.c */
2530 #include <stdio.h>
2531
2532 void print_num (int num)
2533 @{
2534   printf ("num is %d.\n", num);
2535   return;
2536 @}
2537
2538 /* file2.c */
2539
2540 /* num_from_Ada is declared in my_main.adb */
2541 extern int num_from_Ada;
2542
2543 int get_num (void)
2544 @{
2545   return num_from_Ada;
2546 @}
2547 @end smallexample
2548
2549 @smallexample @c ada
2550 --  my_main.adb
2551 procedure My_Main is
2552
2553    --  Declare then export an Integer entity called num_from_Ada
2554    My_Num : Integer := 10;
2555    pragma Export (C, My_Num, "num_from_Ada");
2556
2557    --  Declare an Ada function spec for Get_Num, then use
2558    --  C function get_num for the implementation.
2559    function Get_Num return Integer;
2560    pragma Import (C, Get_Num, "get_num");
2561
2562    --  Declare an Ada procedure spec for Print_Num, then use
2563    --  C function print_num for the implementation.
2564    procedure Print_Num (Num : Integer);
2565    pragma Import (C, Print_Num, "print_num");
2566
2567 begin
2568    Print_Num (Get_Num);
2569 end My_Main;
2570 @end smallexample
2571
2572 @enumerate
2573 @item
2574 To build this example, first compile the foreign language files to
2575 generate object files:
2576 @smallexample
2577 ^gcc -c file1.c^gcc -c FILE1.C^
2578 ^gcc -c file2.c^gcc -c FILE2.C^
2579 @end smallexample
2580
2581 @item
2582 Then, compile the Ada units to produce a set of object files and ALI
2583 files:
2584 @smallexample
2585 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2586 @end smallexample
2587
2588 @item
2589 Run the Ada binder on the Ada main program:
2590 @smallexample
2591 gnatbind my_main.ali
2592 @end smallexample
2593
2594 @item
2595 Link the Ada main program, the Ada objects and the other language
2596 objects:
2597 @smallexample
2598 gnatlink my_main.ali file1.o file2.o
2599 @end smallexample
2600 @end enumerate
2601
2602 The last three steps can be grouped in a single command:
2603 @smallexample
2604 gnatmake my_main.adb -largs file1.o file2.o
2605 @end smallexample
2606
2607 @cindex Binder output file
2608 @noindent
2609 If the main program is in a language other than Ada, then you may have
2610 more than one entry point into the Ada subsystem. You must use a special
2611 binder option to generate callable routines that initialize and
2612 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2613 Calls to the initialization and finalization routines must be inserted
2614 in the main program, or some other appropriate point in the code. The
2615 call to initialize the Ada units must occur before the first Ada
2616 subprogram is called, and the call to finalize the Ada units must occur
2617 after the last Ada subprogram returns. The binder will place the
2618 initialization and finalization subprograms into the
2619 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2620 sources.  To illustrate, we have the following example:
2621
2622 @smallexample
2623 /* main.c */
2624 extern void adainit (void);
2625 extern void adafinal (void);
2626 extern int add (int, int);
2627 extern int sub (int, int);
2628
2629 int main (int argc, char *argv[])
2630 @{
2631   int a = 21, b = 7;
2632
2633   adainit();
2634
2635   /* Should print "21 + 7 = 28" */
2636   printf ("%d + %d = %d\n", a, b, add (a, b));
2637   /* Should print "21 - 7 = 14" */
2638   printf ("%d - %d = %d\n", a, b, sub (a, b));
2639
2640   adafinal();
2641 @}
2642 @end smallexample
2643
2644 @smallexample @c ada
2645 --  unit1.ads
2646 package Unit1 is
2647    function Add (A, B : Integer) return Integer;
2648    pragma Export (C, Add, "add");
2649 end Unit1;
2650
2651 --  unit1.adb
2652 package body Unit1 is
2653    function Add (A, B : Integer) return Integer is
2654    begin
2655       return A + B;
2656    end Add;
2657 end Unit1;
2658
2659 --  unit2.ads
2660 package Unit2 is
2661    function Sub (A, B : Integer) return Integer;
2662    pragma Export (C, Sub, "sub");
2663 end Unit2;
2664
2665 --  unit2.adb
2666 package body Unit2 is
2667    function Sub (A, B : Integer) return Integer is
2668    begin
2669       return A - B;
2670    end Sub;
2671 end Unit2;
2672 @end smallexample
2673
2674 @enumerate
2675 @item
2676 The build procedure for this application is similar to the last
2677 example's.  First, compile the foreign language files to generate object
2678 files:
2679 @smallexample
2680 ^gcc -c main.c^gcc -c main.c^
2681 @end smallexample
2682
2683 @item
2684 Next, compile the Ada units to produce a set of object files and ALI
2685 files:
2686 @smallexample
2687 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2688 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2689 @end smallexample
2690
2691 @item
2692 Run the Ada binder on every generated ALI file.  Make sure to use the
2693 @option{-n} option to specify a foreign main program:
2694 @smallexample
2695 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2696 @end smallexample
2697
2698 @item
2699 Link the Ada main program, the Ada objects and the foreign language
2700 objects. You need only list the last ALI file here:
2701 @smallexample
2702 gnatlink unit2.ali main.o -o exec_file
2703 @end smallexample
2704
2705 This procedure yields a binary executable called @file{exec_file}.
2706 @end enumerate
2707
2708 @noindent
2709 Depending on the circumstances (for example when your non-Ada main object
2710 does not provide symbol @code{main}), you may also need to instruct the
2711 GNAT linker not to include the standard startup objects by passing the
2712 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2713
2714 @node Calling Conventions
2715 @subsection Calling Conventions
2716 @cindex Foreign Languages
2717 @cindex Calling Conventions
2718 GNAT follows standard calling sequence conventions and will thus interface
2719 to any other language that also follows these conventions. The following
2720 Convention identifiers are recognized by GNAT:
2721
2722 @table @code
2723 @cindex Interfacing to Ada
2724 @cindex Other Ada compilers
2725 @cindex Convention Ada
2726 @item Ada
2727 This indicates that the standard Ada calling sequence will be
2728 used and all Ada data items may be passed without any limitations in the
2729 case where GNAT is used to generate both the caller and callee. It is also
2730 possible to mix GNAT generated code and code generated by another Ada
2731 compiler. In this case, the data types should be restricted to simple
2732 cases, including primitive types. Whether complex data types can be passed
2733 depends on the situation. Probably it is safe to pass simple arrays, such
2734 as arrays of integers or floats. Records may or may not work, depending
2735 on whether both compilers lay them out identically. Complex structures
2736 involving variant records, access parameters, tasks, or protected types,
2737 are unlikely to be able to be passed.
2738
2739 Note that in the case of GNAT running
2740 on a platform that supports HP Ada 83, a higher degree of compatibility
2741 can be guaranteed, and in particular records are layed out in an identical
2742 manner in the two compilers. Note also that if output from two different
2743 compilers is mixed, the program is responsible for dealing with elaboration
2744 issues. Probably the safest approach is to write the main program in the
2745 version of Ada other than GNAT, so that it takes care of its own elaboration
2746 requirements, and then call the GNAT-generated adainit procedure to ensure
2747 elaboration of the GNAT components. Consult the documentation of the other
2748 Ada compiler for further details on elaboration.
2749
2750 However, it is not possible to mix the tasking run time of GNAT and
2751 HP Ada 83, All the tasking operations must either be entirely within
2752 GNAT compiled sections of the program, or entirely within HP Ada 83
2753 compiled sections of the program.
2754
2755 @cindex Interfacing to Assembly
2756 @cindex Convention Assembler
2757 @item Assembler
2758 Specifies assembler as the convention. In practice this has the
2759 same effect as convention Ada (but is not equivalent in the sense of being
2760 considered the same convention).
2761
2762 @cindex Convention Asm
2763 @findex Asm
2764 @item Asm
2765 Equivalent to Assembler.
2766
2767 @cindex Interfacing to COBOL
2768 @cindex Convention COBOL
2769 @findex COBOL
2770 @item COBOL
2771 Data will be passed according to the conventions described
2772 in section B.4 of the Ada Reference Manual.
2773
2774 @findex C
2775 @cindex Interfacing to C
2776 @cindex Convention C
2777 @item C
2778 Data will be passed according to the conventions described
2779 in section B.3 of the Ada Reference Manual.
2780
2781 A note on interfacing to a C ``varargs'' function:
2782 @findex C varargs function
2783 @cindex Interfacing to C varargs function
2784 @cindex varargs function interfaces
2785
2786 @itemize @bullet
2787 @item
2788 In C, @code{varargs} allows a function to take a variable number of
2789 arguments. There is no direct equivalent in this to Ada. One
2790 approach that can be used is to create a C wrapper for each
2791 different profile and then interface to this C wrapper. For
2792 example, to print an @code{int} value using @code{printf},
2793 create a C function @code{printfi} that takes two arguments, a
2794 pointer to a string and an int, and calls @code{printf}.
2795 Then in the Ada program, use pragma @code{Import} to
2796 interface to @code{printfi}.
2797
2798 @item
2799 It may work on some platforms to directly interface to
2800 a @code{varargs} function by providing a specific Ada profile
2801 for a particular call. However, this does not work on
2802 all platforms, since there is no guarantee that the
2803 calling sequence for a two argument normal C function
2804 is the same as for calling a @code{varargs} C function with
2805 the same two arguments.
2806 @end itemize
2807
2808 @cindex Convention Default
2809 @findex Default
2810 @item Default
2811 Equivalent to C.
2812
2813 @cindex Convention External
2814 @findex External
2815 @item External
2816 Equivalent to C.
2817
2818 @ifclear vms
2819 @findex C++
2820 @cindex Interfacing to C++
2821 @cindex Convention C++
2822 @item C_Plus_Plus (or CPP)
2823 This stands for C++. For most purposes this is identical to C.
2824 See the separate description of the specialized GNAT pragmas relating to
2825 C++ interfacing for further details.
2826 @end ifclear
2827
2828 @findex Fortran
2829 @cindex Interfacing to Fortran
2830 @cindex Convention Fortran
2831 @item Fortran
2832 Data will be passed according to the conventions described
2833 in section B.5 of the Ada Reference Manual.
2834
2835 @item Intrinsic
2836 This applies to an intrinsic operation, as defined in the Ada
2837 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2838 this means that the body of the subprogram is provided by the compiler itself,
2839 usually by means of an efficient code sequence, and that the user does not
2840 supply an explicit body for it. In an application program, the pragma can
2841 only be applied to the following two sets of names, which the GNAT compiler
2842 recognizes.
2843
2844 @itemize @bullet
2845 @item
2846 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2847 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2848 two formal parameters. The
2849 first one must be a signed integer type or a modular type with a binary
2850 modulus, and the second parameter must be of type Natural.
2851 The return type must be the same as the type of the first argument. The size
2852 of this type can only be 8, 16, 32, or 64.
2853 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2854 The corresponding operator declaration must have parameters and result type
2855 that have the same root numeric type (for example, all three are long_float
2856 types). This simplifies the definition of operations that use type checking
2857 to perform dimensional checks:
2858
2859 @smallexample @c ada
2860 type Distance is new Long_Float;
2861 type Time     is new Long_Float;
2862 type Velocity is new Long_Float;
2863 function "/" (D : Distance; T : Time)
2864   return Velocity;
2865 pragma Import (Intrinsic, "/");
2866 @end smallexample
2867
2868 @noindent
2869 This common idiom is often programmed with a generic definition and an
2870 explicit body. The pragma makes it simpler to introduce such declarations.
2871 It incurs no overhead in compilation time or code size, because it is
2872 implemented as a single machine instruction.
2873 @end itemize
2874 @noindent
2875
2876 @ifset unw
2877 @findex Stdcall
2878 @cindex Convention Stdcall
2879 @item Stdcall
2880 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2881 and specifies that the @code{Stdcall} calling sequence will be used,
2882 as defined by the NT API. Nevertheless, to ease building
2883 cross-platform bindings this convention will be handled as a @code{C} calling
2884 convention on non Windows platforms.
2885
2886 @findex DLL
2887 @cindex Convention DLL
2888 @item DLL
2889 This is equivalent to @code{Stdcall}.
2890
2891 @findex Win32
2892 @cindex Convention Win32
2893 @item Win32
2894 This is equivalent to @code{Stdcall}.
2895 @end ifset
2896
2897 @findex Stubbed
2898 @cindex Convention Stubbed
2899 @item Stubbed
2900 This is a special convention that indicates that the compiler
2901 should provide a stub body that raises @code{Program_Error}.
2902 @end table
2903
2904 @noindent
2905 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2906 that can be used to parametrize conventions and allow additional synonyms
2907 to be specified. For example if you have legacy code in which the convention
2908 identifier Fortran77 was used for Fortran, you can use the configuration
2909 pragma:
2910
2911 @smallexample @c ada
2912 pragma Convention_Identifier (Fortran77, Fortran);
2913 @end smallexample
2914
2915 @noindent
2916 And from now on the identifier Fortran77 may be used as a convention
2917 identifier (for example in an @code{Import} pragma) with the same
2918 meaning as Fortran.
2919
2920 @ifclear vms
2921 @node Building Mixed Ada & C++ Programs
2922 @section Building Mixed Ada and C++ Programs
2923
2924 @noindent
2925 A programmer inexperienced with mixed-language development may find that
2926 building an application containing both Ada and C++ code can be a
2927 challenge.  This section gives a few
2928 hints that should make this task easier. The first section addresses
2929 the differences between interfacing with C and interfacing with C++.
2930 The second section
2931 looks into the delicate problem of linking the complete application from
2932 its Ada and C++ parts. The last section gives some hints on how the GNAT
2933 run-time library can be adapted in order to allow inter-language dispatching
2934 with a new C++ compiler.
2935
2936 @menu
2937 * Interfacing to C++::
2938 * Linking a Mixed C++ & Ada Program::
2939 * A Simple Example::
2940 * Interfacing with C++ at the Class Level::
2941 @end menu
2942
2943 @node Interfacing to C++
2944 @subsection Interfacing to C++
2945
2946 @noindent
2947 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2948 generating code that is compatible with the G++ Application Binary
2949 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2950
2951 @noindent
2952 Interfacing can be done at 3 levels: simple data, subprograms, and
2953 classes. In the first two cases, GNAT offers a specific @var{Convention
2954 C_Plus_Plus} (or @var{CPP}) that behaves exactly like @var{Convention C}.
2955 Usually, C++ mangles the names of subprograms, and currently, GNAT does
2956 not provide any help to solve the demangling problem. This problem can be
2957 addressed in two ways:
2958 @itemize @bullet
2959 @item
2960 by modifying the C++ code in order to force a C convention using
2961 the @code{extern "C"} syntax.
2962
2963 @item
2964 by figuring out the mangled name and use it as the Link_Name argument of
2965 the pragma import.
2966 @end itemize
2967
2968 @noindent
2969 Interfacing at the class level can be achieved by using the GNAT specific
2970 pragmas such as @code{CPP_Constructor}. See the GNAT Reference Manual for
2971 additional information.
2972
2973 @node Linking a Mixed C++ & Ada Program
2974 @subsection Linking a Mixed C++ & Ada Program
2975
2976 @noindent
2977 Usually the linker of the C++ development system must be used to link
2978 mixed applications because most C++ systems will resolve elaboration
2979 issues (such as calling constructors on global class instances)
2980 transparently during the link phase. GNAT has been adapted to ease the
2981 use of a foreign linker for the last phase. Three cases can be
2982 considered:
2983 @enumerate
2984
2985 @item
2986 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2987 The C++ linker can simply be called by using the C++ specific driver
2988 called @code{c++}. Note that this setup is not very common because it
2989 may involve recompiling the whole GCC tree from sources, which makes it
2990 harder to upgrade the compilation system for one language without
2991 destabilizing the other.
2992
2993 @smallexample
2994 $ c++ -c file1.C
2995 $ c++ -c file2.C
2996 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
2997 @end smallexample
2998
2999 @item
3000 Using GNAT and G++ from two different GCC installations: If both
3001 compilers are on the PATH, the previous method may be used. It is
3002 important to note that environment variables such as C_INCLUDE_PATH,
3003 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3004 at the same time and may make one of the two compilers operate
3005 improperly if set during invocation of the wrong compiler.  It is also
3006 very important that the linker uses the proper @file{libgcc.a} GCC
3007 library -- that is, the one from the C++ compiler installation. The
3008 implicit link command as suggested in the gnatmake command from the
3009 former example can be replaced by an explicit link command with the
3010 full-verbosity option in order to verify which library is used:
3011 @smallexample
3012 $ gnatbind ada_unit
3013 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3014 @end smallexample
3015 If there is a problem due to interfering environment variables, it can
3016 be worked around by using an intermediate script. The following example
3017 shows the proper script to use when GNAT has not been installed at its
3018 default location and g++ has been installed at its default location:
3019
3020 @smallexample
3021 $ cat ./my_script
3022 #!/bin/sh
3023 unset BINUTILS_ROOT
3024 unset GCC_ROOT
3025 c++ $*
3026 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3027 @end smallexample
3028
3029 @item
3030 Using a non-GNU C++ compiler: The commands previously described can be
3031 used to insure that the C++ linker is used. Nonetheless, you need to add
3032 a few more parameters to the link command line, depending on the exception
3033 mechanism used.
3034
3035 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3036 to the libgcc libraries are required:
3037
3038 @smallexample
3039 $ cat ./my_script
3040 #!/bin/sh
3041 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3042 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3043 @end smallexample
3044
3045 Where CC is the name of the non-GNU C++ compiler.
3046
3047 If the @code{zero cost} exception mechanism is used, and the platform
3048 supports automatic registration of exception tables (e.g. Solaris or IRIX),
3049 paths to more objects are required:
3050
3051 @smallexample
3052 $ cat ./my_script
3053 #!/bin/sh
3054 CC `gcc -print-file-name=crtbegin.o` $* \
3055 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3056 `gcc -print-file-name=crtend.o`
3057 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3058 @end smallexample
3059
3060 If the @code{zero cost} exception mechanism is used, and the platform
3061 doesn't support automatic registration of exception tables (e.g. HP-UX,
3062 Tru64 or AIX), the simple approach described above will not work and
3063 a pre-linking phase using GNAT will be necessary.
3064
3065 @end enumerate
3066
3067 @node A Simple Example
3068 @subsection  A Simple Example
3069 @noindent
3070 The following example, provided as part of the GNAT examples, shows how
3071 to achieve procedural interfacing between Ada and C++ in both
3072 directions. The C++ class A has two methods. The first method is exported
3073 to Ada by the means of an extern C wrapper function. The second method
3074 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3075 a limited record with a layout comparable to the C++ class. The Ada
3076 subprogram, in turn, calls the C++ method. So, starting from the C++
3077 main program, the process passes back and forth between the two
3078 languages.
3079
3080 @noindent
3081 Here are the compilation commands:
3082 @smallexample
3083 $ gnatmake -c simple_cpp_interface
3084 $ c++ -c cpp_main.C
3085 $ c++ -c ex7.C
3086 $ gnatbind -n simple_cpp_interface
3087 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3088       -lstdc++ ex7.o cpp_main.o
3089 @end smallexample
3090
3091 @noindent
3092 Here are the corresponding sources:
3093 @smallexample
3094
3095 //cpp_main.C
3096
3097 #include "ex7.h"
3098
3099 extern "C" @{
3100   void adainit (void);
3101   void adafinal (void);
3102   void method1 (A *t);
3103 @}
3104
3105 void method1 (A *t)
3106 @{
3107   t->method1 ();
3108 @}
3109
3110 int main ()
3111 @{
3112   A obj;
3113   adainit ();
3114   obj.method2 (3030);
3115   adafinal ();
3116 @}
3117
3118 //ex7.h
3119
3120 class Origin @{
3121  public:
3122   int o_value;
3123 @};
3124 class A : public Origin @{
3125  public:
3126   void method1 (void);
3127   void method2 (int v);
3128   A();
3129   int   a_value;
3130 @};
3131
3132 //ex7.C
3133
3134 #include "ex7.h"
3135 #include <stdio.h>
3136
3137 extern "C" @{ void ada_method2 (A *t, int v);@}
3138
3139 void A::method1 (void)
3140 @{
3141   a_value = 2020;
3142   printf ("in A::method1, a_value = %d \n",a_value);
3143
3144 @}
3145
3146 void A::method2 (int v)
3147 @{
3148    ada_method2 (this, v);
3149    printf ("in A::method2, a_value = %d \n",a_value);
3150
3151 @}
3152
3153 A::A(void)
3154 @{
3155    a_value = 1010;
3156   printf ("in A::A, a_value = %d \n",a_value);
3157 @}
3158 @end smallexample
3159
3160 @smallexample @c ada
3161 -- Ada sources
3162 package body Simple_Cpp_Interface is
3163
3164    procedure Ada_Method2 (This : in out A; V : Integer) is
3165    begin
3166       Method1 (This);
3167       This.A_Value := V;
3168    end Ada_Method2;
3169
3170 end Simple_Cpp_Interface;
3171
3172 with System;
3173 package Simple_Cpp_Interface is
3174    type A is limited
3175       record
3176          Vptr    : System.Address;
3177          O_Value : Integer;
3178          A_Value : Integer;
3179       end record;
3180    pragma Convention (C, A);
3181
3182    procedure Method1 (This : in out A);
3183    pragma Import (C, Method1);
3184
3185    procedure Ada_Method2 (This : in out A; V : Integer);
3186    pragma Export (C, Ada_Method2);
3187
3188 end Simple_Cpp_Interface;
3189 @end smallexample
3190
3191 @node Interfacing with C++ at the Class Level
3192 @subsection Interfacing with C++ at the Class Level
3193 @noindent
3194 In this section we demonstrate the GNAT features for interfacing with
3195 C++ by means of an example making use of Ada 2005 abstract interface
3196 types. This example consists of a classification of animals; classes
3197 have been used to model our main classification of animals, and
3198 interfaces provide support for the management of secondary
3199 classifications. We first demonstrate a case in which the types and
3200 constructors are defined on the C++ side and imported from the Ada
3201 side, and latter the reverse case.
3202
3203 The root of our derivation will be the @code{Animal} class, with a
3204 single private attribute (the @code{Age} of the animal) and two public
3205 primitives to set and get the value of this attribute.
3206
3207 @smallexample
3208 @b{class} Animal @{
3209  @b{public}:
3210    @b{virtual} void Set_Age (int New_Age);
3211    @b{virtual} int Age ();
3212  @b{private}:
3213    int Age_Count;
3214 @};
3215 @end smallexample
3216
3217 Abstract interface types are defined in C++ by means of classes with pure
3218 virtual functions and no data members. In our example we will use two
3219 interfaces that provide support for the common management of @code{Carnivore}
3220 and @code{Domestic} animals:
3221
3222 @smallexample
3223 @b{class} Carnivore @{
3224 @b{public}:
3225    @b{virtual} int Number_Of_Teeth () = 0;
3226 @};
3227
3228 @b{class} Domestic @{
3229 @b{public}:
3230    @b{virtual void} Set_Owner (char* Name) = 0;
3231 @};
3232 @end smallexample
3233
3234 Using these declarations, we can now say that a @code{Dog} is an animal that is
3235 both Carnivore and Domestic, that is:
3236
3237 @smallexample
3238 @b{class} Dog : Animal, Carnivore, Domestic @{
3239  @b{public}:
3240    @b{virtual} int  Number_Of_Teeth ();
3241    @b{virtual} void Set_Owner (char* Name);
3242
3243    Dog(); // Constructor
3244  @b{private}:
3245    int  Tooth_Count;
3246    char *Owner;
3247 @};
3248 @end smallexample
3249
3250 In the following examples we will assume that the previous declarations are
3251 located in a file named @code{animals.h}. The following package demonstrates
3252 how to import these C++ declarations from the Ada side:
3253
3254 @smallexample @c ada
3255 with Interfaces.C.Strings; use Interfaces.C.Strings;
3256 package Animals is
3257   type Carnivore is interface;
3258   pragma Convention (C_Plus_Plus, Carnivore);
3259   function Number_Of_Teeth (X : Carnivore)
3260      return Natural is abstract;
3261
3262   type Domestic is interface;
3263   pragma Convention (C_Plus_Plus, Set_Owner);
3264   procedure Set_Owner
3265     (X    : in out Domestic;
3266      Name : Chars_Ptr) is abstract;
3267
3268   type Animal is tagged record
3269     Age : Natural := 0;
3270   end record;
3271   pragma Import (C_Plus_Plus, Animal);
3272
3273   procedure Set_Age (X : in out Animal; Age : Integer);
3274   pragma Import (C_Plus_Plus, Set_Age);
3275
3276   function Age (X : Animal) return Integer;
3277   pragma Import (C_Plus_Plus, Age);
3278
3279   type Dog is new Animal and Carnivore and Domestic with record
3280     Tooth_Count : Natural;
3281     Owner       : String (1 .. 30);
3282   end record;
3283   pragma Import (C_Plus_Plus, Dog);
3284
3285   function Number_Of_Teeth (A : Dog) return Integer;
3286   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3287
3288   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3289   pragma Import (C_Plus_Plus, Set_Owner);
3290
3291   function New_Dog return Dog'Class;
3292   pragma CPP_Constructor (New_Dog);
3293   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3294 end Animals;
3295 @end smallexample
3296
3297 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3298 interfacing with these C++ classes is easy. The only requirement is that all
3299 the primitives and components must be declared exactly in the same order in
3300 the two languages.
3301
3302 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3303 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3304 the arguments to the called primitives will be the same as for C++. For the
3305 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3306 to indicate that they have been defined on the C++ side; this is required
3307 because the dispatch table associated with these tagged types will be built
3308 in the C++ side and therefore will not contain the predefined Ada primitives
3309 which Ada would otherwise expect.
3310
3311 As the reader can see there is no need to indicate the C++ mangled names
3312 associated with each subprogram because it is assumed that all the calls to
3313 these primitives will be dispatching calls. The only exception is the
3314 constructor, which must be registered with the compiler by means of
3315 @code{pragma CPP_Constructor} and needs to provide its associated C++
3316 mangled name because the Ada compiler generates direct calls to it.
3317
3318 With the above packages we can now declare objects of type Dog on the Ada side
3319 and dispatch calls to the corresponding subprograms on the C++ side. We can
3320 also extend the tagged type Dog with further fields and primitives, and
3321 override some of its C++ primitives on the Ada side. For example, here we have
3322 a type derivation defined on the Ada side that inherits all the dispatching
3323 primitives of the ancestor from the C++ side.
3324
3325 @smallexample
3326 @b{with} Animals; @b{use} Animals;
3327 @b{package} Vaccinated_Animals @b{is}
3328   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3329   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3330 @b{end} Vaccinated_Animals;
3331 @end smallexample
3332
3333 It is important to note that, because of the ABI compatibility, the programmer
3334 does not need to add any further information to indicate either the object
3335 layout or the dispatch table entry associated with each dispatching operation.
3336
3337 Now let us define all the types and constructors on the Ada side and export
3338 them to C++, using the same hierarchy of our previous example:
3339
3340 @smallexample @c ada
3341 with Interfaces.C.Strings;
3342 use Interfaces.C.Strings;
3343 package Animals is
3344   type Carnivore is interface;
3345   pragma Convention (C_Plus_Plus, Carnivore);
3346   function Number_Of_Teeth (X : Carnivore)
3347      return Natural is abstract;
3348
3349   type Domestic is interface;
3350   pragma Convention (C_Plus_Plus, Set_Owner);
3351   procedure Set_Owner
3352     (X    : in out Domestic;
3353      Name : Chars_Ptr) is abstract;
3354
3355   type Animal is tagged record
3356     Age : Natural := 0;
3357   end record;
3358   pragma Convention (C_Plus_Plus, Animal);
3359
3360   procedure Set_Age (X : in out Animal; Age : Integer);
3361   pragma Export (C_Plus_Plus, Set_Age);
3362
3363   function Age (X : Animal) return Integer;
3364   pragma Export (C_Plus_Plus, Age);
3365
3366   type Dog is new Animal and Carnivore and Domestic with record
3367     Tooth_Count : Natural;
3368     Owner       : String (1 .. 30);
3369   end record;
3370   pragma Convention (C_Plus_Plus, Dog);
3371
3372   function Number_Of_Teeth (A : Dog) return Integer;
3373   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3374
3375   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3376   pragma Export (C_Plus_Plus, Set_Owner);
3377
3378   function New_Dog return Dog'Class;
3379   pragma Export (C_Plus_Plus, New_Dog);
3380 end Animals;
3381 @end smallexample
3382
3383 Compared with our previous example the only difference is the use of
3384 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3385 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3386 nothing else to be done; as explained above, the only requirement is that all
3387 the primitives and components are declared in exactly the same order.
3388
3389 For completeness, let us see a brief C++ main program that uses the
3390 declarations available in @code{animals.h} (presented in our first example) to
3391 import and use the declarations from the Ada side, properly initializing and
3392 finalizing the Ada run-time system along the way:
3393
3394 @smallexample
3395 @b{#include} "animals.h"
3396 @b{#include} <iostream>
3397 @b{using namespace} std;
3398
3399 void Check_Carnivore (Carnivore *obj) @{ ... @}
3400 void Check_Domestic (Domestic *obj)   @{ ... @}
3401 void Check_Animal (Animal *obj)       @{ ... @}
3402 void Check_Dog (Dog *obj)             @{ ... @}
3403
3404 @b{extern} "C" @{
3405   void adainit (void);
3406   void adafinal (void);
3407   Dog* new_dog ();
3408 @}
3409
3410 void test ()
3411 @{
3412   Dog *obj = new_dog();  // Ada constructor
3413   Check_Carnivore (obj); // Check secondary DT
3414   Check_Domestic (obj);  // Check secondary DT
3415   Check_Animal (obj);    // Check primary DT
3416   Check_Dog (obj);       // Check primary DT
3417 @}
3418
3419 int main ()
3420 @{
3421   adainit ();  test();  adafinal ();
3422   return 0;
3423 @}
3424 @end smallexample
3425
3426 @node Comparison between GNAT and C/C++ Compilation Models
3427 @section Comparison between GNAT and C/C++ Compilation Models
3428
3429 @noindent
3430 The GNAT model of compilation is close to the C and C++ models. You can
3431 think of Ada specs as corresponding to header files in C. As in C, you
3432 don't need to compile specs; they are compiled when they are used. The
3433 Ada @code{with} is similar in effect to the @code{#include} of a C
3434 header.
3435
3436 One notable difference is that, in Ada, you may compile specs separately
3437 to check them for semantic and syntactic accuracy. This is not always
3438 possible with C headers because they are fragments of programs that have
3439 less specific syntactic or semantic rules.
3440
3441 The other major difference is the requirement for running the binder,
3442 which performs two important functions. First, it checks for
3443 consistency. In C or C++, the only defense against assembling
3444 inconsistent programs lies outside the compiler, in a makefile, for
3445 example. The binder satisfies the Ada requirement that it be impossible
3446 to construct an inconsistent program when the compiler is used in normal
3447 mode.
3448
3449 @cindex Elaboration order control
3450 The other important function of the binder is to deal with elaboration
3451 issues. There are also elaboration issues in C++ that are handled
3452 automatically. This automatic handling has the advantage of being
3453 simpler to use, but the C++ programmer has no control over elaboration.
3454 Where @code{gnatbind} might complain there was no valid order of
3455 elaboration, a C++ compiler would simply construct a program that
3456 malfunctioned at run time.
3457 @end ifclear
3458
3459 @node Comparison between GNAT and Conventional Ada Library Models
3460 @section Comparison between GNAT and Conventional Ada Library Models
3461
3462 @noindent
3463 This section is intended for Ada programmers who have
3464 used an Ada compiler implementing the traditional Ada library
3465 model, as described in the Ada Reference Manual.
3466
3467 @cindex GNAT library
3468 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3469 source files themselves acts as the library. Compiling Ada programs does
3470 not generate any centralized information, but rather an object file and
3471 a ALI file, which are of interest only to the binder and linker.
3472 In a traditional system, the compiler reads information not only from
3473 the source file being compiled, but also from the centralized library.
3474 This means that the effect of a compilation depends on what has been
3475 previously compiled. In particular:
3476
3477 @itemize @bullet
3478 @item
3479 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3480 to the version of the unit most recently compiled into the library.
3481
3482 @item
3483 Inlining is effective only if the necessary body has already been
3484 compiled into the library.
3485
3486 @item
3487 Compiling a unit may obsolete other units in the library.
3488 @end itemize
3489
3490 @noindent
3491 In GNAT, compiling one unit never affects the compilation of any other
3492 units because the compiler reads only source files. Only changes to source
3493 files can affect the results of a compilation. In particular:
3494
3495 @itemize @bullet
3496 @item
3497 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3498 to the source version of the unit that is currently accessible to the
3499 compiler.
3500
3501 @item
3502 @cindex Inlining
3503 Inlining requires the appropriate source files for the package or
3504 subprogram bodies to be available to the compiler. Inlining is always
3505 effective, independent of the order in which units are complied.
3506
3507 @item
3508 Compiling a unit never affects any other compilations. The editing of
3509 sources may cause previous compilations to be out of date if they
3510 depended on the source file being modified.
3511 @end itemize
3512
3513 @noindent
3514 The most important result of these differences is that order of compilation
3515 is never significant in GNAT. There is no situation in which one is
3516 required to do one compilation before another. What shows up as order of
3517 compilation requirements in the traditional Ada library becomes, in
3518 GNAT, simple source dependencies; in other words, there is only a set
3519 of rules saying what source files must be present when a file is
3520 compiled.
3521
3522 @ifset vms
3523 @node Placement of temporary files
3524 @section Placement of temporary files
3525 @cindex Temporary files (user control over placement)
3526
3527 @noindent
3528 GNAT creates temporary files in the directory designated by the environment
3529 variable @env{TMPDIR}.
3530 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3531 for detailed information on how environment variables are resolved.
3532 For most users the easiest way to make use of this feature is to simply
3533 define @env{TMPDIR} as a job level logical name).
3534 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3535 for compiler temporary files, then you can include something like the
3536 following command in your @file{LOGIN.COM} file:
3537
3538 @smallexample
3539 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3540 @end smallexample
3541
3542 @noindent
3543 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3544 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3545 designated by @env{TEMP}.
3546 If none of these environment variables are defined then GNAT uses the
3547 directory designated by the logical name @code{SYS$SCRATCH:}
3548 (by default the user's home directory). If all else fails
3549 GNAT uses the current directory for temporary files.
3550 @end ifset
3551
3552 @c *************************
3553 @node Compiling Using gcc
3554 @chapter Compiling Using @command{gcc}
3555
3556 @noindent
3557 This chapter discusses how to compile Ada programs using the @command{gcc}
3558 command. It also describes the set of switches
3559 that can be used to control the behavior of the compiler.
3560 @menu
3561 * Compiling Programs::
3562 * Switches for gcc::
3563 * Search Paths and the Run-Time Library (RTL)::
3564 * Order of Compilation Issues::
3565 * Examples::
3566 @end menu
3567
3568 @node Compiling Programs
3569 @section Compiling Programs
3570
3571 @noindent
3572 The first step in creating an executable program is to compile the units
3573 of the program using the @command{gcc} command. You must compile the
3574 following files:
3575
3576 @itemize @bullet
3577 @item
3578 the body file (@file{.adb}) for a library level subprogram or generic
3579 subprogram
3580
3581 @item
3582 the spec file (@file{.ads}) for a library level package or generic
3583 package that has no body
3584
3585 @item
3586 the body file (@file{.adb}) for a library level package
3587 or generic package that has a body
3588
3589 @end itemize
3590
3591 @noindent
3592 You need @emph{not} compile the following files
3593
3594 @itemize @bullet
3595
3596 @item
3597 the spec of a library unit which has a body
3598
3599 @item
3600 subunits
3601 @end itemize
3602
3603 @noindent
3604 because they are compiled as part of compiling related units. GNAT
3605 package specs
3606 when the corresponding body is compiled, and subunits when the parent is
3607 compiled.
3608
3609 @cindex cannot generate code
3610 If you attempt to compile any of these files, you will get one of the
3611 following error messages (where fff is the name of the file you compiled):
3612
3613 @smallexample
3614 cannot generate code for file @var{fff} (package spec)
3615 to check package spec, use -gnatc
3616
3617 cannot generate code for file @var{fff} (missing subunits)
3618 to check parent unit, use -gnatc
3619
3620 cannot generate code for file @var{fff} (subprogram spec)
3621 to check subprogram spec, use -gnatc
3622
3623 cannot generate code for file @var{fff} (subunit)
3624 to check subunit, use -gnatc
3625 @end smallexample
3626
3627 @noindent
3628 As indicated by the above error messages, if you want to submit
3629 one of these files to the compiler to check for correct semantics
3630 without generating code, then use the @option{-gnatc} switch.
3631
3632 The basic command for compiling a file containing an Ada unit is
3633
3634 @smallexample
3635 $ gcc -c [@var{switches}] @file{file name}
3636 @end smallexample
3637
3638 @noindent
3639 where @var{file name} is the name of the Ada file (usually
3640 having an extension
3641 @file{.ads} for a spec or @file{.adb} for a body).
3642 @ifclear vms
3643 You specify the
3644 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3645 @end ifclear
3646 The result of a successful compilation is an object file, which has the
3647 same name as the source file but an extension of @file{.o} and an Ada
3648 Library Information (ALI) file, which also has the same name as the
3649 source file, but with @file{.ali} as the extension. GNAT creates these
3650 two output files in the current directory, but you may specify a source
3651 file in any directory using an absolute or relative path specification
3652 containing the directory information.
3653
3654 @findex gnat1
3655 @command{gcc} is actually a driver program that looks at the extensions of
3656 the file arguments and loads the appropriate compiler. For example, the
3657 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3658 These programs are in directories known to the driver program (in some
3659 configurations via environment variables you set), but need not be in
3660 your path. The @command{gcc} driver also calls the assembler and any other
3661 utilities needed to complete the generation of the required object
3662 files.
3663
3664 It is possible to supply several file names on the same @command{gcc}
3665 command. This causes @command{gcc} to call the appropriate compiler for
3666 each file. For example, the following command lists three separate
3667 files to be compiled:
3668
3669 @smallexample
3670 $ gcc -c x.adb y.adb z.c
3671 @end smallexample
3672
3673 @noindent
3674 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3675 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3676 The compiler generates three object files @file{x.o}, @file{y.o} and
3677 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3678 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3679 @ifclear vms
3680 except for
3681 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3682 @end ifclear
3683
3684 @node Switches for gcc
3685 @section Switches for @command{gcc}
3686
3687 @noindent
3688 The @command{gcc} command accepts switches that control the
3689 compilation process. These switches are fully described in this section.
3690 First we briefly list all the switches, in alphabetical order, then we
3691 describe the switches in more detail in functionally grouped sections.
3692
3693 More switches exist for GCC than those documented here, especially
3694 for specific targets. However, their use is not recommended as
3695 they may change code generation in ways that are incompatible with
3696 the Ada run-time library, or can cause inconsistencies between
3697 compilation units.
3698
3699 @menu
3700 * Output and Error Message Control::
3701 * Warning Message Control::
3702 * Debugging and Assertion Control::
3703 * Validity Checking::
3704 * Style Checking::
3705 * Run-Time Checks::
3706 * Using gcc for Syntax Checking::
3707 * Using gcc for Semantic Checking::
3708 * Compiling Different Versions of Ada::
3709 * Character Set Control::
3710 * File Naming Control::
3711 * Subprogram Inlining Control::
3712 * Auxiliary Output Control::
3713 * Debugging Control::
3714 * Exception Handling Control::
3715 * Units to Sources Mapping Files::
3716 * Integrated Preprocessing::
3717 * Code Generation Control::
3718 @ifset vms
3719 * Return Codes::
3720 @end ifset
3721 @end menu
3722
3723 @table @option
3724 @c !sort!
3725 @ifclear vms
3726 @cindex @option{-b} (@command{gcc})
3727 @item -b @var{target}
3728 Compile your program to run on @var{target}, which is the name of a
3729 system configuration. You must have a GNAT cross-compiler built if
3730 @var{target} is not the same as your host system.
3731
3732 @item -B@var{dir}
3733 @cindex @option{-B} (@command{gcc})
3734 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3735 from @var{dir} instead of the default location. Only use this switch
3736 when multiple versions of the GNAT compiler are available. See the
3737 @command{gcc} manual page for further details. You would normally use the
3738 @option{-b} or @option{-V} switch instead.
3739
3740 @item -c
3741 @cindex @option{-c} (@command{gcc})
3742 Compile. Always use this switch when compiling Ada programs.
3743
3744 Note: for some other languages when using @command{gcc}, notably in
3745 the case of C and C++, it is possible to use
3746 use @command{gcc} without a @option{-c} switch to
3747 compile and link in one step. In the case of GNAT, you
3748 cannot use this approach, because the binder must be run
3749 and @command{gcc} cannot be used to run the GNAT binder.
3750 @end ifclear
3751
3752 @item -fno-inline
3753 @cindex @option{-fno-inline} (@command{gcc})
3754 Suppresses all back-end inlining, even if other optimization or inlining
3755 switches are set.
3756 This includes suppression of inlining that results
3757 from the use of the pragma @code{Inline_Always}.
3758 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3759 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3760 effect if this switch is present.
3761
3762 @item -fno-strict-aliasing
3763 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3764 Causes the compiler to avoid assumptions regarding non-aliasing
3765 of objects of different types. See
3766 @ref{Optimization and Strict Aliasing} for details.
3767
3768 @item -fstack-check
3769 @cindex @option{-fstack-check} (@command{gcc})
3770 Activates stack checking.
3771 See @ref{Stack Overflow Checking} for details.
3772
3773 @item -fstack-usage
3774 @cindex @option{-fstack-usage} (@command{gcc})
3775 Makes the compiler output stack usage information for the program, on a
3776 per-function basis. See @ref{Static Stack Usage Analysis} for details.
3777
3778 @item -fcallgraph-info[=su]
3779 @cindex @option{-fcallgraph-info} (@command{gcc})
3780 Makes the compiler output callgraph information for the program, on a
3781 per-file basis.  The information is generated in the VCG format.  It can
3782 be decorated with stack-usage per-node information.
3783
3784 @item ^-g^/DEBUG^
3785 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3786 Generate debugging information. This information is stored in the object
3787 file and copied from there to the final executable file by the linker,
3788 where it can be read by the debugger. You must use the
3789 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3790
3791 @item -gnat83
3792 @cindex @option{-gnat83} (@command{gcc})
3793 Enforce Ada 83 restrictions.
3794
3795 @item -gnat95
3796 @cindex @option{-gnat95} (@command{gcc})
3797 Enforce Ada 95 restrictions.
3798
3799 @item -gnat05
3800 @cindex @option{-gnat05} (@command{gcc})
3801 Allow full Ada 2005 features.
3802
3803 @item -gnata
3804 @cindex @option{-gnata} (@command{gcc})
3805 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3806 activated. Note that these pragmas can also be controlled using the
3807 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3808
3809 @item -gnatA
3810 @cindex @option{-gnatA} (@command{gcc})
3811 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3812 it will be ignored.
3813
3814 @item -gnatb
3815 @cindex @option{-gnatb} (@command{gcc})
3816 Generate brief messages to @file{stderr} even if verbose mode set.
3817
3818 @item -gnatc
3819 @cindex @option{-gnatc} (@command{gcc})
3820 Check syntax and semantics only (no code generation attempted).
3821
3822 @item -gnatd
3823 @cindex @option{-gnatd} (@command{gcc})
3824 Specify debug options for the compiler. The string of characters after
3825 the @option{-gnatd} specify the specific debug options. The possible
3826 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3827 compiler source file @file{debug.adb} for details of the implemented
3828 debug options. Certain debug options are relevant to applications
3829 programmers, and these are documented at appropriate points in this
3830 users guide.
3831
3832 @item -gnatD
3833 @cindex @option{-gnatD} (@command{gcc})
3834 Create expanded source files for source level debugging. This switch
3835 also suppress generation of cross-reference information
3836 (see @option{-gnatx}).
3837
3838 @item -gnatec=@var{path}
3839 @cindex @option{-gnatec} (@command{gcc})
3840 Specify a configuration pragma file
3841 @ifclear vms
3842 (the equal sign is optional)
3843 @end ifclear
3844 (@pxref{The Configuration Pragmas Files}).
3845
3846 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3847 @cindex @option{-gnateD} (@command{gcc})
3848 Defines a symbol, associated with value, for preprocessing.
3849 (@pxref{Integrated Preprocessing}).
3850
3851 @item -gnatef
3852 @cindex @option{-gnatef} (@command{gcc})
3853 Display full source path name in brief error messages.
3854
3855 @item -gnatem=@var{path}
3856 @cindex @option{-gnatem} (@command{gcc})
3857 Specify a mapping file
3858 @ifclear vms
3859 (the equal sign is optional)
3860 @end ifclear
3861 (@pxref{Units to Sources Mapping Files}).
3862
3863 @item -gnatep=@var{file}
3864 @cindex @option{-gnatep} (@command{gcc})
3865 Specify a preprocessing data file
3866 @ifclear vms
3867 (the equal sign is optional)
3868 @end ifclear
3869 (@pxref{Integrated Preprocessing}).
3870
3871 @item -gnatE
3872 @cindex @option{-gnatE} (@command{gcc})
3873 Full dynamic elaboration checks.
3874
3875 @item -gnatf
3876 @cindex @option{-gnatf} (@command{gcc})
3877 Full errors. Multiple errors per line, all undefined references, do not
3878 attempt to suppress cascaded errors.
3879
3880 @item -gnatF
3881 @cindex @option{-gnatF} (@command{gcc})
3882 Externals names are folded to all uppercase.
3883
3884 @item ^-gnatg^/GNAT_INTERNAL^
3885 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
3886 Internal GNAT implementation mode. This should not be used for
3887 applications programs, it is intended only for use by the compiler
3888 and its run-time library. For documentation, see the GNAT sources.
3889 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
3890 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
3891 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
3892 so that all standard warnings and all standard style options are turned on.
3893 All warnings and style error messages are treated as errors.
3894
3895 @item -gnatG
3896 @cindex @option{-gnatG} (@command{gcc})
3897 List generated expanded code in source form.
3898
3899 @item ^-gnath^/HELP^
3900 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3901 Output usage information. The output is written to @file{stdout}.
3902
3903 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3904 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3905 Identifier character set
3906 @ifclear vms
3907 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3908 @end ifclear
3909 For details of the possible selections for @var{c},
3910 see @ref{Character Set Control}.
3911
3912 @item ^-gnatI^/IGNORE_REP_CLAUSES^
3913 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
3914 Ignore representation clauses. When this switch is used, all
3915 representation clauses are treated as comments. This is useful
3916 when initially porting code where you want to ignore rep clause
3917 problems, and also for compiling foreign code (particularly
3918 for use with ASIS).
3919
3920 @item -gnatjnn
3921 @cindex @option{-gnatjnn} (@command{gcc})
3922 Reformat error messages to fit on nn character lines
3923
3924 @item -gnatk=@var{n}
3925 @cindex @option{-gnatk} (@command{gcc})
3926 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3927
3928 @item -gnatl
3929 @cindex @option{-gnatl} (@command{gcc})
3930 Output full source listing with embedded error messages.
3931
3932 @item -gnatL
3933 @cindex @option{-gnatL} (@command{gcc})
3934 Used in conjunction with -gnatG or -gnatD to intersperse original
3935 source lines (as comment lines with line numbers) in the expanded
3936 source output.
3937
3938 @item -gnatm=@var{n}
3939 @cindex @option{-gnatm} (@command{gcc})
3940 Limit number of detected error or warning messages to @var{n}
3941 where @var{n} is in the range 1..999_999. The default setting if
3942 no switch is given is 9999. Compilation is terminated if this
3943 limit is exceeded. The equal sign here is optional.
3944
3945 @item -gnatn
3946 @cindex @option{-gnatn} (@command{gcc})
3947 Activate inlining for subprograms for which
3948 pragma @code{inline} is specified. This inlining is performed
3949 by the GCC back-end.
3950
3951 @item -gnatN
3952 @cindex @option{-gnatN} (@command{gcc})
3953 Activate front end inlining for subprograms for which
3954 pragma @code{Inline} is specified. This inlining is performed
3955 by the front end and will be visible in the
3956 @option{-gnatG} output.
3957 In some cases, this has proved more effective than the back end
3958 inlining resulting from the use of
3959 @option{-gnatn}.
3960 Note that
3961 @option{-gnatN} automatically implies
3962 @option{-gnatn} so it is not necessary
3963 to specify both options. There are a few cases that the back-end inlining
3964 catches that cannot be dealt with in the front-end.
3965
3966 @item -gnato
3967 @cindex @option{-gnato} (@command{gcc})
3968 Enable numeric overflow checking (which is not normally enabled by
3969 default). Not that division by zero is a separate check that is not
3970 controlled by this switch (division by zero checking is on by default).
3971
3972 @item -gnatp
3973 @cindex @option{-gnatp} (@command{gcc})
3974 Suppress all checks.
3975
3976 @item -gnatP
3977 @cindex @option{-gnatP} (@command{gcc})
3978 Enable polling. This is required on some systems (notably Windows NT) to
3979 obtain asynchronous abort and asynchronous transfer of control capability.
3980 See the description of pragma Polling in the GNAT Reference Manual for
3981 full details.
3982
3983 @item -gnatq
3984 @cindex @option{-gnatq} (@command{gcc})
3985 Don't quit; try semantics, even if parse errors.
3986
3987 @item -gnatQ
3988 @cindex @option{-gnatQ} (@command{gcc})
3989 Don't quit; generate @file{ALI} and tree files even if illegalities.
3990
3991 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3992 @cindex @option{-gnatR} (@command{gcc})
3993 Output representation information for declared types and objects.
3994
3995 @item -gnats
3996 @cindex @option{-gnats} (@command{gcc})
3997 Syntax check only.
3998
3999 @item -gnatS
4000 @cindex @option{-gnatS} (@command{gcc})
4001 Print package Standard.
4002
4003 @item -gnatt
4004 @cindex @option{-gnatt} (@command{gcc})
4005 Generate tree output file.
4006
4007 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4008 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4009 All compiler tables start at @var{nnn} times usual starting size.
4010
4011 @item -gnatu
4012 @cindex @option{-gnatu} (@command{gcc})
4013 List units for this compilation.
4014
4015 @item -gnatU
4016 @cindex @option{-gnatU} (@command{gcc})
4017 Tag all error messages with the unique string ``error:''
4018
4019 @item -gnatv
4020 @cindex @option{-gnatv} (@command{gcc})
4021 Verbose mode. Full error output with source lines to @file{stdout}.
4022
4023 @item -gnatV
4024 @cindex @option{-gnatV} (@command{gcc})
4025 Control level of validity checking. See separate section describing
4026 this feature.
4027
4028 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
4029 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4030 Warning mode where
4031 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4032 the exact warnings that
4033 are enabled or disabled (@pxref{Warning Message Control}).
4034
4035 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4036 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4037 Wide character encoding method
4038 @ifclear vms
4039 (@var{e}=n/h/u/s/e/8).
4040 @end ifclear
4041 @ifset vms
4042 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4043 @end ifset
4044
4045 @item -gnatx
4046 @cindex @option{-gnatx} (@command{gcc})
4047 Suppress generation of cross-reference information.
4048
4049 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
4050 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4051 Enable built-in style checks (@pxref{Style Checking}).
4052
4053 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4054 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4055 Distribution stub generation and compilation
4056 @ifclear vms
4057 (@var{m}=r/c for receiver/caller stubs).
4058 @end ifclear
4059 @ifset vms
4060 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4061 to be generated and compiled).
4062 @end ifset
4063
4064 @item ^-I^/SEARCH=^@var{dir}
4065 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4066 @cindex RTL
4067 Direct GNAT to search the @var{dir} directory for source files needed by
4068 the current compilation
4069 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4070
4071 @item ^-I-^/NOCURRENT_DIRECTORY^
4072 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4073 @cindex RTL
4074 Except for the source file named in the command line, do not look for source
4075 files in the directory containing the source file named in the command line
4076 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4077
4078 @ifclear vms
4079 @item -mbig-switch
4080 @cindex @option{-mbig-switch} (@command{gcc})
4081 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4082 This standard gcc switch causes the compiler to use larger offsets in its
4083 jump table representation for @code{case} statements.
4084 This may result in less efficient code, but is sometimes necessary
4085 (for example on HP-UX targets)
4086 @cindex HP-UX and @option{-mbig-switch} option
4087 in order to compile large and/or nested @code{case} statements.
4088
4089 @item -o @var{file}
4090 @cindex @option{-o} (@command{gcc})
4091 This switch is used in @command{gcc} to redirect the generated object file
4092 and its associated ALI file. Beware of this switch with GNAT, because it may
4093 cause the object file and ALI file to have different names which in turn
4094 may confuse the binder and the linker.
4095 @end ifclear
4096
4097 @item -nostdinc
4098 @cindex @option{-nostdinc} (@command{gcc})
4099 Inhibit the search of the default location for the GNAT Run Time
4100 Library (RTL) source files.
4101
4102 @item -nostdlib
4103 @cindex @option{-nostdlib} (@command{gcc})
4104 Inhibit the search of the default location for the GNAT Run Time
4105 Library (RTL) ALI files.
4106
4107 @ifclear vms
4108 @item -O[@var{n}]
4109 @cindex @option{-O} (@command{gcc})
4110 @var{n} controls the optimization level.
4111
4112 @table @asis
4113 @item n = 0
4114 No optimization, the default setting if no @option{-O} appears
4115
4116 @item n = 1
4117 Normal optimization, the default if you specify @option{-O} without
4118 an operand. A good compromise between code quality and compilation
4119 time.
4120
4121 @item n = 2
4122 Extensive optimization, may improve execution time, possibly at the cost of
4123 substantially increased compilation time.
4124
4125 @item n = 3
4126 Same as @option{-O2}, and also includes inline expansion for small subprograms
4127 in the same unit.
4128
4129 @item n = s
4130 Optimize space usage
4131 @end table
4132
4133 @noindent
4134 See also @ref{Optimization Levels}.
4135 @end ifclear
4136
4137 @ifset vms
4138 @item  /NOOPTIMIZE
4139 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4140 Equivalent to @option{/OPTIMIZE=NONE}.
4141 This is the default behavior in the absence of an @option{/OPTIMIZE}
4142 qualifier.
4143
4144 @item /OPTIMIZE[=(keyword[,...])]
4145 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4146 Selects the level of optimization for your program. The supported
4147 keywords are as follows:
4148 @table @code
4149 @item   ALL
4150 Perform most optimizations, including those that
4151 are expensive.
4152 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4153 without keyword options.
4154
4155 @item   NONE
4156 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4157
4158 @item SOME
4159 Perform some optimizations, but omit ones that are costly.
4160
4161 @item   DEVELOPMENT
4162 Same as @code{SOME}.
4163
4164 @item INLINING
4165 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4166 automatic inlining of small subprograms within a unit
4167
4168 @item   UNROLL_LOOPS
4169 Try to unroll loops. This keyword may be specified together with
4170 any keyword above other than @code{NONE}. Loop unrolling
4171 usually, but not always, improves the performance of programs.
4172
4173 @item SPACE
4174 Optimize space usage
4175 @end table
4176
4177 @noindent
4178 See also @ref{Optimization Levels}.
4179 @end ifset
4180
4181 @ifclear vms
4182 @item -pass-exit-codes
4183 @cindex @option{-pass-exit-codes} (@command{gcc})
4184 Catch exit codes from the compiler and use the most meaningful as
4185 exit status.
4186 @end ifclear
4187
4188 @item --RTS=@var{rts-path}
4189 @cindex @option{--RTS} (@command{gcc})
4190 Specifies the default location of the runtime library. Same meaning as the
4191 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4192
4193 @item ^-S^/ASM^
4194 @cindex @option{^-S^/ASM^} (@command{gcc})
4195 ^Used in place of @option{-c} to^Used to^
4196 cause the assembler source file to be
4197 generated, using @file{^.s^.S^} as the extension,
4198 instead of the object file.
4199 This may be useful if you need to examine the generated assembly code.
4200
4201 @item ^-fverbose-asm^/VERBOSE_ASM^
4202 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4203 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4204 to cause the generated assembly code file to be annotated with variable
4205 names, making it significantly easier to follow.
4206
4207 @item ^-v^/VERBOSE^
4208 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4209 Show commands generated by the @command{gcc} driver. Normally used only for
4210 debugging purposes or if you need to be sure what version of the
4211 compiler you are executing.
4212
4213 @ifclear vms
4214 @item -V @var{ver}
4215 @cindex @option{-V} (@command{gcc})
4216 Execute @var{ver} version of the compiler. This is the @command{gcc}
4217 version, not the GNAT version.
4218 @end ifclear
4219
4220 @item ^-w^/NO_BACK_END_WARNINGS^
4221 @cindex @option{-w} (@command{gcc})
4222 Turn off warnings generated by the back end of the compiler. Use of
4223 this switch also causes the default for front end warnings to be set
4224 to suppress (as though @option{-gnatws} had appeared at the start of
4225 the options.
4226
4227 @end table
4228
4229 @ifclear vms
4230 @c Combining qualifiers does not work on VMS
4231 You may combine a sequence of GNAT switches into a single switch. For
4232 example, the combined switch
4233
4234 @cindex Combining GNAT switches
4235 @smallexample
4236 -gnatofi3
4237 @end smallexample
4238
4239 @noindent
4240 is equivalent to specifying the following sequence of switches:
4241
4242 @smallexample
4243 -gnato -gnatf -gnati3
4244 @end smallexample
4245 @end ifclear
4246
4247 @noindent
4248 The following restrictions apply to the combination of switches
4249 in this manner:
4250
4251 @itemize @bullet
4252 @item
4253 The switch @option{-gnatc} if combined with other switches must come
4254 first in the string.
4255
4256 @item
4257 The switch @option{-gnats} if combined with other switches must come
4258 first in the string.
4259
4260 @item
4261 The switches
4262 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4263 may not be combined with any other switches.
4264
4265 @ifclear vms
4266 @item
4267 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4268 switch), then all further characters in the switch are interpreted
4269 as style modifiers (see description of @option{-gnaty}).
4270
4271 @item
4272 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4273 switch), then all further characters in the switch are interpreted
4274 as debug flags (see description of @option{-gnatd}).
4275
4276 @item
4277 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4278 switch), then all further characters in the switch are interpreted
4279 as warning mode modifiers (see description of @option{-gnatw}).
4280
4281 @item
4282 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4283 switch), then all further characters in the switch are interpreted
4284 as validity checking options (see description of @option{-gnatV}).
4285 @end ifclear
4286 @end itemize
4287
4288 @node Output and Error Message Control
4289 @subsection Output and Error Message Control
4290 @findex stderr
4291
4292 @noindent
4293 The standard default format for error messages is called ``brief format''.
4294 Brief format messages are written to @file{stderr} (the standard error
4295 file) and have the following form:
4296
4297 @smallexample
4298 e.adb:3:04: Incorrect spelling of keyword "function"
4299 e.adb:4:20: ";" should be "is"
4300 @end smallexample
4301
4302 @noindent
4303 The first integer after the file name is the line number in the file,
4304 and the second integer is the column number within the line.
4305 @ifclear vms
4306 @code{GPS} can parse the error messages
4307 and point to the referenced character.
4308 @end ifclear
4309 The following switches provide control over the error message
4310 format:
4311
4312 @table @option
4313 @c !sort!
4314 @item -gnatv
4315 @cindex @option{-gnatv} (@command{gcc})
4316 @findex stdout
4317 @ifclear vms
4318 The v stands for verbose.
4319 @end ifclear
4320 The effect of this setting is to write long-format error
4321 messages to @file{stdout} (the standard output file.
4322 The same program compiled with the
4323 @option{-gnatv} switch would generate:
4324
4325 @smallexample
4326 @cartouche
4327 3. funcion X (Q : Integer)
4328    |
4329 >>> Incorrect spelling of keyword "function"
4330 4. return Integer;
4331                  |
4332 >>> ";" should be "is"
4333 @end cartouche
4334 @end smallexample
4335
4336 @noindent
4337 The vertical bar indicates the location of the error, and the @samp{>>>}
4338 prefix can be used to search for error messages. When this switch is
4339 used the only source lines output are those with errors.
4340
4341 @item -gnatl
4342 @cindex @option{-gnatl} (@command{gcc})
4343 @ifclear vms
4344 The @code{l} stands for list.
4345 @end ifclear
4346 This switch causes a full listing of
4347 the file to be generated. In the case where a body is
4348 compiled, the corresponding spec is also listed, along
4349 with any subunits. Typical output from compiling a package
4350 body @file{p.adb} might look like:
4351
4352 @smallexample @c ada
4353 @cartouche
4354  Compiling: p.adb
4355
4356      1. package body p is
4357      2.    procedure a;
4358      3.    procedure a is separate;
4359      4. begin
4360      5.    null
4361                |
4362         >>> missing ";"
4363
4364      6. end;
4365
4366 Compiling: p.ads
4367
4368      1. package p is
4369      2.    pragma Elaborate_Body
4370                                 |
4371         >>> missing ";"
4372
4373      3. end p;
4374
4375 Compiling: p-a.adb
4376
4377      1. separate p
4378                 |
4379         >>> missing "("
4380
4381      2. procedure a is
4382      3. begin
4383      4.    null
4384                |
4385         >>> missing ";"
4386
4387      5. end;
4388 @end cartouche
4389 @end smallexample
4390
4391 @noindent
4392 @findex stderr
4393 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4394 standard output is redirected, a brief summary is written to
4395 @file{stderr} (standard error) giving the number of error messages and
4396 warning messages generated.
4397
4398 @item -^gnatl^OUTPUT_FILE^=file
4399 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4400 This has the same effect as @code{-gnatl} except that the output is
4401 written to a file instead of to standard output. If the given name
4402 @file{fname} does not start with a period, then it is the full name
4403 of the file to be written. If @file{fname} is an extension, it is
4404 appended to the name of the file being compiled. For example, if
4405 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4406 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4407
4408 @item -gnatU
4409 @cindex @option{-gnatU} (@command{gcc})
4410 This switch forces all error messages to be preceded by the unique
4411 string ``error:''. This means that error messages take a few more
4412 characters in space, but allows easy searching for and identification
4413 of error messages.
4414
4415 @item -gnatb
4416 @cindex @option{-gnatb} (@command{gcc})
4417 @ifclear vms
4418 The @code{b} stands for brief.
4419 @end ifclear
4420 This switch causes GNAT to generate the
4421 brief format error messages to @file{stderr} (the standard error
4422 file) as well as the verbose
4423 format message or full listing (which as usual is written to
4424 @file{stdout} (the standard output file).
4425
4426 @item -gnatm=@var{n}
4427 @cindex @option{-gnatm} (@command{gcc})
4428 @ifclear vms
4429 The @code{m} stands for maximum.
4430 @end ifclear
4431 @var{n} is a decimal integer in the
4432 range of 1 to 999 and limits the number of error messages to be
4433 generated. For example, using @option{-gnatm2} might yield
4434
4435 @smallexample
4436 e.adb:3:04: Incorrect spelling of keyword "function"
4437 e.adb:5:35: missing ".."
4438 fatal error: maximum errors reached
4439 compilation abandoned
4440 @end smallexample
4441
4442 @noindent
4443 Note that the equal sign is optional, so the switches
4444 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4445
4446 @item -gnatf
4447 @cindex @option{-gnatf} (@command{gcc})
4448 @cindex Error messages, suppressing
4449 @ifclear vms
4450 The @code{f} stands for full.
4451 @end ifclear
4452 Normally, the compiler suppresses error messages that are likely to be
4453 redundant. This switch causes all error
4454 messages to be generated. In particular, in the case of
4455 references to undefined variables. If a given variable is referenced
4456 several times, the normal format of messages is
4457 @smallexample
4458 e.adb:7:07: "V" is undefined (more references follow)
4459 @end smallexample
4460
4461 @noindent
4462 where the parenthetical comment warns that there are additional
4463 references to the variable @code{V}. Compiling the same program with the
4464 @option{-gnatf} switch yields
4465
4466 @smallexample
4467 e.adb:7:07: "V" is undefined
4468 e.adb:8:07: "V" is undefined
4469 e.adb:8:12: "V" is undefined
4470 e.adb:8:16: "V" is undefined
4471 e.adb:9:07: "V" is undefined
4472 e.adb:9:12: "V" is undefined
4473 @end smallexample
4474
4475 @noindent
4476 The @option{-gnatf} switch also generates additional information for
4477 some error messages.  Some examples are:
4478
4479 @itemize @bullet
4480 @item
4481 Full details on entities not available in high integrity mode
4482 @item
4483 Details on possibly non-portable unchecked conversion
4484 @item
4485 List possible interpretations for ambiguous calls
4486 @item
4487 Additional details on incorrect parameters
4488 @end itemize
4489
4490 @item -gnatjnn
4491 @cindex @option{-gnatjnn} (@command{gcc})
4492 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4493 with continuation lines are treated as though the continuation lines were
4494 separate messages (and so a warning with two continuation lines counts as
4495 three warnings, and is listed as three separate messages).
4496
4497 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4498 messages are output in a different manner. A message and all its continuation
4499 lines are treated as a unit, and count as only one warning or message in the
4500 statistics totals. Furthermore, the message is reformatted so that no line
4501 is longer than nn characters.
4502
4503 @item -gnatq
4504 @cindex @option{-gnatq} (@command{gcc})
4505 @ifclear vms
4506 The @code{q} stands for quit (really ``don't quit'').
4507 @end ifclear
4508 In normal operation mode, the compiler first parses the program and
4509 determines if there are any syntax errors. If there are, appropriate
4510 error messages are generated and compilation is immediately terminated.
4511 This switch tells
4512 GNAT to continue with semantic analysis even if syntax errors have been
4513 found. This may enable the detection of more errors in a single run. On
4514 the other hand, the semantic analyzer is more likely to encounter some
4515 internal fatal error when given a syntactically invalid tree.
4516
4517 @item -gnatQ
4518 @cindex @option{-gnatQ} (@command{gcc})
4519 In normal operation mode, the @file{ALI} file is not generated if any
4520 illegalities are detected in the program. The use of @option{-gnatQ} forces
4521 generation of the @file{ALI} file. This file is marked as being in
4522 error, so it cannot be used for binding purposes, but it does contain
4523 reasonably complete cross-reference information, and thus may be useful
4524 for use by tools (e.g. semantic browsing tools or integrated development
4525 environments) that are driven from the @file{ALI} file. This switch
4526 implies @option{-gnatq}, since the semantic phase must be run to get a
4527 meaningful ALI file.
4528
4529 In addition, if @option{-gnatt} is also specified, then the tree file is
4530 generated even if there are illegalities. It may be useful in this case
4531 to also specify @option{-gnatq} to ensure that full semantic processing
4532 occurs. The resulting tree file can be processed by ASIS, for the purpose
4533 of providing partial information about illegal units, but if the error
4534 causes the tree to be badly malformed, then ASIS may crash during the
4535 analysis.
4536
4537 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4538 being in error, @command{gnatmake} will attempt to recompile the source when it
4539 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4540
4541 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4542 since ALI files are never generated if @option{-gnats} is set.
4543
4544 @end table
4545
4546 @node Warning Message Control
4547 @subsection Warning Message Control
4548 @cindex Warning messages
4549 @noindent
4550 In addition to error messages, which correspond to illegalities as defined
4551 in the Ada Reference Manual, the compiler detects two kinds of warning
4552 situations.
4553
4554 First, the compiler considers some constructs suspicious and generates a
4555 warning message to alert you to a possible error. Second, if the
4556 compiler detects a situation that is sure to raise an exception at
4557 run time, it generates a warning message. The following shows an example
4558 of warning messages:
4559 @smallexample
4560 e.adb:4:24: warning: creation of object may raise Storage_Error
4561 e.adb:10:17: warning: static value out of range
4562 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4563 @end smallexample
4564
4565 @noindent
4566 GNAT considers a large number of situations as appropriate
4567 for the generation of warning messages. As always, warnings are not
4568 definite indications of errors. For example, if you do an out-of-range
4569 assignment with the deliberate intention of raising a
4570 @code{Constraint_Error} exception, then the warning that may be
4571 issued does not indicate an error. Some of the situations for which GNAT
4572 issues warnings (at least some of the time) are given in the following
4573 list. This list is not complete, and new warnings are often added to
4574 subsequent versions of GNAT. The list is intended to give a general idea
4575 of the kinds of warnings that are generated.
4576
4577 @itemize @bullet
4578 @item
4579 Possible infinitely recursive calls
4580
4581 @item
4582 Out-of-range values being assigned
4583
4584 @item
4585 Possible order of elaboration problems
4586
4587 @item
4588 Assertions (pragma Assert) that are sure to fail
4589
4590 @item
4591 Unreachable code
4592
4593 @item
4594 Address clauses with possibly unaligned values, or where an attempt is
4595 made to overlay a smaller variable with a larger one.
4596
4597 @item
4598 Fixed-point type declarations with a null range
4599
4600 @item
4601 Direct_IO or Sequential_IO instantiated with a type that has access values
4602
4603 @item
4604 Variables that are never assigned a value
4605
4606 @item
4607 Variables that are referenced before being initialized
4608
4609 @item
4610 Task entries with no corresponding @code{accept} statement
4611
4612 @item
4613 Duplicate accepts for the same task entry in a @code{select}
4614
4615 @item
4616 Objects that take too much storage
4617
4618 @item
4619 Unchecked conversion between types of differing sizes
4620
4621 @item
4622 Missing @code{return} statement along some execution path in a function
4623
4624 @item
4625 Incorrect (unrecognized) pragmas
4626
4627 @item
4628 Incorrect external names
4629
4630 @item
4631 Allocation from empty storage pool
4632
4633 @item
4634 Potentially blocking operation in protected type
4635
4636 @item
4637 Suspicious parenthesization of expressions
4638
4639 @item
4640 Mismatching bounds in an aggregate
4641
4642 @item
4643 Attempt to return local value by reference
4644
4645 @item
4646 Premature instantiation of a generic body
4647
4648 @item
4649 Attempt to pack aliased components
4650
4651 @item
4652 Out of bounds array subscripts
4653
4654 @item
4655 Wrong length on string assignment
4656
4657 @item
4658 Violations of style rules if style checking is enabled
4659
4660 @item
4661 Unused @code{with} clauses
4662
4663 @item
4664 @code{Bit_Order} usage that does not have any effect
4665
4666 @item
4667 @code{Standard.Duration} used to resolve universal fixed expression
4668
4669 @item
4670 Dereference of possibly null value
4671
4672 @item
4673 Declaration that is likely to cause storage error
4674
4675 @item
4676 Internal GNAT unit @code{with}'ed by application unit
4677
4678 @item
4679 Values known to be out of range at compile time
4680
4681 @item
4682 Unreferenced labels and variables
4683
4684 @item
4685 Address overlays that could clobber memory
4686
4687 @item
4688 Unexpected initialization when address clause present
4689
4690 @item
4691 Bad alignment for address clause
4692
4693 @item
4694 Useless type conversions
4695
4696 @item
4697 Redundant assignment statements and other redundant constructs
4698
4699 @item
4700 Useless exception handlers
4701
4702 @item
4703 Accidental hiding of name by child unit
4704
4705 @item
4706 Access before elaboration detected at compile time
4707
4708 @item
4709 A range in a @code{for} loop that is known to be null or might be null
4710
4711 @end itemize
4712
4713 @noindent
4714 The following section lists compiler switches that are available
4715 to control the handling of warning messages. It is also possible
4716 to exercise much finer control over what warnings are issued and
4717 suppressed using the GNAT pragma Warnings, which is documented
4718 in the GNAT Reference manual.
4719
4720 @table @option
4721 @c !sort!
4722 @item -gnatwa
4723 @emph{Activate all optional errors.}
4724 @cindex @option{-gnatwa} (@command{gcc})
4725 This switch activates most optional warning messages, see remaining list
4726 in this section for details on optional warning messages that can be
4727 individually controlled.  The warnings that are not turned on by this
4728 switch are
4729 @option{-gnatwd} (implicit dereferencing),
4730 @option{-gnatwh} (hiding),
4731 @option{-gnatwl} (elaboration warnings),
4732 @option{-gnatw.o} (warn on values set by out parameters ignored)
4733 and @option{-gnatwt} (tracking of deleted conditional code).
4734 All other optional warnings are turned on.
4735
4736 @item -gnatwA
4737 @emph{Suppress all optional errors.}
4738 @cindex @option{-gnatwA} (@command{gcc})
4739 This switch suppresses all optional warning messages, see remaining list
4740 in this section for details on optional warning messages that can be
4741 individually controlled.
4742
4743 @item -gnatw.a
4744 @emph{Activate warnings on failing assertions.}
4745 @cindex @option{-gnatw.a} (@command{gcc})
4746 @cindex Assert failures
4747 This switch activates warnings for assertions where the compiler can tell at
4748 compile time that the assertion will fail. Note that this warning is given
4749 even if assertions are disabled. The default is that such warnings are
4750 generated.
4751
4752 @item -gnatw.A
4753 @emph{Suppress warnings on failing assertions.}
4754 @cindex @option{-gnatw.A} (@command{gcc})
4755 @cindex Assert failures
4756 This switch suppresses warnings for assertions where the compiler can tell at
4757 compile time that the assertion will fail.
4758
4759 @item -gnatwb
4760 @emph{Activate warnings on bad fixed values.}
4761 @cindex @option{-gnatwb} (@command{gcc})
4762 @cindex Bad fixed values
4763 @cindex Fixed-point Small value
4764 @cindex Small value
4765 This switch activates warnings for static fixed-point expressions whose
4766 value is not an exact multiple of Small. Such values are implementation
4767 dependent, since an implementation is free to choose either of the multiples
4768 that surround the value. GNAT always chooses the closer one, but this is not
4769 required behavior, and it is better to specify a value that is an exact
4770 multiple, ensuring predictable execution. The default is that such warnings
4771 are not generated.
4772
4773 @item -gnatwB
4774 @emph{Suppress warnings on bad fixed values.}
4775 @cindex @option{-gnatwB} (@command{gcc})
4776 This switch suppresses warnings for static fixed-point expressions whose
4777 value is not an exact multiple of Small.
4778
4779 @item -gnatwc
4780 @emph{Activate warnings on conditionals.}
4781 @cindex @option{-gnatwc} (@command{gcc})
4782 @cindex Conditionals, constant
4783 This switch activates warnings for conditional expressions used in
4784 tests that are known to be True or False at compile time. The default
4785 is that such warnings are not generated.
4786 Note that this warning does
4787 not get issued for the use of boolean variables or constants whose
4788 values are known at compile time, since this is a standard technique
4789 for conditional compilation in Ada, and this would generate too many
4790 false positive warnings.
4791
4792 This warning option also activates a special test for comparisons using
4793 the operators ``>='' and`` <=''.
4794 If the compiler can tell that only the equality condition is possible,
4795 then it will warn that the ``>'' or ``<'' part of the test
4796 is useless and that the operator could be replaced by ``=''.
4797 An example would be comparing a @code{Natural} variable <= 0.
4798
4799 This warning option also generates warnings if
4800 one or both tests is optimized away in a membership test for integer
4801 values if the result can be determined at compile time. Range tests on
4802 enumeration types are not included, since it is common for such tests
4803 to include an end point.
4804
4805 This warning can also be turned on using @option{-gnatwa}.
4806
4807 @item -gnatwC
4808 @emph{Suppress warnings on conditionals.}
4809 @cindex @option{-gnatwC} (@command{gcc})
4810 This switch suppresses warnings for conditional expressions used in
4811 tests that are known to be True or False at compile time.
4812
4813 @item -gnatw.c
4814 @emph{Activate warnings on missing component clauses.}
4815 @cindex @option{-gnatw.c} (@command{gcc})
4816 @cindex Component clause, missing
4817 This switch activates warnings for record components where a record
4818 representation clause is present and has component clauses for the
4819 majority, but not all, of the components. A warning is given for each
4820 component for which no component clause is present.
4821
4822 This warning can also be turned on using @option{-gnatwa}.
4823
4824 @item -gnatw.C
4825 @emph{Suppress warnings on missing component clauses.}
4826 @cindex @option{-gnatwC} (@command{gcc})
4827 This switch suppresses warnings for record components that are
4828 missing a component clause in the situation described above.
4829
4830 @item -gnatwd
4831 @emph{Activate warnings on implicit dereferencing.}
4832 @cindex @option{-gnatwd} (@command{gcc})
4833 If this switch is set, then the use of a prefix of an access type
4834 in an indexed component, slice, or selected component without an
4835 explicit @code{.all} will generate a warning. With this warning
4836 enabled, access checks occur only at points where an explicit
4837 @code{.all} appears in the source code (assuming no warnings are
4838 generated as a result of this switch). The default is that such
4839 warnings are not generated.
4840 Note that @option{-gnatwa} does not affect the setting of
4841 this warning option.
4842
4843 @item -gnatwD
4844 @emph{Suppress warnings on implicit dereferencing.}
4845 @cindex @option{-gnatwD} (@command{gcc})
4846 @cindex Implicit dereferencing
4847 @cindex Dereferencing, implicit
4848 This switch suppresses warnings for implicit dereferences in
4849 indexed components, slices, and selected components.
4850
4851 @item -gnatwe
4852 @emph{Treat warnings as errors.}
4853 @cindex @option{-gnatwe} (@command{gcc})
4854 @cindex Warnings, treat as error
4855 This switch causes warning messages to be treated as errors.
4856 The warning string still appears, but the warning messages are counted
4857 as errors, and prevent the generation of an object file.
4858
4859 @item -gnatwf
4860 @emph{Activate warnings on unreferenced formals.}
4861 @cindex @option{-gnatwf} (@command{gcc})
4862 @cindex Formals, unreferenced
4863 This switch causes a warning to be generated if a formal parameter
4864 is not referenced in the body of the subprogram. This warning can
4865 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
4866 default is that these warnings are not generated.
4867
4868 @item -gnatwF
4869 @emph{Suppress warnings on unreferenced formals.}
4870 @cindex @option{-gnatwF} (@command{gcc})
4871 This switch suppresses warnings for unreferenced formal
4872 parameters. Note that the
4873 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4874 effect of warning on unreferenced entities other than subprogram
4875 formals.
4876
4877 @item -gnatwg
4878 @emph{Activate warnings on unrecognized pragmas.}
4879 @cindex @option{-gnatwg} (@command{gcc})
4880 @cindex Pragmas, unrecognized
4881 This switch causes a warning to be generated if an unrecognized
4882 pragma is encountered. Apart from issuing this warning, the
4883 pragma is ignored and has no effect. This warning can
4884 also be turned on using @option{-gnatwa}. The default
4885 is that such warnings are issued (satisfying the Ada Reference
4886 Manual requirement that such warnings appear).
4887
4888 @item -gnatwG
4889 @emph{Suppress warnings on unrecognized pragmas.}
4890 @cindex @option{-gnatwG} (@command{gcc})
4891 This switch suppresses warnings for unrecognized pragmas.
4892
4893 @item -gnatwh
4894 @emph{Activate warnings on hiding.}
4895 @cindex @option{-gnatwh} (@command{gcc})
4896 @cindex Hiding of Declarations
4897 This switch activates warnings on hiding declarations.
4898 A declaration is considered hiding
4899 if it is for a non-overloadable entity, and it declares an entity with the
4900 same name as some other entity that is directly or use-visible. The default
4901 is that such warnings are not generated.
4902 Note that @option{-gnatwa} does not affect the setting of this warning option.
4903
4904 @item -gnatwH
4905 @emph{Suppress warnings on hiding.}
4906 @cindex @option{-gnatwH} (@command{gcc})
4907 This switch suppresses warnings on hiding declarations.
4908
4909 @item -gnatwi
4910 @emph{Activate warnings on implementation units.}
4911 @cindex @option{-gnatwi} (@command{gcc})
4912 This switch activates warnings for a @code{with} of an internal GNAT
4913 implementation unit, defined as any unit from the @code{Ada},
4914 @code{Interfaces}, @code{GNAT},
4915 ^^@code{DEC},^ or @code{System}
4916 hierarchies that is not
4917 documented in either the Ada Reference Manual or the GNAT
4918 Programmer's Reference Manual. Such units are intended only
4919 for internal implementation purposes and should not be @code{with}'ed
4920 by user programs. The default is that such warnings are generated
4921 This warning can also be turned on using @option{-gnatwa}.
4922
4923 @item -gnatwI
4924 @emph{Disable warnings on implementation units.}
4925 @cindex @option{-gnatwI} (@command{gcc})
4926 This switch disables warnings for a @code{with} of an internal GNAT
4927 implementation unit.
4928
4929 @item -gnatwj
4930 @emph{Activate warnings on obsolescent features (Annex J).}
4931 @cindex @option{-gnatwj} (@command{gcc})
4932 @cindex Features, obsolescent
4933 @cindex Obsolescent features
4934 If this warning option is activated, then warnings are generated for
4935 calls to subprograms marked with @code{pragma Obsolescent} and
4936 for use of features in Annex J of the Ada Reference Manual. In the
4937 case of Annex J, not all features are flagged. In particular use
4938 of the renamed packages (like @code{Text_IO}) and use of package
4939 @code{ASCII} are not flagged, since these are very common and
4940 would generate many annoying positive warnings. The default is that
4941 such warnings are not generated. This warning is also turned on by
4942 the use of @option{-gnatwa}.
4943
4944 In addition to the above cases, warnings are also generated for
4945 GNAT features that have been provided in past versions but which
4946 have been superseded (typically by features in the new Ada standard).
4947 For example, @code{pragma Ravenscar} will be flagged since its
4948 function is replaced by @code{pragma Profile(Ravenscar)}.
4949
4950 Note that this warning option functions differently from the
4951 restriction @code{No_Obsolescent_Features} in two respects.
4952 First, the restriction applies only to annex J features.
4953 Second, the restriction does flag uses of package @code{ASCII}.
4954
4955 @item -gnatwJ
4956 @emph{Suppress warnings on obsolescent features (Annex J).}
4957 @cindex @option{-gnatwJ} (@command{gcc})
4958 This switch disables warnings on use of obsolescent features.
4959
4960 @item -gnatwk
4961 @emph{Activate warnings on variables that could be constants.}
4962 @cindex @option{-gnatwk} (@command{gcc})
4963 This switch activates warnings for variables that are initialized but
4964 never modified, and then could be declared constants. The default is that
4965 such warnings are not given.
4966 This warning can also be turned on using @option{-gnatwa}.
4967
4968 @item -gnatwK
4969 @emph{Suppress warnings on variables that could be constants.}
4970 @cindex @option{-gnatwK} (@command{gcc})
4971 This switch disables warnings on variables that could be declared constants.
4972
4973 @item -gnatwl
4974 @emph{Activate warnings for missing elaboration pragmas.}
4975 @cindex @option{-gnatwl} (@command{gcc})
4976 @cindex Elaboration, warnings
4977 This switch activates warnings on missing
4978 @code{Elaborate_All} and @code{Elaborate} pragmas.
4979 See the section in this guide on elaboration checking for details on
4980 when such pragmas should be used. Warnings are also generated if you
4981 are using the static mode of elaboration, and a @code{pragma Elaborate}
4982 is encountered. The default is that such warnings
4983 are not generated.
4984 This warning is not automatically turned on by the use of @option{-gnatwa}.
4985
4986 @item -gnatwL
4987 @emph{Suppress warnings for missing elaboration pragmas.}
4988 @cindex @option{-gnatwL} (@command{gcc})
4989 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
4990 See the section in this guide on elaboration checking for details on
4991 when such pragmas should be used.
4992
4993 @item -gnatwm
4994 @emph{Activate warnings on modified but unreferenced variables.}
4995 @cindex @option{-gnatwm} (@command{gcc})
4996 This switch activates warnings for variables that are assigned (using
4997 an initialization value or with one or more assignment statements) but
4998 whose value is never read. The warning is suppressed for volatile
4999 variables and also for variables that are renamings of other variables
5000 or for which an address clause is given.
5001 This warning can also be turned on using @option{-gnatwa}.
5002 The default is that these warnings are not given.
5003
5004 @item -gnatwM
5005 @emph{Disable warnings on modified but unreferenced variables.}
5006 @cindex @option{-gnatwM} (@command{gcc})
5007 This switch disables warnings for variables that are assigned or
5008 initialized, but never read.
5009
5010 @item -gnatwn
5011 @emph{Set normal warnings mode.}
5012 @cindex @option{-gnatwn} (@command{gcc})
5013 This switch sets normal warning mode, in which enabled warnings are
5014 issued and treated as warnings rather than errors. This is the default
5015 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5016 an explicit @option{-gnatws} or
5017 @option{-gnatwe}. It also cancels the effect of the
5018 implicit @option{-gnatwe} that is activated by the
5019 use of @option{-gnatg}.
5020
5021 @item -gnatwo
5022 @emph{Activate warnings on address clause overlays.}
5023 @cindex @option{-gnatwo} (@command{gcc})
5024 @cindex Address Clauses, warnings
5025 This switch activates warnings for possibly unintended initialization
5026 effects of defining address clauses that cause one variable to overlap
5027 another. The default is that such warnings are generated.
5028 This warning can also be turned on using @option{-gnatwa}.
5029
5030 @item -gnatwO
5031 @emph{Suppress warnings on address clause overlays.}
5032 @cindex @option{-gnatwO} (@command{gcc})
5033 This switch suppresses warnings on possibly unintended initialization
5034 effects of defining address clauses that cause one variable to overlap
5035 another.
5036
5037 @item -gnatw.o
5038 @emph{Activate warnings on modified but unreferenced out parameters.}
5039 @cindex @option{-gnatw.o} (@command{gcc})
5040 This switch activates warnings for variables that are modified by using
5041 them as actuals for a call to a procedure with an out mode formal, where
5042 the resulting assigned value is never read.
5043 The warning is suppressed for volatile
5044 variables and also for variables that are renamings of other variables
5045 or for which an address clause is given.
5046 The default is that these warnings are not given. Note that this warning
5047 is not included in -gnatwa, it must be activated explicitly.
5048
5049 @item -gnatw.O
5050 @emph{Disable warnings on modified but unreferenced out parameters.}
5051 @cindex @option{-gnatw.O} (@command{gcc})
5052 This switch suppresses warnings for variables that are modified by using
5053 them as actuals for a call to a procedure with an out mode formal, where
5054 the resulting assigned value is never read.
5055
5056 @item -gnatwp
5057 @emph{Activate warnings on ineffective pragma Inlines.}
5058 @cindex @option{-gnatwp} (@command{gcc})
5059 @cindex Inlining, warnings
5060 This switch activates warnings for failure of front end inlining
5061 (activated by @option{-gnatN}) to inline a particular call. There are
5062 many reasons for not being able to inline a call, including most
5063 commonly that the call is too complex to inline. The default is
5064 that such warnings are not given.
5065 This warning can also be turned on using @option{-gnatwa}.
5066 Warnings on ineffective inlining by the gcc back-end can be activated
5067 separately, using the gcc switch -Winline.
5068
5069 @item -gnatwP
5070 @emph{Suppress warnings on ineffective pragma Inlines.}
5071 @cindex @option{-gnatwP} (@command{gcc})
5072 This switch suppresses warnings on ineffective pragma Inlines. If the
5073 inlining mechanism cannot inline a call, it will simply ignore the
5074 request silently.
5075
5076 @item -gnatwq
5077 @emph{Activate warnings on questionable missing parentheses.}
5078 @cindex @option{-gnatwq} (@command{gcc})
5079 @cindex Parentheses, warnings
5080 This switch activates warnings for cases where parentheses are not used and
5081 the result is potential ambiguity from a readers point of view. For example
5082 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5083 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5084 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5085 follow the rule of always parenthesizing to make the association clear, and
5086 this warning switch warns if such parentheses are not present. The default
5087 is that these warnings are given.
5088 This warning can also be turned on using @option{-gnatwa}.
5089
5090 @item -gnatwQ
5091 @emph{Suppress warnings on questionable missing parentheses.}
5092 @cindex @option{-gnatwQ} (@command{gcc})
5093 This switch suppresses warnings for cases where the association is not
5094 clear and the use of parentheses is preferred.
5095
5096 @item -gnatwr
5097 @emph{Activate warnings on redundant constructs.}
5098 @cindex @option{-gnatwr} (@command{gcc})
5099 This switch activates warnings for redundant constructs. The following
5100 is the current list of constructs regarded as redundant:
5101
5102 @itemize @bullet
5103 @item
5104 Assignment of an item to itself.
5105 @item
5106 Type conversion that converts an expression to its own type.
5107 @item
5108 Use of the attribute @code{Base} where @code{typ'Base} is the same
5109 as @code{typ}.
5110 @item
5111 Use of pragma @code{Pack} when all components are placed by a record
5112 representation clause.
5113 @item
5114 Exception handler containing only a reraise statement (raise with no
5115 operand) which has no effect.
5116 @item
5117 Use of the operator abs on an operand that is known at compile time
5118 to be non-negative
5119 @item
5120 Comparison of boolean expressions to an explicit True value.
5121 @end itemize
5122
5123 This warning can also be turned on using @option{-gnatwa}.
5124 The default is that warnings for redundant constructs are not given.
5125
5126 @item -gnatwR
5127 @emph{Suppress warnings on redundant constructs.}
5128 @cindex @option{-gnatwR} (@command{gcc})
5129 This switch suppresses warnings for redundant constructs.
5130
5131 @item -gnatws
5132 @emph{Suppress all warnings.}
5133 @cindex @option{-gnatws} (@command{gcc})
5134 This switch completely suppresses the
5135 output of all warning messages from the GNAT front end.
5136 Note that it does not suppress warnings from the @command{gcc} back end.
5137 To suppress these back end warnings as well, use the switch @option{-w}
5138 in addition to @option{-gnatws}.
5139
5140 @item -gnatwt
5141 @emph{Activate warnings for tracking of deleted conditional code.}
5142 @cindex @option{-gnatwt} (@command{gcc})
5143 @cindex Deactivated code, warnings
5144 @cindex Deleted code, warnings
5145 This switch activates warnings for tracking of code in conditionals (IF and
5146 CASE statements) that is detected to be dead code which cannot be executed, and
5147 which is removed by the front end. This warning is off by default, and is not
5148 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5149 useful for detecting deactivated code in certified applications.
5150
5151 @item -gnatwT
5152 @emph{Suppress warnings for tracking of deleted conditional code.}
5153 @cindex @option{-gnatwT} (@command{gcc})
5154 This switch suppresses warnings for tracking of deleted conditional code.
5155
5156 @item -gnatwu
5157 @emph{Activate warnings on unused entities.}
5158 @cindex @option{-gnatwu} (@command{gcc})
5159 This switch activates warnings to be generated for entities that
5160 are declared but not referenced, and for units that are @code{with}'ed
5161 and not
5162 referenced. In the case of packages, a warning is also generated if
5163 no entities in the package are referenced. This means that if the package
5164 is referenced but the only references are in @code{use}
5165 clauses or @code{renames}
5166 declarations, a warning is still generated. A warning is also generated
5167 for a generic package that is @code{with}'ed but never instantiated.
5168 In the case where a package or subprogram body is compiled, and there
5169 is a @code{with} on the corresponding spec
5170 that is only referenced in the body,
5171 a warning is also generated, noting that the
5172 @code{with} can be moved to the body. The default is that
5173 such warnings are not generated.
5174 This switch also activates warnings on unreferenced formals
5175 (it includes the effect of @option{-gnatwf}).
5176 This warning can also be turned on using @option{-gnatwa}.
5177
5178 @item -gnatwU
5179 @emph{Suppress warnings on unused entities.}
5180 @cindex @option{-gnatwU} (@command{gcc})
5181 This switch suppresses warnings for unused entities and packages.
5182 It also turns off warnings on unreferenced formals (and thus includes
5183 the effect of @option{-gnatwF}).
5184
5185 @item -gnatwv
5186 @emph{Activate warnings on unassigned variables.}
5187 @cindex @option{-gnatwv} (@command{gcc})
5188 @cindex Unassigned variable warnings
5189 This switch activates warnings for access to variables which
5190 may not be properly initialized. The default is that
5191 such warnings are generated.
5192 This warning can also be turned on using @option{-gnatwa}.
5193
5194 @item -gnatwV
5195 @emph{Suppress warnings on unassigned variables.}
5196 @cindex @option{-gnatwV} (@command{gcc})
5197 This switch suppresses warnings for access to variables which
5198 may not be properly initialized.
5199 For variables of a composite type, the warning can also be suppressed in
5200 Ada 2005 by using a default initialization with a box. For example, if
5201 Table is an array of records whose components are only partially uninitialized,
5202 then the following code:
5203
5204 @smallexample @c ada
5205    Tab : Table := (others => <>);
5206 @end smallexample
5207
5208 will suppress warnings on subsequent statements that access components
5209 of variable Tab.
5210
5211 @item -gnatww
5212 @emph{Activate warnings on wrong low bound assumption.}
5213 @cindex @option{-gnatww} (@command{gcc})
5214 @cindex String indexing warnings
5215 This switch activates warnings for indexing an unconstrained string parameter
5216 with a literal or S'Length. This is a case where the code is assuming that the
5217 low bound is one, which is in general not true (for example when a slice is
5218 passed). The default is that such warnings are generated.
5219 This warning can also be turned on using @option{-gnatwa}.
5220
5221 @item -gnatwW
5222 @emph{Suppress warnings on wrong low bound assumption.}
5223 @cindex @option{-gnatwW} (@command{gcc})
5224 This switch activates warnings for indexing an unconstrained string parameter
5225 with a literal or S'Length. This warning can also be suppressed by providing
5226 an Assert pragma that checks the low bound, for example:
5227
5228 @smallexample @c ada
5229    procedure K (S : String) is
5230       pragma Assert (S'First = 1);
5231       ...
5232 @end smallexample
5233
5234 @item -gnatwx
5235 @emph{Activate warnings on Export/Import pragmas.}
5236 @cindex @option{-gnatwx} (@command{gcc})
5237 @cindex Export/Import pragma warnings
5238 This switch activates warnings on Export/Import pragmas when
5239 the compiler detects a possible conflict between the Ada and
5240 foreign language calling sequences. For example, the use of
5241 default parameters in a convention C procedure is dubious
5242 because the C compiler cannot supply the proper default, so
5243 a warning is issued. The default is that such warnings are
5244 generated.
5245 This warning can also be turned on using @option{-gnatwa}.
5246
5247 @item -gnatwX
5248 @emph{Suppress warnings on Export/Import pragmas.}
5249 @cindex @option{-gnatwX} (@command{gcc})
5250 This switch suppresses warnings on Export/Import pragmas.
5251 The sense of this is that you are telling the compiler that
5252 you know what you are doing in writing the pragma, and it
5253 should not complain at you.
5254
5255 @item -gnatw.x
5256 @emph{Activate warnings for No_Exception_Propagation mode.}
5257 @cindex @option{-gnatwm} (@command{gcc})
5258 This switch activates warnings for exception usage when pragma Restrictions
5259 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5260 explicit exception raises which are not covered by a local handler, and for
5261 exception handlers which do not cover a local raise. The default is that these
5262 warnings are not given.
5263
5264 @item -gnatw.X
5265 @emph{Disable warnings for No_Exception_Propagation mode.}
5266 This switch disables warnings for exception usage when pragma Restrictions
5267 (No_Exception_Propagation) is in effect.
5268
5269 @item -gnatwy
5270 @emph{Activate warnings for Ada 2005 compatibility issues.}
5271 @cindex @option{-gnatwy} (@command{gcc})
5272 @cindex Ada 2005 compatibility issues warnings
5273 For the most part Ada 2005 is upwards compatible with Ada 95,
5274 but there are some exceptions (for example the fact that
5275 @code{interface} is now a reserved word in Ada 2005). This
5276 switch activates several warnings to help in identifying
5277 and correcting such incompatibilities. The default is that
5278 these warnings are generated. Note that at one point Ada 2005
5279 was called Ada 0Y, hence the choice of character.
5280 This warning can also be turned on using @option{-gnatwa}.
5281
5282 @item -gnatwY
5283 @emph{Disable warnings for Ada 2005 compatibility issues.}
5284 @cindex @option{-gnatwY} (@command{gcc})
5285 @cindex Ada 2005 compatibility issues warnings
5286 This switch suppresses several warnings intended to help in identifying
5287 incompatibilities between Ada 95 and Ada 2005.
5288
5289 @item -gnatwz
5290 @emph{Activate warnings on unchecked conversions.}
5291 @cindex @option{-gnatwz} (@command{gcc})
5292 @cindex Unchecked_Conversion warnings
5293 This switch activates warnings for unchecked conversions
5294 where the types are known at compile time to have different
5295 sizes. The default
5296 is that such warnings are generated.
5297 This warning can also be turned on using @option{-gnatwa}.
5298
5299 @item -gnatwZ
5300 @emph{Suppress warnings on unchecked conversions.}
5301 @cindex @option{-gnatwZ} (@command{gcc})
5302 This switch suppresses warnings for unchecked conversions
5303 where the types are known at compile time to have different
5304 sizes.
5305
5306 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5307 @cindex @option{-Wuninitialized}
5308 The warnings controlled by the @option{-gnatw} switch are generated by the
5309 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
5310 can provide additional warnings. One such useful warning is provided by
5311 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
5312 conjunction with turning on optimization mode. This causes the flow
5313 analysis circuits of the back end optimizer to output additional
5314 warnings about uninitialized variables.
5315
5316 @item ^-w^/NO_BACK_END_WARNINGS^
5317 @cindex @option{-w}
5318 This switch suppresses warnings from the @option{^gcc^GCC^} back end. The
5319 code generator detects a number of warning situations that are missed
5320 by the @option{GNAT} front end, and this switch can be used to suppress them.
5321 The use of this switch also sets the default front end warning mode to
5322 @option{-gnatws}, that is, front end warnings suppressed as well.
5323
5324 @end table
5325
5326 @noindent
5327 @ifclear vms
5328 A string of warning parameters can be used in the same parameter. For example:
5329
5330 @smallexample
5331 -gnatwaLe
5332 @end smallexample
5333
5334 @noindent
5335 will turn on all optional warnings except for elaboration pragma warnings,
5336 and also specify that warnings should be treated as errors.
5337 @end ifclear
5338 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5339
5340 @table @option
5341 @c !sort!
5342 @item -gnatwC
5343 @item -gnatwD
5344 @item -gnatwF
5345 @item -gnatwg
5346 @item -gnatwH
5347 @item -gnatwi
5348 @item -gnatwJ
5349 @item -gnatwK
5350 @item -gnatwL
5351 @item -gnatwM
5352 @item -gnatwn
5353 @item -gnatwo
5354 @item -gnatwP
5355 @item -gnatwR
5356 @item -gnatwU
5357 @item -gnatwv
5358 @item -gnatwz
5359 @item -gnatwx
5360
5361 @end table
5362
5363 @node Debugging and Assertion Control
5364 @subsection Debugging and Assertion Control
5365
5366 @table @option
5367 @item -gnata
5368 @cindex @option{-gnata} (@command{gcc})
5369 @findex Assert
5370 @findex Debug
5371 @cindex Assertions
5372
5373 @noindent
5374 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5375 are ignored. This switch, where @samp{a} stands for assert, causes
5376 @code{Assert} and @code{Debug} pragmas to be activated.
5377
5378 The pragmas have the form:
5379
5380 @smallexample
5381 @cartouche
5382    @b{pragma} Assert (@var{Boolean-expression} [,
5383                       @var{static-string-expression}])
5384    @b{pragma} Debug (@var{procedure call})
5385 @end cartouche
5386 @end smallexample
5387
5388 @noindent
5389 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5390 If the result is @code{True}, the pragma has no effect (other than
5391 possible side effects from evaluating the expression). If the result is
5392 @code{False}, the exception @code{Assert_Failure} declared in the package
5393 @code{System.Assertions} is
5394 raised (passing @var{static-string-expression}, if present, as the
5395 message associated with the exception). If no string expression is
5396 given the default is a string giving the file name and line number
5397 of the pragma.
5398
5399 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5400 @code{pragma Debug} may appear within a declaration sequence, allowing
5401 debugging procedures to be called between declarations.
5402
5403 @ifset vms
5404 @item /DEBUG[=debug-level]
5405 @itemx  /NODEBUG
5406 Specifies how much debugging information is to be included in
5407 the resulting object file where 'debug-level' is one of the following:
5408 @table @code
5409 @item   TRACEBACK
5410 Include both debugger symbol records and traceback
5411 the object file.
5412 This is the default setting.
5413 @item   ALL
5414 Include both debugger symbol records and traceback in
5415 object file.
5416 @item   NONE
5417 Excludes both debugger symbol records and traceback
5418 the object file. Same as /NODEBUG.
5419 @item   SYMBOLS
5420 Includes only debugger symbol records in the object
5421 file. Note that this doesn't include traceback information.
5422 @end table
5423 @end ifset
5424 @end table
5425
5426 @node Validity Checking
5427 @subsection Validity Checking
5428 @findex Validity Checking
5429
5430 @noindent
5431 The Ada Reference Manual has specific requirements for checking
5432 for invalid values. In particular, RM 13.9.1 requires that the
5433 evaluation of invalid values (for example from unchecked conversions),
5434 not result in erroneous execution. In GNAT, the result of such an
5435 evaluation in normal default mode is to either use the value
5436 unmodified, or to raise Constraint_Error in those cases where use
5437 of the unmodified value would cause erroneous execution. The cases
5438 where unmodified values might lead to erroneous execution are case
5439 statements (where a wild jump might result from an invalid value),
5440 and subscripts on the left hand side (where memory corruption could
5441 occur as a result of an invalid value).
5442
5443 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5444 checking mode.
5445 @ifclear vms
5446 The @code{x} argument is a string of letters that
5447 indicate validity checks that are performed or not performed in addition
5448 to the default checks described above.
5449 @end ifclear
5450 @ifset vms
5451 The options allowed for this qualifier
5452 indicate validity checks that are performed or not performed in addition
5453 to the default checks described above.
5454 @end ifset
5455
5456 @table @option
5457 @c !sort!
5458 @item -gnatVa
5459 @emph{All validity checks.}
5460 @cindex @option{-gnatVa} (@command{gcc})
5461 All validity checks are turned on.
5462 @ifclear vms
5463 That is, @option{-gnatVa} is
5464 equivalent to @option{gnatVcdfimorst}.
5465 @end ifclear
5466
5467 @item -gnatVc
5468 @emph{Validity checks for copies.}
5469 @cindex @option{-gnatVc} (@command{gcc})
5470 The right hand side of assignments, and the initializing values of
5471 object declarations are validity checked.
5472
5473 @item -gnatVd
5474 @emph{Default (RM) validity checks.}
5475 @cindex @option{-gnatVd} (@command{gcc})
5476 Some validity checks are done by default following normal Ada semantics
5477 (RM 13.9.1 (9-11)).
5478 A check is done in case statements that the expression is within the range
5479 of the subtype. If it is not, Constraint_Error is raised.
5480 For assignments to array components, a check is done that the expression used
5481 as index is within the range. If it is not, Constraint_Error is raised.
5482 Both these validity checks may be turned off using switch @option{-gnatVD}.
5483 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5484 switch @option{-gnatVd} will leave the checks turned on.
5485 Switch @option{-gnatVD} should be used only if you are sure that all such
5486 expressions have valid values. If you use this switch and invalid values
5487 are present, then the program is erroneous, and wild jumps or memory
5488 overwriting may occur.
5489
5490 @item -gnatVe
5491 @emph{Validity checks for elementary components.}
5492 @cindex @option{-gnatVe} (@command{gcc})
5493 In the absence of this switch, assignments to record or array components are
5494 not validity checked, even if validity checks for assignments generally
5495 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5496 require valid data, but assignment of individual components does. So for
5497 example, there is a difference between copying the elements of an array with a
5498 slice assignment, compared to assigning element by element in a loop. This
5499 switch allows you to turn off validity checking for components, even when they
5500 are assigned component by component.
5501
5502 @item -gnatVf
5503 @emph{Validity checks for floating-point values.}
5504 @cindex @option{-gnatVf} (@command{gcc})
5505 In the absence of this switch, validity checking occurs only for discrete
5506 values. If @option{-gnatVf} is specified, then validity checking also applies
5507 for floating-point values, and NaN's and infinities are considered invalid,
5508 as well as out of range values for constrained types. Note that this means
5509 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5510 in which floating-point values are checked depends on the setting of other
5511 options. For example,
5512 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5513 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5514 (the order does not matter) specifies that floating-point parameters of mode
5515 @code{in} should be validity checked.
5516
5517 @item -gnatVi
5518 @emph{Validity checks for @code{in} mode parameters}
5519 @cindex @option{-gnatVi} (@command{gcc})
5520 Arguments for parameters of mode @code{in} are validity checked in function
5521 and procedure calls at the point of call.
5522
5523 @item -gnatVm
5524 @emph{Validity checks for @code{in out} mode parameters.}
5525 @cindex @option{-gnatVm} (@command{gcc})
5526 Arguments for parameters of mode @code{in out} are validity checked in
5527 procedure calls at the point of call. The @code{'m'} here stands for
5528 modify, since this concerns parameters that can be modified by the call.
5529 Note that there is no specific option to test @code{out} parameters,
5530 but any reference within the subprogram will be tested in the usual
5531 manner, and if an invalid value is copied back, any reference to it
5532 will be subject to validity checking.
5533
5534 @item -gnatVn
5535 @emph{No validity checks.}
5536 @cindex @option{-gnatVn} (@command{gcc})
5537 This switch turns off all validity checking, including the default checking
5538 for case statements and left hand side subscripts. Note that the use of
5539 the switch @option{-gnatp} suppresses all run-time checks, including
5540 validity checks, and thus implies @option{-gnatVn}. When this switch
5541 is used, it cancels any other @option{-gnatV} previously issued.
5542
5543 @item -gnatVo
5544 @emph{Validity checks for operator and attribute operands.}
5545 @cindex @option{-gnatVo} (@command{gcc})
5546 Arguments for predefined operators and attributes are validity checked.
5547 This includes all operators in package @code{Standard},
5548 the shift operators defined as intrinsic in package @code{Interfaces}
5549 and operands for attributes such as @code{Pos}. Checks are also made
5550 on individual component values for composite comparisons, and on the
5551 expressions in type conversions and qualified expressions. Checks are
5552 also made on explicit ranges using .. (e.g. slices, loops etc).
5553
5554 @item -gnatVp
5555 @emph{Validity checks for parameters.}
5556 @cindex @option{-gnatVp} (@command{gcc})
5557 This controls the treatment of parameters within a subprogram (as opposed
5558 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5559 of parameters on a call. If either of these call options is used, then
5560 normally an assumption is made within a subprogram that the input arguments
5561 have been validity checking at the point of call, and do not need checking
5562 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5563 is not made, and parameters are not assumed to be valid, so their validity
5564 will be checked (or rechecked) within the subprogram.
5565
5566 @item -gnatVr
5567 @emph{Validity checks for function returns.}
5568 @cindex @option{-gnatVr} (@command{gcc})
5569 The expression in @code{return} statements in functions is validity
5570 checked.
5571
5572 @item -gnatVs
5573 @emph{Validity checks for subscripts.}
5574 @cindex @option{-gnatVs} (@command{gcc})
5575 All subscripts expressions are checked for validity, whether they appear
5576 on the right side or left side (in default mode only left side subscripts
5577 are validity checked).
5578
5579 @item -gnatVt
5580 @emph{Validity checks for tests.}
5581 @cindex @option{-gnatVt} (@command{gcc})
5582 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5583 statements are checked, as well as guard expressions in entry calls.
5584
5585 @end table
5586
5587 @noindent
5588 The @option{-gnatV} switch may be followed by
5589 ^a string of letters^a list of options^
5590 to turn on a series of validity checking options.
5591 For example,
5592 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5593 specifies that in addition to the default validity checking, copies and
5594 function return expressions are to be validity checked.
5595 In order to make it easier
5596 to specify the desired combination of effects,
5597 @ifclear vms
5598 the upper case letters @code{CDFIMORST} may
5599 be used to turn off the corresponding lower case option.
5600 @end ifclear
5601 @ifset vms
5602 the prefix @code{NO} on an option turns off the corresponding validity
5603 checking:
5604 @itemize @bullet
5605 @item @code{NOCOPIES}
5606 @item @code{NODEFAULT}
5607 @item @code{NOFLOATS}
5608 @item @code{NOIN_PARAMS}
5609 @item @code{NOMOD_PARAMS}
5610 @item @code{NOOPERANDS}
5611 @item @code{NORETURNS}
5612 @item @code{NOSUBSCRIPTS}
5613 @item @code{NOTESTS}
5614 @end itemize
5615 @end ifset
5616 Thus
5617 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5618 turns on all validity checking options except for
5619 checking of @code{@b{in out}} procedure arguments.
5620
5621 The specification of additional validity checking generates extra code (and
5622 in the case of @option{-gnatVa} the code expansion can be substantial.
5623 However, these additional checks can be very useful in detecting
5624 uninitialized variables, incorrect use of unchecked conversion, and other
5625 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5626 is useful in conjunction with the extra validity checking, since this
5627 ensures that wherever possible uninitialized variables have invalid values.
5628
5629 See also the pragma @code{Validity_Checks} which allows modification of
5630 the validity checking mode at the program source level, and also allows for
5631 temporary disabling of validity checks.
5632
5633 @node Style Checking
5634 @subsection Style Checking
5635 @findex Style checking
5636
5637 @noindent
5638 The @option{-gnaty^x^(option,option,...)^} switch
5639 @cindex @option{-gnaty} (@command{gcc})
5640 causes the compiler to
5641 enforce specified style rules. A limited set of style rules has been used
5642 in writing the GNAT sources themselves. This switch allows user programs
5643 to activate all or some of these checks. If the source program fails a
5644 specified style check, an appropriate warning message is given, preceded by
5645 the character sequence ``(style)''.
5646 @ifset vms
5647 @code{(option,option,...)} is a sequence of keywords
5648 @end ifset
5649 @ifclear vms
5650 The string @var{x} is a sequence of letters or digits
5651 @end ifclear
5652 indicating the particular style
5653 checks to be performed. The following checks are defined:
5654
5655 @table @option
5656 @c !sort!
5657 @item 1-9
5658 @emph{Specify indentation level.}
5659 If a digit from 1-9 appears
5660 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5661 then proper indentation is checked, with the digit indicating the
5662 indentation level required.
5663 The general style of required indentation is as specified by
5664 the examples in the Ada Reference Manual. Full line comments must be
5665 aligned with the @code{--} starting on a column that is a multiple of
5666 the alignment level, or they may be aligned the same way as the following
5667 non-blank line (this is useful when full line comments appear in the middle
5668 of a statement.
5669
5670 @item ^a^ATTRIBUTE^
5671 @emph{Check attribute casing.}
5672 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5673 then attribute names, including the case of keywords such as @code{digits}
5674 used as attributes names, must be written in mixed case, that is, the
5675 initial letter and any letter following an underscore must be uppercase.
5676 All other letters must be lowercase.
5677
5678 @item ^A^ARRAY_INDEXES^
5679 @emph{Use of array index numbers in array attributes.}
5680 If the ^letter A^word ARRAY_INDEXES^ appears in the string after
5681 @option{-gnaty} then when using the array attributes First, Last, Range,
5682 or Length, the index number must be omitted for one-dimensional arrays
5683 and is required for multi-dimensional arrays.
5684
5685 @item ^b^BLANKS^
5686 @emph{Blanks not allowed at statement end.}
5687 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5688 trailing blanks are not allowed at the end of statements. The purpose of this
5689 rule, together with h (no horizontal tabs), is to enforce a canonical format
5690 for the use of blanks to separate source tokens.
5691
5692 @item ^c^COMMENTS^
5693 @emph{Check comments.}
5694 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5695 then comments must meet the following set of rules:
5696
5697 @itemize @bullet
5698
5699 @item
5700 The ``@code{--}'' that starts the column must either start in column one,
5701 or else at least one blank must precede this sequence.
5702
5703 @item
5704 Comments that follow other tokens on a line must have at least one blank
5705 following the ``@code{--}'' at the start of the comment.
5706
5707 @item
5708 Full line comments must have two blanks following the ``@code{--}'' that
5709 starts the comment, with the following exceptions.
5710
5711 @item
5712 A line consisting only of the ``@code{--}'' characters, possibly preceded
5713 by blanks is permitted.
5714
5715 @item
5716 A comment starting with ``@code{--x}'' where @code{x} is a special character
5717 is permitted.
5718 This allows proper processing of the output generated by specialized tools
5719 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5720 annotation
5721 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5722 special character is defined as being in one of the ASCII ranges
5723 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5724 Note that this usage is not permitted
5725 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5726
5727 @item
5728 A line consisting entirely of minus signs, possibly preceded by blanks, is
5729 permitted. This allows the construction of box comments where lines of minus
5730 signs are used to form the top and bottom of the box.
5731
5732 @item
5733 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5734 least one blank follows the initial ``@code{--}''. Together with the preceding
5735 rule, this allows the construction of box comments, as shown in the following
5736 example:
5737 @smallexample
5738 ---------------------------
5739 -- This is a box comment --
5740 -- with two text lines.  --
5741 ---------------------------
5742 @end smallexample
5743 @end itemize
5744
5745 @item ^d^DOS_LINE_ENDINGS^
5746 @emph{Check no DOS line terminators present.}
5747 If the ^letter d^word DOS_LINE_ENDINGS^ appears in the string after
5748 @option{-gnaty} then all lines must be terminated by a single ASCII.LF
5749 character (in particular the DOS line terminator sequence CR/LF is not
5750 allowed).
5751
5752 @item ^e^END^
5753 @emph{Check end/exit labels.}
5754 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5755 optional labels on @code{end} statements ending subprograms and on
5756 @code{exit} statements exiting named loops, are required to be present.
5757
5758 @item ^f^VTABS^
5759 @emph{No form feeds or vertical tabs.}
5760 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5761 neither form feeds nor vertical tab characters are permitted
5762 in the source text.
5763
5764 @item ^g^GNAT^
5765 @emph{GNAT style mode}
5766 If the ^letter g^word GNAT^ appears in the string after @option{-gnaty} then
5767 the set of style check switches is set to match that used by the GNAT sources.
5768 This may be useful when developing code that is eventually intended to be
5769 incorporated into GNAT. For further details, see GNAT sources.
5770
5771 @item ^h^HTABS^
5772 @emph{No horizontal tabs.}
5773 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5774 horizontal tab characters are not permitted in the source text.
5775 Together with the b (no blanks at end of line) check, this
5776 enforces a canonical form for the use of blanks to separate
5777 source tokens.
5778
5779 @item ^i^IF_THEN^
5780 @emph{Check if-then layout.}
5781 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5782 then the keyword @code{then} must appear either on the same
5783 line as corresponding @code{if}, or on a line on its own, lined
5784 up under the @code{if} with at least one non-blank line in between
5785 containing all or part of the condition to be tested.
5786
5787 @item ^I^IN_MODE^
5788 @emph{check mode IN keywords}
5789 If the ^letter I (upper case)^word IN_MODE^ appears in the string
5790 after @option{-gnaty} then mode @code{in} (the default mode) is not
5791 allowed to be given explicitly. @code{in out} is fine,
5792 but not @code{in} on its own.
5793
5794 @item ^k^KEYWORD^
5795 @emph{Check keyword casing.}
5796 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5797 all keywords must be in lower case (with the exception of keywords
5798 such as @code{digits} used as attribute names to which this check
5799 does not apply).
5800
5801 @item ^l^LAYOUT^
5802 @emph{Check layout.}
5803 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5804 layout of statement and declaration constructs must follow the
5805 recommendations in the Ada Reference Manual, as indicated by the
5806 form of the syntax rules. For example an @code{else} keyword must
5807 be lined up with the corresponding @code{if} keyword.
5808
5809 There are two respects in which the style rule enforced by this check
5810 option are more liberal than those in the Ada Reference Manual. First
5811 in the case of record declarations, it is permissible to put the
5812 @code{record} keyword on the same line as the @code{type} keyword, and
5813 then the @code{end} in @code{end record} must line up under @code{type}.
5814 This is also permitted when the type declaration is split on two lines.
5815 For example, any of the following three layouts is acceptable:
5816
5817 @smallexample @c ada
5818 @cartouche
5819 type q is record
5820    a : integer;
5821    b : integer;
5822 end record;
5823
5824 type q is
5825    record
5826       a : integer;
5827       b : integer;
5828    end record;
5829
5830 type q is
5831    record
5832       a : integer;
5833       b : integer;
5834 end record;
5835
5836 @end cartouche
5837 @end smallexample
5838
5839 @noindent
5840 Second, in the case of a block statement, a permitted alternative
5841 is to put the block label on the same line as the @code{declare} or
5842 @code{begin} keyword, and then line the @code{end} keyword up under
5843 the block label. For example both the following are permitted:
5844
5845 @smallexample @c ada
5846 @cartouche
5847 Block : declare
5848    A : Integer := 3;
5849 begin
5850    Proc (A, A);
5851 end Block;
5852
5853 Block :
5854    declare
5855       A : Integer := 3;
5856    begin
5857       Proc (A, A);
5858    end Block;
5859 @end cartouche
5860 @end smallexample
5861
5862 @noindent
5863 The same alternative format is allowed for loops. For example, both of
5864 the following are permitted:
5865
5866 @smallexample @c ada
5867 @cartouche
5868 Clear : while J < 10 loop
5869    A (J) := 0;
5870 end loop Clear;
5871
5872 Clear :
5873    while J < 10 loop
5874       A (J) := 0;
5875    end loop Clear;
5876 @end cartouche
5877 @end smallexample
5878
5879 @item ^Lnnn^MAX_NESTING=nnn^
5880 @emph{Set maximum nesting level}
5881 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5882 the range 0-999, appears in the string after @option{-gnaty} then the
5883 maximum level of nesting of constructs (including subprograms, loops,
5884 blocks, packages, and conditionals) may not exceed the given value. A
5885 value of zero disconnects this style check.
5886
5887 @item ^m^LINE_LENGTH^
5888 @emph{Check maximum line length.}
5889 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5890 then the length of source lines must not exceed 79 characters, including
5891 any trailing blanks. The value of 79 allows convenient display on an
5892 80 character wide device or window, allowing for possible special
5893 treatment of 80 character lines. Note that this count is of
5894 characters in the source text. This means that a tab character counts
5895 as one character in this count but a wide character sequence counts as
5896 a single character (however many bytes are needed in the encoding).
5897
5898 @item ^Mnnn^MAX_LENGTH=nnn^
5899 @emph{Set maximum line length.}
5900 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5901 the string after @option{-gnaty} then the length of lines must not exceed the
5902 given value. The maximum value that can be specified is 32767.
5903
5904 @item ^n^STANDARD_CASING^
5905 @emph{Check casing of entities in Standard.}
5906 If the ^letter n^word STANDARD_CASING^ appears in the string
5907 after @option{-gnaty} then any identifier from Standard must be cased
5908 to match the presentation in the Ada Reference Manual (for example,
5909 @code{Integer} and @code{ASCII.NUL}).
5910
5911 @item ^o^ORDERED_SUBPROGRAMS^
5912 @emph{Check order of subprogram bodies.}
5913 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5914 after @option{-gnaty} then all subprogram bodies in a given scope
5915 (e.g. a package body) must be in alphabetical order. The ordering
5916 rule uses normal Ada rules for comparing strings, ignoring casing
5917 of letters, except that if there is a trailing numeric suffix, then
5918 the value of this suffix is used in the ordering (e.g. Junk2 comes
5919 before Junk10).
5920
5921 @item ^p^PRAGMA^
5922 @emph{Check pragma casing.}
5923 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5924 pragma names must be written in mixed case, that is, the
5925 initial letter and any letter following an underscore must be uppercase.
5926 All other letters must be lowercase.
5927
5928 @item ^r^REFERENCES^
5929 @emph{Check references.}
5930 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5931 then all identifier references must be cased in the same way as the
5932 corresponding declaration. No specific casing style is imposed on
5933 identifiers. The only requirement is for consistency of references
5934 with declarations.
5935
5936 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
5937 @emph{Check no statements after THEN/ELSE.}
5938 If the ^letter S^word STATEMENTS_AFTER_THEN_ELSE^ appears in the
5939 string after @option{-gnaty} then it is not permitted to write any
5940 statements on the same line as a THEN OR ELSE keyword following the
5941 keyword in an IF statement. OR ELSE and AND THEN are not affected,
5942 and a special exception allows a pragma to appear after ELSE.
5943
5944 @item ^s^SPECS^
5945 @emph{Check separate specs.}
5946 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5947 separate declarations (``specs'') are required for subprograms (a
5948 body is not allowed to serve as its own declaration). The only
5949 exception is that parameterless library level procedures are
5950 not required to have a separate declaration. This exception covers
5951 the most frequent form of main program procedures.
5952
5953 @item ^t^TOKEN^
5954 @emph{Check token spacing.}
5955 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5956 the following token spacing rules are enforced:
5957
5958 @itemize @bullet
5959
5960 @item
5961 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5962
5963 @item
5964 The token @code{=>} must be surrounded by spaces.
5965
5966 @item
5967 The token @code{<>} must be preceded by a space or a left parenthesis.
5968
5969 @item
5970 Binary operators other than @code{**} must be surrounded by spaces.
5971 There is no restriction on the layout of the @code{**} binary operator.
5972
5973 @item
5974 Colon must be surrounded by spaces.
5975
5976 @item
5977 Colon-equal (assignment, initialization) must be surrounded by spaces.
5978
5979 @item
5980 Comma must be the first non-blank character on the line, or be
5981 immediately preceded by a non-blank character, and must be followed
5982 by a space.
5983
5984 @item
5985 If the token preceding a left parenthesis ends with a letter or digit, then
5986 a space must separate the two tokens.
5987
5988 @item
5989 A right parenthesis must either be the first non-blank character on
5990 a line, or it must be preceded by a non-blank character.
5991
5992 @item
5993 A semicolon must not be preceded by a space, and must not be followed by
5994 a non-blank character.
5995
5996 @item
5997 A unary plus or minus may not be followed by a space.
5998
5999 @item
6000 A vertical bar must be surrounded by spaces.
6001 @end itemize
6002
6003 @item ^u^UNNECESSARY_BLANK_LINES^
6004 @emph{Check unnecessary blank lines.}
6005 Check for unnecessary blank lines. A blank line is considered
6006 unnecessary if it appears at the end of the file, or if more than
6007 one blank line occurs in sequence.
6008
6009 @item ^x^XTRA_PARENS^
6010 @emph{Check extra parentheses.}
6011 Check for the use of an unnecessary extra level of parentheses (C-style)
6012 around conditions in @code{if} statements, @code{while} statements and
6013 @code{exit} statements.
6014
6015 @end table
6016
6017 @noindent
6018 In the above rules, appearing in column one is always permitted, that is,
6019 counts as meeting either a requirement for a required preceding space,
6020 or as meeting a requirement for no preceding space.
6021
6022 Appearing at the end of a line is also always permitted, that is, counts
6023 as meeting either a requirement for a following space, or as meeting
6024 a requirement for no following space.
6025
6026 @noindent
6027 If any of these style rules is violated, a message is generated giving
6028 details on the violation. The initial characters of such messages are
6029 always ``@code{(style)}''. Note that these messages are treated as warning
6030 messages, so they normally do not prevent the generation of an object
6031 file. The @option{-gnatwe} switch can be used to treat warning messages,
6032 including style messages, as fatal errors.
6033
6034 The switch
6035 @ifclear vms
6036 @option{-gnaty} on its own (that is not
6037 followed by any letters or digits),
6038 is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6039 options enabled with the exception of @option{-gnatyo},
6040 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6041 @end ifclear
6042 @ifset vms
6043 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6044 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6045 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6046 @end ifset
6047 an indentation level of 3 is set. This is similar to the standard
6048 checking option that is used for the GNAT sources.
6049
6050 The switch
6051 @ifclear vms
6052 @option{-gnatyN}
6053 @end ifclear
6054 @ifset vms
6055 /STYLE_CHECKS=NONE
6056 @end ifset
6057 clears any previously set style checks.
6058
6059 @node Run-Time Checks
6060 @subsection Run-Time Checks
6061 @cindex Division by zero
6062 @cindex Access before elaboration
6063 @cindex Checks, division by zero
6064 @cindex Checks, access before elaboration
6065 @cindex Checks, stack overflow checking
6066
6067 @noindent
6068 If you compile with the default options, GNAT will insert many run-time
6069 checks into the compiled code, including code that performs range
6070 checking against constraints, but not arithmetic overflow checking for
6071 integer operations (including division by zero), checks for access
6072 before elaboration on subprogram calls, or stack overflow checking. All
6073 other run-time checks, as required by the Ada Reference Manual, are
6074 generated by default. The following @command{gcc} switches refine this
6075 default behavior:
6076
6077 @table @option
6078 @c !sort!
6079 @item -gnatp
6080 @cindex @option{-gnatp} (@command{gcc})
6081 @cindex Suppressing checks
6082 @cindex Checks, suppressing
6083 @findex Suppress
6084 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
6085 had been present in the source. Validity checks are also suppressed (in
6086 other words @option{-gnatp} also implies @option{-gnatVn}.
6087 Use this switch to improve the performance
6088 of the code at the expense of safety in the presence of invalid data or
6089 program bugs.
6090
6091 @item -gnato
6092 @cindex @option{-gnato} (@command{gcc})
6093 @cindex Overflow checks
6094 @cindex Check, overflow
6095 Enables overflow checking for integer operations.
6096 This causes GNAT to generate slower and larger executable
6097 programs by adding code to check for overflow (resulting in raising
6098 @code{Constraint_Error} as required by standard Ada
6099 semantics). These overflow checks correspond to situations in which
6100 the true value of the result of an operation may be outside the base
6101 range of the result type. The following example shows the distinction:
6102
6103 @smallexample @c ada
6104 X1 : Integer := Integer'Last;
6105 X2 : Integer range 1 .. 5 := 5;
6106 X3 : Integer := Integer'Last;
6107 X4 : Integer range 1 .. 5 := 5;
6108 F  : Float := 2.0E+20;
6109 ...
6110 X1 := X1 + 1;
6111 X2 := X2 + 1;
6112 X3 := Integer (F);
6113 X4 := Integer (F);
6114 @end smallexample
6115
6116 @noindent
6117 Here the first addition results in a value that is outside the base range
6118 of Integer, and hence requires an overflow check for detection of the
6119 constraint error. Thus the first assignment to @code{X1} raises a
6120 @code{Constraint_Error} exception only if @option{-gnato} is set.
6121
6122 The second increment operation results in a violation
6123 of the explicit range constraint, and such range checks are always
6124 performed (unless specifically suppressed with a pragma @code{suppress}
6125 or the use of @option{-gnatp}).
6126
6127 The two conversions of @code{F} both result in values that are outside
6128 the base range of type @code{Integer} and thus will raise
6129 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6130 The fact that the result of the second conversion is assigned to
6131 variable @code{X4} with a restricted range is irrelevant, since the problem
6132 is in the conversion, not the assignment.
6133
6134 Basically the rule is that in the default mode (@option{-gnato} not
6135 used), the generated code assures that all integer variables stay
6136 within their declared ranges, or within the base range if there is
6137 no declared range. This prevents any serious problems like indexes
6138 out of range for array operations.
6139
6140 What is not checked in default mode is an overflow that results in
6141 an in-range, but incorrect value. In the above example, the assignments
6142 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6143 range of the target variable, but the result is wrong in the sense that
6144 it is too large to be represented correctly. Typically the assignment
6145 to @code{X1} will result in wrap around to the largest negative number.
6146 The conversions of @code{F} will result in some @code{Integer} value
6147 and if that integer value is out of the @code{X4} range then the
6148 subsequent assignment would generate an exception.
6149
6150 @findex Machine_Overflows
6151 Note that the @option{-gnato} switch does not affect the code generated
6152 for any floating-point operations; it applies only to integer
6153 semantics).
6154 For floating-point, GNAT has the @code{Machine_Overflows}
6155 attribute set to @code{False} and the normal mode of operation is to
6156 generate IEEE NaN and infinite values on overflow or invalid operations
6157 (such as dividing 0.0 by 0.0).
6158
6159 The reason that we distinguish overflow checking from other kinds of
6160 range constraint checking is that a failure of an overflow check can
6161 generate an incorrect value, but cannot cause erroneous behavior. This
6162 is unlike the situation with a constraint check on an array subscript,
6163 where failure to perform the check can result in random memory description,
6164 or the range check on a case statement, where failure to perform the check
6165 can cause a wild jump.
6166
6167 Note again that @option{-gnato} is off by default, so overflow checking is
6168 not performed in default mode. This means that out of the box, with the
6169 default settings, GNAT does not do all the checks expected from the
6170 language description in the Ada Reference Manual. If you want all constraint
6171 checks to be performed, as described in this Manual, then you must
6172 explicitly use the -gnato switch either on the @command{gnatmake} or
6173 @command{gcc} command.
6174
6175 @item -gnatE
6176 @cindex @option{-gnatE} (@command{gcc})
6177 @cindex Elaboration checks
6178 @cindex Check, elaboration
6179 Enables dynamic checks for access-before-elaboration
6180 on subprogram calls and generic instantiations.
6181 For full details of the effect and use of this switch,
6182 @xref{Compiling Using gcc}.
6183
6184 @item -fstack-check
6185 @cindex @option{-fstack-check} (@command{gcc})
6186 @cindex Stack Overflow Checking
6187 @cindex Checks, stack overflow checking
6188 Activates stack overflow checking. For full details of the effect and use of
6189 this switch see @ref{Stack Overflow Checking}.
6190 @end table
6191
6192 @findex Unsuppress
6193 @noindent
6194 The setting of these switches only controls the default setting of the
6195 checks. You may modify them using either @code{Suppress} (to remove
6196 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6197 the program source.
6198
6199 @node Using gcc for Syntax Checking
6200 @subsection Using @command{gcc} for Syntax Checking
6201 @table @option
6202 @item -gnats
6203 @cindex @option{-gnats} (@command{gcc})
6204 @ifclear vms
6205
6206 @noindent
6207 The @code{s} stands for ``syntax''.
6208 @end ifclear
6209
6210 Run GNAT in syntax checking only mode. For
6211 example, the command
6212
6213 @smallexample
6214 $ gcc -c -gnats x.adb
6215 @end smallexample
6216
6217 @noindent
6218 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6219 series of files in a single command
6220 @ifclear vms
6221 , and can use wild cards to specify such a group of files.
6222 Note that you must specify the @option{-c} (compile
6223 only) flag in addition to the @option{-gnats} flag.
6224 @end ifclear
6225 .
6226 You may use other switches in conjunction with @option{-gnats}. In
6227 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6228 format of any generated error messages.
6229
6230 When the source file is empty or contains only empty lines and/or comments,
6231 the output is a warning:
6232
6233 @smallexample
6234 $ gcc -c -gnats -x ada toto.txt
6235 toto.txt:1:01: warning: empty file, contains no compilation units
6236 $
6237 @end smallexample
6238
6239 Otherwise, the output is simply the error messages, if any. No object file or
6240 ALI file is generated by a syntax-only compilation. Also, no units other
6241 than the one specified are accessed. For example, if a unit @code{X}
6242 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6243 check only mode does not access the source file containing unit
6244 @code{Y}.
6245
6246 @cindex Multiple units, syntax checking
6247 Normally, GNAT allows only a single unit in a source file. However, this
6248 restriction does not apply in syntax-check-only mode, and it is possible
6249 to check a file containing multiple compilation units concatenated
6250 together. This is primarily used by the @code{gnatchop} utility
6251 (@pxref{Renaming Files Using gnatchop}).
6252 @end table
6253
6254 @node Using gcc for Semantic Checking
6255 @subsection Using @command{gcc} for Semantic Checking
6256 @table @option
6257 @item -gnatc
6258 @cindex @option{-gnatc} (@command{gcc})
6259
6260 @ifclear vms
6261 @noindent
6262 The @code{c} stands for ``check''.
6263 @end ifclear
6264 Causes the compiler to operate in semantic check mode,
6265 with full checking for all illegalities specified in the
6266 Ada Reference Manual, but without generation of any object code
6267 (no object file is generated).
6268
6269 Because dependent files must be accessed, you must follow the GNAT
6270 semantic restrictions on file structuring to operate in this mode:
6271
6272 @itemize @bullet
6273 @item
6274 The needed source files must be accessible
6275 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6276
6277 @item
6278 Each file must contain only one compilation unit.
6279
6280 @item
6281 The file name and unit name must match (@pxref{File Naming Rules}).
6282 @end itemize
6283
6284 The output consists of error messages as appropriate. No object file is
6285 generated. An @file{ALI} file is generated for use in the context of
6286 cross-reference tools, but this file is marked as not being suitable
6287 for binding (since no object file is generated).
6288 The checking corresponds exactly to the notion of
6289 legality in the Ada Reference Manual.
6290
6291 Any unit can be compiled in semantics-checking-only mode, including
6292 units that would not normally be compiled (subunits,
6293 and specifications where a separate body is present).
6294 @end table
6295
6296 @node Compiling Different Versions of Ada
6297 @subsection Compiling Different Versions of Ada
6298
6299 @noindent
6300 The switches described in this section allow you to explicitly specify
6301 the version of the Ada language that your programs are written in.
6302 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6303 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6304 indicate Ada 83 compatibility mode.
6305
6306 @table @option
6307 @cindex Compatibility with Ada 83
6308
6309 @item -gnat83 (Ada 83 Compatibility Mode)
6310 @cindex @option{-gnat83} (@command{gcc})
6311 @cindex ACVC, Ada 83 tests
6312 @cindex Ada 83 mode
6313
6314 @noindent
6315 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6316 specifies that the program is to be compiled in Ada 83 mode. With
6317 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6318 semantics where this can be done easily.
6319 It is not possible to guarantee this switch does a perfect
6320 job; some subtle tests, such as are
6321 found in earlier ACVC tests (and that have been removed from the ACATS suite
6322 for Ada 95), might not compile correctly.
6323 Nevertheless, this switch may be useful in some circumstances, for example
6324 where, due to contractual reasons, existing code needs to be maintained
6325 using only Ada 83 features.
6326
6327 With few exceptions (most notably the need to use @code{<>} on
6328 @cindex Generic formal parameters
6329 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6330 reserved words, and the use of packages
6331 with optional bodies), it is not necessary to specify the
6332 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6333 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6334 a correct Ada 83 program is usually also a correct program
6335 in these later versions of the language standard.
6336 For further information, please refer to @ref{Compatibility and Porting Guide}.
6337
6338 @item -gnat95 (Ada 95 mode)
6339 @cindex @option{-gnat95} (@command{gcc})
6340 @cindex Ada 95 mode
6341
6342 @noindent
6343 This switch directs the compiler to implement the Ada 95 version of the
6344 language.
6345 Since Ada 95 is almost completely upwards
6346 compatible with Ada 83, Ada 83 programs may generally be compiled using
6347 this switch (see the description of the @option{-gnat83} switch for further
6348 information about Ada 83 mode).
6349 If an Ada 2005 program is compiled in Ada 95 mode,
6350 uses of the new Ada 2005 features will cause error
6351 messages or warnings.
6352
6353 This switch also can be used to cancel the effect of a previous
6354 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6355
6356 @item -gnat05 (Ada 2005 mode)
6357 @cindex @option{-gnat05} (@command{gcc})
6358 @cindex Ada 2005 mode
6359
6360 @noindent
6361 This switch directs the compiler to implement the Ada 2005 version of the
6362 language.
6363 Since Ada 2005 is almost completely upwards
6364 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6365 may generally be compiled using this switch (see the description of the
6366 @option{-gnat83} and @option{-gnat95} switches for further
6367 information).
6368
6369 For information about the approved ``Ada Issues'' that have been incorporated
6370 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6371 Included with GNAT releases is a file @file{features-ada0y} that describes
6372 the set of implemented Ada 2005 features.
6373 @end table
6374
6375
6376 @node Character Set Control
6377 @subsection Character Set Control
6378 @table @option
6379 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6380 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6381
6382 @noindent
6383 Normally GNAT recognizes the Latin-1 character set in source program
6384 identifiers, as described in the Ada Reference Manual.
6385 This switch causes
6386 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6387 single character ^^or word^ indicating the character set, as follows:
6388
6389 @table @code
6390 @item 1
6391 ISO 8859-1 (Latin-1) identifiers
6392
6393 @item 2
6394 ISO 8859-2 (Latin-2) letters allowed in identifiers
6395
6396 @item 3
6397 ISO 8859-3 (Latin-3) letters allowed in identifiers
6398
6399 @item 4
6400 ISO 8859-4 (Latin-4) letters allowed in identifiers
6401
6402 @item 5
6403 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6404
6405 @item 9
6406 ISO 8859-15 (Latin-9) letters allowed in identifiers
6407
6408 @item ^p^PC^
6409 IBM PC letters (code page 437) allowed in identifiers
6410
6411 @item ^8^PC850^
6412 IBM PC letters (code page 850) allowed in identifiers
6413
6414 @item ^f^FULL_UPPER^
6415 Full upper-half codes allowed in identifiers
6416
6417 @item ^n^NO_UPPER^
6418 No upper-half codes allowed in identifiers
6419
6420 @item ^w^WIDE^
6421 Wide-character codes (that is, codes greater than 255)
6422 allowed in identifiers
6423 @end table
6424
6425 @xref{Foreign Language Representation}, for full details on the
6426 implementation of these character sets.
6427
6428 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6429 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6430 Specify the method of encoding for wide characters.
6431 @var{e} is one of the following:
6432
6433 @table @code
6434
6435 @item ^h^HEX^
6436 Hex encoding (brackets coding also recognized)
6437
6438 @item ^u^UPPER^
6439 Upper half encoding (brackets encoding also recognized)
6440
6441 @item ^s^SHIFT_JIS^
6442 Shift/JIS encoding (brackets encoding also recognized)
6443
6444 @item ^e^EUC^
6445 EUC encoding (brackets encoding also recognized)
6446
6447 @item ^8^UTF8^
6448 UTF-8 encoding (brackets encoding also recognized)
6449
6450 @item ^b^BRACKETS^
6451 Brackets encoding only (default value)
6452 @end table
6453 For full details on these encoding
6454 methods see @ref{Wide Character Encodings}.
6455 Note that brackets coding is always accepted, even if one of the other
6456 options is specified, so for example @option{-gnatW8} specifies that both
6457 brackets and @code{UTF-8} encodings will be recognized. The units that are
6458 with'ed directly or indirectly will be scanned using the specified
6459 representation scheme, and so if one of the non-brackets scheme is
6460 used, it must be used consistently throughout the program. However,
6461 since brackets encoding is always recognized, it may be conveniently
6462 used in standard libraries, allowing these libraries to be used with
6463 any of the available coding schemes.
6464 scheme.
6465
6466 If no @option{-gnatW?} parameter is present, then the default
6467 representation is normally Brackets encoding only. However, if the
6468 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6469 byte order mark or BOM for UTF-8), then these three characters are
6470 skipped and the default representation for the file is set to UTF-8.
6471
6472 Note that the wide character representation that is specified (explicitly
6473 or by default) for the main program also acts as the default encoding used
6474 for Wide_Text_IO files if not specifically overridden by a WCEM form
6475 parameter.
6476
6477 @end table
6478 @node File Naming Control
6479 @subsection File Naming Control
6480
6481 @table @option
6482 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6483 @cindex @option{-gnatk} (@command{gcc})
6484 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6485 1-999, indicates the maximum allowable length of a file name (not
6486 including the @file{.ads} or @file{.adb} extension). The default is not
6487 to enable file name krunching.
6488
6489 For the source file naming rules, @xref{File Naming Rules}.
6490 @end table
6491
6492 @node Subprogram Inlining Control
6493 @subsection Subprogram Inlining Control
6494
6495 @table @option
6496 @c !sort!
6497 @item -gnatn
6498 @cindex @option{-gnatn} (@command{gcc})
6499 @ifclear vms
6500 The @code{n} here is intended to suggest the first syllable of the
6501 word ``inline''.
6502 @end ifclear
6503 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6504 inlining to actually occur, optimization must be enabled. To enable
6505 inlining of subprograms specified by pragma @code{Inline},
6506 you must also specify this switch.
6507 In the absence of this switch, GNAT does not attempt
6508 inlining and does not need to access the bodies of
6509 subprograms for which @code{pragma Inline} is specified if they are not
6510 in the current unit.
6511
6512 If you specify this switch the compiler will access these bodies,
6513 creating an extra source dependency for the resulting object file, and
6514 where possible, the call will be inlined.
6515 For further details on when inlining is possible
6516 see @ref{Inlining of Subprograms}.
6517
6518 @item -gnatN
6519 @cindex @option{-gnatN} (@command{gcc})
6520 The front end inlining activated by this switch is generally more extensive,
6521 and quite often more effective than the standard @option{-gnatn} inlining mode.
6522 It will also generate additional dependencies.
6523 Note that
6524 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6525 to specify both options.
6526 @end table
6527
6528 @node Auxiliary Output Control
6529 @subsection Auxiliary Output Control
6530
6531 @table @option
6532 @item -gnatt
6533 @cindex @option{-gnatt} (@command{gcc})
6534 @cindex Writing internal trees
6535 @cindex Internal trees, writing to file
6536 Causes GNAT to write the internal tree for a unit to a file (with the
6537 extension @file{.adt}.
6538 This not normally required, but is used by separate analysis tools.
6539 Typically
6540 these tools do the necessary compilations automatically, so you should
6541 not have to specify this switch in normal operation.
6542
6543 @item -gnatu
6544 @cindex @option{-gnatu} (@command{gcc})
6545 Print a list of units required by this compilation on @file{stdout}.
6546 The listing includes all units on which the unit being compiled depends
6547 either directly or indirectly.
6548
6549 @ifclear vms
6550 @item -pass-exit-codes
6551 @cindex @option{-pass-exit-codes} (@command{gcc})
6552 If this switch is not used, the exit code returned by @command{gcc} when
6553 compiling multiple files indicates whether all source files have
6554 been successfully used to generate object files or not.
6555
6556 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6557 exit status and allows an integrated development environment to better
6558 react to a compilation failure. Those exit status are:
6559
6560 @table @asis
6561 @item 5
6562 There was an error in at least one source file.
6563 @item 3
6564 At least one source file did not generate an object file.
6565 @item 2
6566 The compiler died unexpectedly (internal error for example).
6567 @item 0
6568 An object file has been generated for every source file.
6569 @end table
6570 @end ifclear
6571 @end table
6572
6573 @node Debugging Control
6574 @subsection Debugging Control
6575
6576 @table @option
6577 @c !sort!
6578 @cindex Debugging options
6579 @ifclear vms
6580 @item -gnatd@var{x}
6581 @cindex @option{-gnatd} (@command{gcc})
6582 Activate internal debugging switches. @var{x} is a letter or digit, or
6583 string of letters or digits, which specifies the type of debugging
6584 outputs desired. Normally these are used only for internal development
6585 or system debugging purposes. You can find full documentation for these
6586 switches in the body of the @code{Debug} unit in the compiler source
6587 file @file{debug.adb}.
6588 @end ifclear
6589
6590 @item -gnatG
6591 @cindex @option{-gnatG} (@command{gcc})
6592 This switch causes the compiler to generate auxiliary output containing
6593 a pseudo-source listing of the generated expanded code. Like most Ada
6594 compilers, GNAT works by first transforming the high level Ada code into
6595 lower level constructs. For example, tasking operations are transformed
6596 into calls to the tasking run-time routines. A unique capability of GNAT
6597 is to list this expanded code in a form very close to normal Ada source.
6598 This is very useful in understanding the implications of various Ada
6599 usage on the efficiency of the generated code. There are many cases in
6600 Ada (e.g. the use of controlled types), where simple Ada statements can
6601 generate a lot of run-time code. By using @option{-gnatG} you can identify
6602 these cases, and consider whether it may be desirable to modify the coding
6603 approach to improve efficiency.
6604
6605 The format of the output is very similar to standard Ada source, and is
6606 easily understood by an Ada programmer. The following special syntactic
6607 additions correspond to low level features used in the generated code that
6608 do not have any exact analogies in pure Ada source form. The following
6609 is a partial list of these special constructions. See the specification
6610 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6611
6612 If the switch @option{-gnatL} is used in conjunction with
6613 @cindex @option{-gnatL} (@command{gcc})
6614 @option{-gnatG}, then the original source lines are interspersed
6615 in the expanded source (as comment lines with the original line number).
6616
6617 @table @code
6618 @item new @var{xxx} [storage_pool = @var{yyy}]
6619 Shows the storage pool being used for an allocator.
6620
6621 @item at end @var{procedure-name};
6622 Shows the finalization (cleanup) procedure for a scope.
6623
6624 @item (if @var{expr} then @var{expr} else @var{expr})
6625 Conditional expression equivalent to the @code{x?y:z} construction in C.
6626
6627 @item @var{target}^^^(@var{source})
6628 A conversion with floating-point truncation instead of rounding.
6629
6630 @item @var{target}?(@var{source})
6631 A conversion that bypasses normal Ada semantic checking. In particular
6632 enumeration types and fixed-point types are treated simply as integers.
6633
6634 @item @var{target}?^^^(@var{source})
6635 Combines the above two cases.
6636
6637 @item @var{x} #/ @var{y}
6638 @itemx @var{x} #mod @var{y}
6639 @itemx @var{x} #* @var{y}
6640 @itemx @var{x} #rem @var{y}
6641 A division or multiplication of fixed-point values which are treated as
6642 integers without any kind of scaling.
6643
6644 @item free @var{expr} [storage_pool = @var{xxx}]
6645 Shows the storage pool associated with a @code{free} statement.
6646
6647 @item [subtype or type declaration]
6648 Used to list an equivalent declaration for an internally generated
6649 type that is referenced elsewhere in the listing.
6650
6651 @item freeze @var{type-name} [@var{actions}]
6652 Shows the point at which @var{type-name} is frozen, with possible
6653 associated actions to be performed at the freeze point.
6654
6655 @item reference @var{itype}
6656 Reference (and hence definition) to internal type @var{itype}.
6657
6658 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6659 Intrinsic function call.
6660
6661 @item @var{label-name} : label
6662 Declaration of label @var{labelname}.
6663
6664 @item #$ @var{subprogram-name}
6665 An implicit call to a run-time support routine
6666 (to meet the requirement of H.3.1(9) in a
6667 convenient manner).
6668
6669 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6670 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6671 @var{expr}, but handled more efficiently).
6672
6673 @item [constraint_error]
6674 Raise the @code{Constraint_Error} exception.
6675
6676 @item @var{expression}'reference
6677 A pointer to the result of evaluating @var{expression}.
6678
6679 @item @var{target-type}!(@var{source-expression})
6680 An unchecked conversion of @var{source-expression} to @var{target-type}.
6681
6682 @item [@var{numerator}/@var{denominator}]
6683 Used to represent internal real literals (that) have no exact
6684 representation in base 2-16 (for example, the result of compile time
6685 evaluation of the expression 1.0/27.0).
6686 @end table
6687
6688 @item -gnatD
6689 @cindex @option{-gnatD} (@command{gcc})
6690 When used in conjunction with @option{-gnatG}, this switch causes
6691 the expanded source, as described above for
6692 @option{-gnatG} to be written to files with names
6693 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6694 instead of to the standard output file. For
6695 example, if the source file name is @file{hello.adb}, then a file
6696 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6697 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6698 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6699 you to do source level debugging using the generated code which is
6700 sometimes useful for complex code, for example to find out exactly
6701 which part of a complex construction raised an exception. This switch
6702 also suppress generation of cross-reference information (see
6703 @option{-gnatx}) since otherwise the cross-reference information
6704 would refer to the @file{^.dg^.DG^} file, which would cause
6705 confusion since this is not the original source file.
6706
6707 Note that @option{-gnatD} actually implies @option{-gnatG}
6708 automatically, so it is not necessary to give both options.
6709 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6710
6711 If the switch @option{-gnatL} is used in conjunction with
6712 @cindex @option{-gnatL} (@command{gcc})
6713 @option{-gnatDG}, then the original source lines are interspersed
6714 in the expanded source (as comment lines with the original line number).
6715
6716 @ifclear vms
6717 @item -gnatR[0|1|2|3[s]]
6718 @cindex @option{-gnatR} (@command{gcc})
6719 This switch controls output from the compiler of a listing showing
6720 representation information for declared types and objects. For
6721 @option{-gnatR0}, no information is output (equivalent to omitting
6722 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6723 so @option{-gnatR} with no parameter has the same effect), size and alignment
6724 information is listed for declared array and record types. For
6725 @option{-gnatR2}, size and alignment information is listed for all
6726 declared types and objects. Finally @code{-gnatR3} includes symbolic
6727 expressions for values that are computed at run time for
6728 variant records. These symbolic expressions have a mostly obvious
6729 format with #n being used to represent the value of the n'th
6730 discriminant. See source files @file{repinfo.ads/adb} in the
6731 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6732 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6733 the output is to a file with the name @file{^file.rep^file_REP^} where
6734 file is the name of the corresponding source file.
6735 @end ifclear
6736 @ifset vms
6737 @item /REPRESENTATION_INFO
6738 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6739 This qualifier controls output from the compiler of a listing showing
6740 representation information for declared types and objects. For
6741 @option{/REPRESENTATION_INFO=NONE}, no information is output
6742 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6743 @option{/REPRESENTATION_INFO} without option is equivalent to
6744 @option{/REPRESENTATION_INFO=ARRAYS}.
6745 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6746 information is listed for declared array and record types. For
6747 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6748 is listed for all expression information for values that are computed
6749 at run time for variant records. These symbolic expressions have a mostly
6750 obvious format with #n being used to represent the value of the n'th
6751 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6752 @code{GNAT} sources for full details on the format of
6753 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6754 If _FILE is added at the end of an option
6755 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6756 then the output is to a file with the name @file{file_REP} where
6757 file is the name of the corresponding source file.
6758 @end ifset
6759 Note that it is possible for record components to have zero size. In
6760 this case, the component clause uses an obvious extension of permitted
6761 Ada syntax, for example @code{at 0 range 0 .. -1}.
6762
6763 Representation information requires that code be generated (since it is the
6764 code generator that lays out complex data structures). If an attempt is made
6765 to output representation information when no code is generated, for example
6766 when a subunit is compiled on its own, then no information can be generated
6767 and the compiler outputs a message to this effect.
6768
6769 @item -gnatS
6770 @cindex @option{-gnatS} (@command{gcc})
6771 The use of the switch @option{-gnatS} for an
6772 Ada compilation will cause the compiler to output a
6773 representation of package Standard in a form very
6774 close to standard Ada. It is not quite possible to
6775 do this entirely in standard Ada (since new
6776 numeric base types cannot be created in standard
6777 Ada), but the output is easily
6778 readable to any Ada programmer, and is useful to
6779 determine the characteristics of target dependent
6780 types in package Standard.
6781
6782 @item -gnatx
6783 @cindex @option{-gnatx} (@command{gcc})
6784 Normally the compiler generates full cross-referencing information in
6785 the @file{ALI} file. This information is used by a number of tools,
6786 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6787 suppresses this information. This saves some space and may slightly
6788 speed up compilation, but means that these tools cannot be used.
6789 @end table
6790
6791 @node Exception Handling Control
6792 @subsection Exception Handling Control
6793
6794 @noindent
6795 GNAT uses two methods for handling exceptions at run-time. The
6796 @code{setjmp/longjmp} method saves the context when entering
6797 a frame with an exception handler. Then when an exception is
6798 raised, the context can be restored immediately, without the
6799 need for tracing stack frames. This method provides very fast
6800 exception propagation, but introduces significant overhead for
6801 the use of exception handlers, even if no exception is raised.
6802
6803 The other approach is called ``zero cost'' exception handling.
6804 With this method, the compiler builds static tables to describe
6805 the exception ranges. No dynamic code is required when entering
6806 a frame containing an exception handler. When an exception is
6807 raised, the tables are used to control a back trace of the
6808 subprogram invocation stack to locate the required exception
6809 handler. This method has considerably poorer performance for
6810 the propagation of exceptions, but there is no overhead for
6811 exception handlers if no exception is raised. Note that in this
6812 mode and in the context of mixed Ada and C/C++ programming,
6813 to propagate an exception through a C/C++ code, the C/C++ code
6814 must be compiled with the @option{-funwind-tables} GCC's
6815 option.
6816
6817 The following switches may be used to control which of the
6818 two exception handling methods is used.
6819
6820 @table @option
6821 @c !sort!
6822
6823 @item --RTS=sjlj
6824 @cindex @option{--RTS=sjlj} (@command{gnatmake})
6825 This switch causes the setjmp/longjmp run-time (when available) to be used
6826 for exception handling. If the default
6827 mechanism for the target is zero cost exceptions, then
6828 this switch can be used to modify this default, and must be
6829 used for all units in the partition.
6830 This option is rarely used. One case in which it may be
6831 advantageous is if you have an application where exception
6832 raising is common and the overall performance of the
6833 application is improved by favoring exception propagation.
6834
6835 @item --RTS=zcx
6836 @cindex @option{--RTS=zcx} (@command{gnatmake})
6837 @cindex Zero Cost Exceptions
6838 This switch causes the zero cost approach to be used
6839 for exception handling. If this is the default mechanism for the
6840 target (see below), then this switch is unneeded. If the default
6841 mechanism for the target is setjmp/longjmp exceptions, then
6842 this switch can be used to modify this default, and must be
6843 used for all units in the partition.
6844 This option can only be used if the zero cost approach
6845 is available for the target in use, otherwise it will generate an error.
6846 @end table
6847
6848 @noindent
6849 The same option @option{--RTS} must be used both for @command{gcc}
6850 and @command{gnatbind}. Passing this option to @command{gnatmake}
6851 (@pxref{Switches for gnatmake}) will ensure the required consistency
6852 through the compilation and binding steps.
6853
6854 @node Units to Sources Mapping Files
6855 @subsection Units to Sources Mapping Files
6856
6857 @table @option
6858
6859 @item -gnatem^^=^@var{path}
6860 @cindex @option{-gnatem} (@command{gcc})
6861 A mapping file is a way to communicate to the compiler two mappings:
6862 from unit names to file names (without any directory information) and from
6863 file names to path names (with full directory information). These mappings
6864 are used by the compiler to short-circuit the path search.
6865
6866 The use of mapping files is not required for correct operation of the
6867 compiler, but mapping files can improve efficiency, particularly when
6868 sources are read over a slow network connection. In normal operation,
6869 you need not be concerned with the format or use of mapping files,
6870 and the @option{-gnatem} switch is not a switch that you would use
6871 explicitly. it is intended only for use by automatic tools such as
6872 @command{gnatmake} running under the project file facility. The
6873 description here of the format of mapping files is provided
6874 for completeness and for possible use by other tools.
6875
6876 A mapping file is a sequence of sets of three lines. In each set,
6877 the first line is the unit name, in lower case, with ``@code{%s}''
6878 appended for
6879 specifications and ``@code{%b}'' appended for bodies; the second line is the
6880 file name; and the third line is the path name.
6881
6882 Example:
6883 @smallexample
6884    main%b
6885    main.2.ada
6886    /gnat/project1/sources/main.2.ada
6887 @end smallexample
6888
6889 When the switch @option{-gnatem} is specified, the compiler will create
6890 in memory the two mappings from the specified file. If there is any problem
6891 (non existent file, truncated file or duplicate entries), no mapping
6892 will be created.
6893
6894 Several @option{-gnatem} switches may be specified; however, only the last
6895 one on the command line will be taken into account.
6896
6897 When using a project file, @command{gnatmake} create a temporary mapping file
6898 and communicates it to the compiler using this switch.
6899
6900 @end table
6901
6902 @node Integrated Preprocessing
6903 @subsection Integrated Preprocessing
6904
6905 @noindent
6906 GNAT sources may be preprocessed immediately before compilation.
6907 In this case, the actual
6908 text of the source is not the text of the source file, but is derived from it
6909 through a process called preprocessing. Integrated preprocessing is specified
6910 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6911 indicates, through a text file, the preprocessing data to be used.
6912 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6913
6914 @noindent
6915 Note that when integrated preprocessing is used, the output from the
6916 preprocessor is not written to any external file. Instead it is passed
6917 internally to the compiler. If you need to preserve the result of
6918 preprocessing in a file, then you should use @command{gnatprep}
6919 to perform the desired preprocessing in stand-alone mode.
6920
6921 @noindent
6922 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6923 used when Integrated Preprocessing is used. The reason is that preprocessing
6924 with another Preprocessing Data file without changing the sources will
6925 not trigger recompilation without this switch.
6926
6927 @noindent
6928 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6929 always trigger recompilation for sources that are preprocessed,
6930 because @command{gnatmake} cannot compute the checksum of the source after
6931 preprocessing.
6932
6933 @noindent
6934 The actual preprocessing function is described in details in section
6935 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6936 preprocessing is triggered and parameterized.
6937
6938 @table @code
6939
6940 @item -gnatep=@var{file}
6941 @cindex @option{-gnatep} (@command{gcc})
6942 This switch indicates to the compiler the file name (without directory
6943 information) of the preprocessor data file to use. The preprocessor data file
6944 should be found in the source directories.
6945
6946 @noindent
6947 A preprocessing data file is a text file with significant lines indicating
6948 how should be preprocessed either a specific source or all sources not
6949 mentioned in other lines. A significant line is a non empty, non comment line.
6950 Comments are similar to Ada comments.
6951
6952 @noindent
6953 Each significant line starts with either a literal string or the character '*'.
6954 A literal string is the file name (without directory information) of the source
6955 to preprocess. A character '*' indicates the preprocessing for all the sources
6956 that are not specified explicitly on other lines (order of the lines is not
6957 significant). It is an error to have two lines with the same file name or two
6958 lines starting with the character '*'.
6959
6960 @noindent
6961 After the file name or the character '*', another optional literal string
6962 indicating the file name of the definition file to be used for preprocessing
6963 (@pxref{Form of Definitions File}). The definition files are found by the
6964 compiler in one of the source directories. In some cases, when compiling
6965 a source in a directory other than the current directory, if the definition
6966 file is in the current directory, it may be necessary to add the current
6967 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6968 the compiler would not find the definition file.
6969
6970 @noindent
6971 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6972 be found. Those ^switches^switches^ are:
6973
6974 @table @code
6975
6976 @item -b
6977 Causes both preprocessor lines and the lines deleted by
6978 preprocessing to be replaced by blank lines, preserving the line number.
6979 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6980 it cancels the effect of @option{-c}.
6981
6982 @item -c
6983 Causes both preprocessor lines and the lines deleted
6984 by preprocessing to be retained as comments marked
6985 with the special string ``@code{--! }''.
6986
6987 @item -Dsymbol=value
6988 Define or redefine a symbol, associated with value. A symbol is an Ada
6989 identifier, or an Ada reserved word, with the exception of @code{if},
6990 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6991 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6992 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6993 same name defined in a definition file.
6994
6995 @item -s
6996 Causes a sorted list of symbol names and values to be
6997 listed on the standard output file.
6998
6999 @item -u
7000 Causes undefined symbols to be treated as having the value @code{FALSE}
7001 in the context
7002 of a preprocessor test. In the absence of this option, an undefined symbol in
7003 a @code{#if} or @code{#elsif} test will be treated as an error.
7004
7005 @end table
7006
7007 @noindent
7008 Examples of valid lines in a preprocessor data file:
7009
7010 @smallexample
7011   "toto.adb"  "prep.def" -u
7012   --  preprocess "toto.adb", using definition file "prep.def",
7013   --  undefined symbol are False.
7014
7015   * -c -DVERSION=V101
7016   --  preprocess all other sources without a definition file;
7017   --  suppressed lined are commented; symbol VERSION has the value V101.
7018
7019   "titi.adb" "prep2.def" -s
7020   --  preprocess "titi.adb", using definition file "prep2.def";
7021   --  list all symbols with their values.
7022 @end smallexample
7023
7024 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
7025 @cindex @option{-gnateD} (@command{gcc})
7026 Define or redefine a preprocessing symbol, associated with value. If no value
7027 is given on the command line, then the value of the symbol is @code{True}.
7028 A symbol is an identifier, following normal Ada (case-insensitive)
7029 rules for its syntax, and value is any sequence (including an empty sequence)
7030 of characters from the set (letters, digits, period, underline).
7031 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7032 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7033
7034 @noindent
7035 A symbol declared with this ^switch^switch^ on the command line replaces a
7036 symbol with the same name either in a definition file or specified with a
7037 ^switch^switch^ -D in the preprocessor data file.
7038
7039 @noindent
7040 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7041
7042 @end table
7043
7044 @node Code Generation Control
7045 @subsection Code Generation Control
7046
7047 @noindent
7048
7049 The GCC technology provides a wide range of target dependent
7050 @option{-m} switches for controlling
7051 details of code generation with respect to different versions of
7052 architectures. This includes variations in instruction sets (e.g.
7053 different members of the power pc family), and different requirements
7054 for optimal arrangement of instructions (e.g. different members of
7055 the x86 family). The list of available @option{-m} switches may be
7056 found in the GCC documentation.
7057
7058 Use of these @option{-m} switches may in some cases result in improved
7059 code performance.
7060
7061 The GNAT Pro technology is tested and qualified without any
7062 @option{-m} switches,
7063 so generally the most reliable approach is to avoid the use of these
7064 switches. However, we generally expect most of these switches to work
7065 successfully with GNAT Pro, and many customers have reported successful
7066 use of these options.
7067
7068 Our general advice is to avoid the use of @option{-m} switches unless
7069 special needs lead to requirements in this area. In particular,
7070 there is no point in using @option{-m} switches to improve performance
7071 unless you actually see a performance improvement.
7072
7073 @ifset vms
7074 @node Return Codes
7075 @subsection Return Codes
7076 @cindex Return Codes
7077 @cindex @option{/RETURN_CODES=VMS}
7078
7079 @noindent
7080 On VMS, GNAT compiled programs return POSIX-style codes by default,
7081 e.g. @option{/RETURN_CODES=POSIX}.
7082
7083 To enable VMS style return codes, use GNAT BIND and LINK with the option
7084 @option{/RETURN_CODES=VMS}. For example:
7085
7086 @smallexample
7087 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7088 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7089 @end smallexample
7090
7091 @noindent
7092 Programs built with /RETURN_CODES=VMS are suitable to be called in
7093 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7094 are suitable for spawning with appropriate GNAT RTL routines.
7095
7096 @end ifset
7097
7098 @node Search Paths and the Run-Time Library (RTL)
7099 @section Search Paths and the Run-Time Library (RTL)
7100
7101 @noindent
7102 With the GNAT source-based library system, the compiler must be able to
7103 find source files for units that are needed by the unit being compiled.
7104 Search paths are used to guide this process.
7105
7106 The compiler compiles one source file whose name must be given
7107 explicitly on the command line. In other words, no searching is done
7108 for this file. To find all other source files that are needed (the most
7109 common being the specs of units), the compiler examines the following
7110 directories, in the following order:
7111
7112 @enumerate
7113 @item
7114 The directory containing the source file of the main unit being compiled
7115 (the file name on the command line).
7116
7117 @item
7118 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7119 @command{gcc} command line, in the order given.
7120
7121 @item
7122 @findex ADA_PRJ_INCLUDE_FILE
7123 Each of the directories listed in the text file whose name is given
7124 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7125
7126 @noindent
7127 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7128 driver when project files are used. It should not normally be set
7129 by other means.
7130
7131 @item
7132 @findex ADA_INCLUDE_PATH
7133 Each of the directories listed in the value of the
7134 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7135 @ifclear vms
7136 Construct this value
7137 exactly as the @code{PATH} environment variable: a list of directory
7138 names separated by colons (semicolons when working with the NT version).
7139 @end ifclear
7140 @ifset vms
7141 Normally, define this value as a logical name containing a comma separated
7142 list of directory names.
7143
7144 This variable can also be defined by means of an environment string
7145 (an argument to the HP C exec* set of functions).
7146
7147 Logical Name:
7148 @smallexample
7149 DEFINE ANOTHER_PATH FOO:[BAG]
7150 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7151 @end smallexample
7152
7153 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7154 first, followed by the standard Ada
7155 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7156 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7157 (Text_IO, Sequential_IO, etc)
7158 instead of the standard Ada packages. Thus, in order to get the standard Ada
7159 packages by default, ADA_INCLUDE_PATH must be redefined.
7160 @end ifset
7161
7162 @item
7163 The content of the @file{ada_source_path} file which is part of the GNAT
7164 installation tree and is used to store standard libraries such as the
7165 GNAT Run Time Library (RTL) source files.
7166 @ifclear vms
7167 @ref{Installing a library}
7168 @end ifclear
7169 @end enumerate
7170
7171 @noindent
7172 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7173 inhibits the use of the directory
7174 containing the source file named in the command line. You can still
7175 have this directory on your search path, but in this case it must be
7176 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7177
7178 Specifying the switch @option{-nostdinc}
7179 inhibits the search of the default location for the GNAT Run Time
7180 Library (RTL) source files.
7181
7182 The compiler outputs its object files and ALI files in the current
7183 working directory.
7184 @ifclear vms
7185 Caution: The object file can be redirected with the @option{-o} switch;
7186 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7187 so the @file{ALI} file will not go to the right place. Therefore, you should
7188 avoid using the @option{-o} switch.
7189 @end ifclear
7190
7191 @findex System.IO
7192 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7193 children make up the GNAT RTL, together with the simple @code{System.IO}
7194 package used in the @code{"Hello World"} example. The sources for these units
7195 are needed by the compiler and are kept together in one directory. Not
7196 all of the bodies are needed, but all of the sources are kept together
7197 anyway. In a normal installation, you need not specify these directory
7198 names when compiling or binding. Either the environment variables or
7199 the built-in defaults cause these files to be found.
7200
7201 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7202 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7203 consisting of child units of @code{GNAT}. This is a collection of generally
7204 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
7205 further details.
7206
7207 Besides simplifying access to the RTL, a major use of search paths is
7208 in compiling sources from multiple directories. This can make
7209 development environments much more flexible.
7210
7211 @node Order of Compilation Issues
7212 @section Order of Compilation Issues
7213
7214 @noindent
7215 If, in our earlier example, there was a spec for the @code{hello}
7216 procedure, it would be contained in the file @file{hello.ads}; yet this
7217 file would not have to be explicitly compiled. This is the result of the
7218 model we chose to implement library management. Some of the consequences
7219 of this model are as follows:
7220
7221 @itemize @bullet
7222 @item
7223 There is no point in compiling specs (except for package
7224 specs with no bodies) because these are compiled as needed by clients. If
7225 you attempt a useless compilation, you will receive an error message.
7226 It is also useless to compile subunits because they are compiled as needed
7227 by the parent.
7228
7229 @item
7230 There are no order of compilation requirements: performing a
7231 compilation never obsoletes anything. The only way you can obsolete
7232 something and require recompilations is to modify one of the
7233 source files on which it depends.
7234
7235 @item
7236 There is no library as such, apart from the ALI files
7237 (@pxref{The Ada Library Information Files}, for information on the format
7238 of these files). For now we find it convenient to create separate ALI files,
7239 but eventually the information therein may be incorporated into the object
7240 file directly.
7241
7242 @item
7243 When you compile a unit, the source files for the specs of all units
7244 that it @code{with}'s, all its subunits, and the bodies of any generics it
7245 instantiates must be available (reachable by the search-paths mechanism
7246 described above), or you will receive a fatal error message.
7247 @end itemize
7248
7249 @node Examples
7250 @section Examples
7251
7252 @noindent
7253 The following are some typical Ada compilation command line examples:
7254
7255 @table @code
7256 @item $ gcc -c xyz.adb
7257 Compile body in file @file{xyz.adb} with all default options.
7258
7259 @ifclear vms
7260 @item $ gcc -c -O2 -gnata xyz-def.adb
7261 @end ifclear
7262 @ifset vms
7263 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7264 @end ifset
7265
7266 Compile the child unit package in file @file{xyz-def.adb} with extensive
7267 optimizations, and pragma @code{Assert}/@code{Debug} statements
7268 enabled.
7269
7270 @item $ gcc -c -gnatc abc-def.adb
7271 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7272 mode.
7273 @end table
7274
7275 @node Binding Using gnatbind
7276 @chapter Binding Using @code{gnatbind}
7277 @findex gnatbind
7278
7279 @menu
7280 * Running gnatbind::
7281 * Switches for gnatbind::
7282 * Command-Line Access::
7283 * Search Paths for gnatbind::
7284 * Examples of gnatbind Usage::
7285 @end menu
7286
7287 @noindent
7288 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7289 to bind compiled GNAT objects.
7290
7291 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7292 driver (see @ref{The GNAT Driver and Project Files}).
7293
7294 The @code{gnatbind} program performs four separate functions:
7295
7296 @enumerate
7297 @item
7298 Checks that a program is consistent, in accordance with the rules in
7299 Chapter 10 of the Ada Reference Manual. In particular, error
7300 messages are generated if a program uses inconsistent versions of a
7301 given unit.
7302
7303 @item
7304 Checks that an acceptable order of elaboration exists for the program
7305 and issues an error message if it cannot find an order of elaboration
7306 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7307
7308 @item
7309 Generates a main program incorporating the given elaboration order.
7310 This program is a small Ada package (body and spec) that
7311 must be subsequently compiled
7312 using the GNAT compiler. The necessary compilation step is usually
7313 performed automatically by @command{gnatlink}. The two most important
7314 functions of this program
7315 are to call the elaboration routines of units in an appropriate order
7316 and to call the main program.
7317
7318 @item
7319 Determines the set of object files required by the given main program.
7320 This information is output in the forms of comments in the generated program,
7321 to be read by the @command{gnatlink} utility used to link the Ada application.
7322 @end enumerate
7323
7324 @node Running gnatbind
7325 @section Running @code{gnatbind}
7326
7327 @noindent
7328 The form of the @code{gnatbind} command is
7329
7330 @smallexample
7331 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
7332 @end smallexample
7333
7334 @noindent
7335 where @file{@i{mainprog}.adb} is the Ada file containing the main program
7336 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7337 package in two files whose names are
7338 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
7339 For example, if given the
7340 parameter @file{hello.ali}, for a main program contained in file
7341 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7342 and @file{b~hello.adb}.
7343
7344 When doing consistency checking, the binder takes into consideration
7345 any source files it can locate. For example, if the binder determines
7346 that the given main program requires the package @code{Pack}, whose
7347 @file{.ALI}
7348 file is @file{pack.ali} and whose corresponding source spec file is
7349 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7350 (using the same search path conventions as previously described for the
7351 @command{gcc} command). If it can locate this source file, it checks that
7352 the time stamps
7353 or source checksums of the source and its references to in @file{ALI} files
7354 match. In other words, any @file{ALI} files that mentions this spec must have
7355 resulted from compiling this version of the source file (or in the case
7356 where the source checksums match, a version close enough that the
7357 difference does not matter).
7358
7359 @cindex Source files, use by binder
7360 The effect of this consistency checking, which includes source files, is
7361 that the binder ensures that the program is consistent with the latest
7362 version of the source files that can be located at bind time. Editing a
7363 source file without compiling files that depend on the source file cause
7364 error messages to be generated by the binder.
7365
7366 For example, suppose you have a main program @file{hello.adb} and a
7367 package @code{P}, from file @file{p.ads} and you perform the following
7368 steps:
7369
7370 @enumerate
7371 @item
7372 Enter @code{gcc -c hello.adb} to compile the main program.
7373
7374 @item
7375 Enter @code{gcc -c p.ads} to compile package @code{P}.
7376
7377 @item
7378 Edit file @file{p.ads}.
7379
7380 @item
7381 Enter @code{gnatbind hello}.
7382 @end enumerate
7383
7384 @noindent
7385 At this point, the file @file{p.ali} contains an out-of-date time stamp
7386 because the file @file{p.ads} has been edited. The attempt at binding
7387 fails, and the binder generates the following error messages:
7388
7389 @smallexample
7390 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7391 error: "p.ads" has been modified and must be recompiled
7392 @end smallexample
7393
7394 @noindent
7395 Now both files must be recompiled as indicated, and then the bind can
7396 succeed, generating a main program. You need not normally be concerned
7397 with the contents of this file, but for reference purposes a sample
7398 binder output file is given in @ref{Example of Binder Output File}.
7399
7400 In most normal usage, the default mode of @command{gnatbind} which is to
7401 generate the main package in Ada, as described in the previous section.
7402 In particular, this means that any Ada programmer can read and understand
7403 the generated main program. It can also be debugged just like any other
7404 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7405 @command{gnatbind} and @command{gnatlink}.
7406
7407 However for some purposes it may be convenient to generate the main
7408 program in C rather than Ada. This may for example be helpful when you
7409 are generating a mixed language program with the main program in C. The
7410 GNAT compiler itself is an example.
7411 The use of the @option{^-C^/BIND_FILE=C^} switch
7412 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7413 be generated in C (and compiled using the gnu C compiler).
7414
7415 @node Switches for gnatbind
7416 @section Switches for @command{gnatbind}
7417
7418 @noindent
7419 The following switches are available with @code{gnatbind}; details will
7420 be presented in subsequent sections.
7421
7422 @menu
7423 * Consistency-Checking Modes::
7424 * Binder Error Message Control::
7425 * Elaboration Control::
7426 * Output Control::
7427 * Binding with Non-Ada Main Programs::
7428 * Binding Programs with No Main Subprogram::
7429 @end menu
7430
7431 @table @option
7432 @c !sort!
7433
7434 @item --version
7435 @cindex @option{--version} @command{gnatbind}
7436 Display Copyright and version, then exit disregarding all other options.
7437
7438 @item --help
7439 @cindex @option{--help} @command{gnatbind}
7440 If @option{--version} was not used, display usage, then exit disregarding
7441 all other options.
7442
7443 @item -a
7444 @cindex @option{-a} @command{gnatbind}
7445 Indicates that, if supported by the platform, the adainit procedure should
7446 be treated as an initialisation routine by the linker (a constructor). This
7447 is intended to be used by the Project Manager to automatically initialize
7448 shared Stand-Alone Libraries.
7449
7450 @item ^-aO^/OBJECT_SEARCH^
7451 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7452 Specify directory to be searched for ALI files.
7453
7454 @item ^-aI^/SOURCE_SEARCH^
7455 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7456 Specify directory to be searched for source file.
7457
7458 @item ^-A^/BIND_FILE=ADA^
7459 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7460 Generate binder program in Ada (default)
7461
7462 @item ^-b^/REPORT_ERRORS=BRIEF^
7463 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7464 Generate brief messages to @file{stderr} even if verbose mode set.
7465
7466 @item ^-c^/NOOUTPUT^
7467 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7468 Check only, no generation of binder output file.
7469
7470 @item ^-C^/BIND_FILE=C^
7471 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7472 Generate binder program in C
7473
7474 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]
7475 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]} (@command{gnatbind})
7476 This switch can be used to change the default task stack size value
7477 to a specified size @var{nn}, which is expressed in bytes by default, or
7478 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7479 with @var{m}.
7480 In the absence of a [k|m] suffix, this switch is equivalent, in effect,
7481 to completing all task specs with
7482 @smallexample @c ada
7483    pragma Storage_Size (nn);
7484 @end smallexample
7485 When they do not already have such a pragma.
7486
7487 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}[k|m]
7488 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7489 This switch can be used to change the default secondary stack size value
7490 to a specified size @var{nn}, which is expressed in bytes by default, or
7491 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7492 with @var{m}.
7493
7494 The secondary stack is used to deal with functions that return a variable
7495 sized result, for example a function returning an unconstrained
7496 String. There are two ways in which this secondary stack is allocated.
7497
7498 For most targets, the secondary stack is growing on demand and is allocated
7499 as a chain of blocks in the heap. The -D option is not very
7500 relevant. It only give some control over the size of the allocated
7501 blocks (whose size is the minimum of the default secondary stack size value,
7502 and the actual size needed for the current allocation request).
7503
7504 For certain targets, notably VxWorks 653,
7505 the secondary stack is allocated by carving off a fixed ratio chunk of the
7506 primary task stack. The -D option is used to define the
7507 size of the environment task's secondary stack.
7508
7509 @item ^-e^/ELABORATION_DEPENDENCIES^
7510 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7511 Output complete list of elaboration-order dependencies.
7512
7513 @item ^-E^/STORE_TRACEBACKS^
7514 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7515 Store tracebacks in exception occurrences when the target supports it.
7516 This is the default with the zero cost exception mechanism.
7517 @ignore
7518 @c The following may get moved to an appendix
7519 This option is currently supported on the following targets:
7520 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7521 @end ignore
7522 See also the packages @code{GNAT.Traceback} and
7523 @code{GNAT.Traceback.Symbolic} for more information.
7524 @ifclear vms
7525 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7526 @command{gcc} option.
7527 @end ifclear
7528
7529 @item ^-F^/FORCE_ELABS_FLAGS^
7530 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7531 Force the checks of elaboration flags. @command{gnatbind} does not normally
7532 generate checks of elaboration flags for the main executable, except when
7533 a Stand-Alone Library is used. However, there are cases when this cannot be
7534 detected by gnatbind. An example is importing an interface of a Stand-Alone
7535 Library through a pragma Import and only specifying through a linker switch
7536 this Stand-Alone Library. This switch is used to guarantee that elaboration
7537 flag checks are generated.
7538
7539 @item ^-h^/HELP^
7540 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7541 Output usage (help) information
7542
7543 @item ^-I^/SEARCH^
7544 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7545 Specify directory to be searched for source and ALI files.
7546
7547 @item ^-I-^/NOCURRENT_DIRECTORY^
7548 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7549 Do not look for sources in the current directory where @code{gnatbind} was
7550 invoked, and do not look for ALI files in the directory containing the
7551 ALI file named in the @code{gnatbind} command line.
7552
7553 @item ^-l^/ORDER_OF_ELABORATION^
7554 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7555 Output chosen elaboration order.
7556
7557 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7558 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7559 Bind the units for library building. In this case the adainit and
7560 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7561 are renamed to ^xxxinit^XXXINIT^ and
7562 ^xxxfinal^XXXFINAL^.
7563 Implies ^-n^/NOCOMPILE^.
7564 @ifclear vms
7565 (@xref{GNAT and Libraries}, for more details.)
7566 @end ifclear
7567 @ifset vms
7568 On OpenVMS, these init and final procedures are exported in uppercase
7569 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7570 the init procedure will be "TOTOINIT" and the exported name of the final
7571 procedure will be "TOTOFINAL".
7572 @end ifset
7573
7574 @item ^-Mxyz^/RENAME_MAIN=xyz^
7575 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7576 Rename generated main program from main to xyz. This option is
7577 supported on cross environments only.
7578
7579 @item ^-m^/ERROR_LIMIT=^@var{n}
7580 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7581 Limit number of detected errors to @var{n}, where @var{n} is
7582 in the range 1..999_999. The default value if no switch is
7583 given is 9999. Binding is terminated if the limit is exceeded.
7584 @ifset unw
7585 Furthermore, under Windows, the sources pointed to by the libraries path
7586 set in the registry are not searched for.
7587 @end ifset
7588
7589 @item ^-n^/NOMAIN^
7590 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7591 No main program.
7592
7593 @item -nostdinc
7594 @cindex @option{-nostdinc} (@command{gnatbind})
7595 Do not look for sources in the system default directory.
7596
7597 @item -nostdlib
7598 @cindex @option{-nostdlib} (@command{gnatbind})
7599 Do not look for library files in the system default directory.
7600
7601 @item --RTS=@var{rts-path}
7602 @cindex @option{--RTS} (@code{gnatbind})
7603 Specifies the default location of the runtime library. Same meaning as the
7604 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7605
7606 @item ^-o ^/OUTPUT=^@var{file}
7607 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7608 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7609 Note that if this option is used, then linking must be done manually,
7610 gnatlink cannot be used.
7611
7612 @item ^-O^/OBJECT_LIST^
7613 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7614 Output object list.
7615
7616 @item ^-p^/PESSIMISTIC_ELABORATION^
7617 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7618 Pessimistic (worst-case) elaboration order
7619
7620 @item ^-R^-R^
7621 @cindex @option{^-R^-R^} (@command{gnatbind})
7622 Output closure source list.
7623
7624 @item ^-s^/READ_SOURCES=ALL^
7625 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7626 Require all source files to be present.
7627
7628 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7629 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7630 Specifies the value to be used when detecting uninitialized scalar
7631 objects with pragma Initialize_Scalars.
7632 The @var{xxx} ^string specified with the switch^option^ may be either
7633 @itemize @bullet
7634 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7635 @item ``@option{^lo^LOW^}'' for the lowest possible value
7636 @item ``@option{^hi^HIGH^}'' for the highest possible value
7637 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7638 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7639 @end itemize
7640
7641 In addition, you can specify @option{-Sev} to indicate that the value is
7642 to be set at run time. In this case, the program will look for an environment
7643 @cindex GNAT_INIT_SCALARS
7644 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7645 of @option{in/lo/hi/xx} with the same meanings as above.
7646 If no environment variable is found, or if it does not have a valid value,
7647 then the default is @option{in} (invalid values).
7648
7649 @ifclear vms
7650 @item -static
7651 @cindex @option{-static} (@code{gnatbind})
7652 Link against a static GNAT run time.
7653
7654 @item -shared
7655 @cindex @option{-shared} (@code{gnatbind})
7656 Link against a shared GNAT run time when available.
7657 @end ifclear
7658
7659 @item ^-t^/NOTIME_STAMP_CHECK^
7660 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7661 Tolerate time stamp and other consistency errors
7662
7663 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7664 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7665 Set the time slice value to @var{n} milliseconds. If the system supports
7666 the specification of a specific time slice value, then the indicated value
7667 is used. If the system does not support specific time slice values, but
7668 does support some general notion of round-robin scheduling, then any
7669 nonzero value will activate round-robin scheduling.
7670
7671 A value of zero is treated specially. It turns off time
7672 slicing, and in addition, indicates to the tasking run time that the
7673 semantics should match as closely as possible the Annex D
7674 requirements of the Ada RM, and in particular sets the default
7675 scheduling policy to @code{FIFO_Within_Priorities}.
7676
7677 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
7678 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
7679 Enable dynamic stack usage, with @var{n} results stored and displayed
7680 at program termination. A result is generated when a task
7681 terminates. Results that can't be stored are displayed on the fly, at
7682 task termination. This option is currently not supported on Itanium
7683 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
7684
7685 @item ^-v^/REPORT_ERRORS=VERBOSE^
7686 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7687 Verbose mode. Write error messages, header, summary output to
7688 @file{stdout}.
7689
7690 @ifclear vms
7691 @item -w@var{x}
7692 @cindex @option{-w} (@code{gnatbind})
7693 Warning mode (@var{x}=s/e for suppress/treat as error)
7694 @end ifclear
7695
7696 @ifset vms
7697 @item /WARNINGS=NORMAL
7698 @cindex @option{/WARNINGS} (@code{gnatbind})
7699 Normal warnings mode. Warnings are issued but ignored
7700
7701 @item /WARNINGS=SUPPRESS
7702 @cindex @option{/WARNINGS} (@code{gnatbind})
7703 All warning messages are suppressed
7704
7705 @item /WARNINGS=ERROR
7706 @cindex @option{/WARNINGS} (@code{gnatbind})
7707 Warning messages are treated as fatal errors
7708 @end ifset
7709
7710 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
7711 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
7712 Override default wide character encoding for standard Text_IO files.
7713
7714 @item ^-x^/READ_SOURCES=NONE^
7715 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7716 Exclude source files (check object consistency only).
7717
7718 @ifset vms
7719 @item /READ_SOURCES=AVAILABLE
7720 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7721 Default mode, in which sources are checked for consistency only if
7722 they are available.
7723 @end ifset
7724
7725 @item ^-y^/ENABLE_LEAP_SECONDS^
7726 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
7727 Enable leap seconds support in @code{Ada.Calendar} and its children.
7728
7729 @item ^-z^/ZERO_MAIN^
7730 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7731 No main subprogram.
7732 @end table
7733
7734 @ifclear vms
7735 @noindent
7736 You may obtain this listing of switches by running @code{gnatbind} with
7737 no arguments.
7738 @end ifclear
7739
7740 @node Consistency-Checking Modes
7741 @subsection Consistency-Checking Modes
7742
7743 @noindent
7744 As described earlier, by default @code{gnatbind} checks
7745 that object files are consistent with one another and are consistent
7746 with any source files it can locate. The following switches control binder
7747 access to sources.
7748
7749 @table @option
7750 @c !sort!
7751 @item ^-s^/READ_SOURCES=ALL^
7752 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7753 Require source files to be present. In this mode, the binder must be
7754 able to locate all source files that are referenced, in order to check
7755 their consistency. In normal mode, if a source file cannot be located it
7756 is simply ignored. If you specify this switch, a missing source
7757 file is an error.
7758
7759 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
7760 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
7761 Override default wide character encoding for standard Text_IO files.
7762 Normally the default wide character encoding method used for standard
7763 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
7764 the main source input (see description of switch
7765 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
7766 use of this switch for the binder (which has the same set of
7767 possible arguments) overrides this default as specified.
7768
7769 @item ^-x^/READ_SOURCES=NONE^
7770 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7771 Exclude source files. In this mode, the binder only checks that ALI
7772 files are consistent with one another. Source files are not accessed.
7773 The binder runs faster in this mode, and there is still a guarantee that
7774 the resulting program is self-consistent.
7775 If a source file has been edited since it was last compiled, and you
7776 specify this switch, the binder will not detect that the object
7777 file is out of date with respect to the source file. Note that this is the
7778 mode that is automatically used by @command{gnatmake} because in this
7779 case the checking against sources has already been performed by
7780 @command{gnatmake} in the course of compilation (i.e. before binding).
7781
7782 @ifset vms
7783 @item /READ_SOURCES=AVAILABLE
7784 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7785 This is the default mode in which source files are checked if they are
7786 available, and ignored if they are not available.
7787 @end ifset
7788 @end table
7789
7790 @node Binder Error Message Control
7791 @subsection Binder Error Message Control
7792
7793 @noindent
7794 The following switches provide control over the generation of error
7795 messages from the binder:
7796
7797 @table @option
7798 @c !sort!
7799 @item ^-v^/REPORT_ERRORS=VERBOSE^
7800 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7801 Verbose mode. In the normal mode, brief error messages are generated to
7802 @file{stderr}. If this switch is present, a header is written
7803 to @file{stdout} and any error messages are directed to @file{stdout}.
7804 All that is written to @file{stderr} is a brief summary message.
7805
7806 @item ^-b^/REPORT_ERRORS=BRIEF^
7807 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7808 Generate brief error messages to @file{stderr} even if verbose mode is
7809 specified. This is relevant only when used with the
7810 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7811
7812 @ifclear vms
7813 @item -m@var{n}
7814 @cindex @option{-m} (@code{gnatbind})
7815 Limits the number of error messages to @var{n}, a decimal integer in the
7816 range 1-999. The binder terminates immediately if this limit is reached.
7817
7818 @item -M@var{xxx}
7819 @cindex @option{-M} (@code{gnatbind})
7820 Renames the generated main program from @code{main} to @code{xxx}.
7821 This is useful in the case of some cross-building environments, where
7822 the actual main program is separate from the one generated
7823 by @code{gnatbind}.
7824 @end ifclear
7825
7826 @item ^-ws^/WARNINGS=SUPPRESS^
7827 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7828 @cindex Warnings
7829 Suppress all warning messages.
7830
7831 @item ^-we^/WARNINGS=ERROR^
7832 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7833 Treat any warning messages as fatal errors.
7834
7835 @ifset vms
7836 @item /WARNINGS=NORMAL
7837 Standard mode with warnings generated, but warnings do not get treated
7838 as errors.
7839 @end ifset
7840
7841 @item ^-t^/NOTIME_STAMP_CHECK^
7842 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7843 @cindex Time stamp checks, in binder
7844 @cindex Binder consistency checks
7845 @cindex Consistency checks, in binder
7846 The binder performs a number of consistency checks including:
7847
7848 @itemize @bullet
7849 @item
7850 Check that time stamps of a given source unit are consistent
7851 @item
7852 Check that checksums of a given source unit are consistent
7853 @item
7854 Check that consistent versions of @code{GNAT} were used for compilation
7855 @item
7856 Check consistency of configuration pragmas as required
7857 @end itemize
7858
7859 @noindent
7860 Normally failure of such checks, in accordance with the consistency
7861 requirements of the Ada Reference Manual, causes error messages to be
7862 generated which abort the binder and prevent the output of a binder
7863 file and subsequent link to obtain an executable.
7864
7865 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7866 into warnings, so that
7867 binding and linking can continue to completion even in the presence of such
7868 errors. The result may be a failed link (due to missing symbols), or a
7869 non-functional executable which has undefined semantics.
7870 @emph{This means that
7871 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7872 with extreme care.}
7873 @end table
7874
7875 @node Elaboration Control
7876 @subsection Elaboration Control
7877
7878 @noindent
7879 The following switches provide additional control over the elaboration
7880 order. For full details see @ref{Elaboration Order Handling in GNAT}.
7881
7882 @table @option
7883 @item ^-p^/PESSIMISTIC_ELABORATION^
7884 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7885 Normally the binder attempts to choose an elaboration order that is
7886 likely to minimize the likelihood of an elaboration order error resulting
7887 in raising a @code{Program_Error} exception. This switch reverses the
7888 action of the binder, and requests that it deliberately choose an order
7889 that is likely to maximize the likelihood of an elaboration error.
7890 This is useful in ensuring portability and avoiding dependence on
7891 accidental fortuitous elaboration ordering.
7892
7893 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7894 switch if dynamic
7895 elaboration checking is used (@option{-gnatE} switch used for compilation).
7896 This is because in the default static elaboration mode, all necessary
7897 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
7898 These implicit pragmas are still respected by the binder in
7899 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7900 safe elaboration order is assured.
7901 @end table
7902
7903 @node Output Control
7904 @subsection Output Control
7905
7906 @noindent
7907 The following switches allow additional control over the output
7908 generated by the binder.
7909
7910 @table @option
7911 @c !sort!
7912
7913 @item ^-A^/BIND_FILE=ADA^
7914 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7915 Generate binder program in Ada (default). The binder program is named
7916 @file{b~@var{mainprog}.adb} by default. This can be changed with
7917 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7918
7919 @item ^-c^/NOOUTPUT^
7920 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7921 Check only. Do not generate the binder output file. In this mode the
7922 binder performs all error checks but does not generate an output file.
7923
7924 @item ^-C^/BIND_FILE=C^
7925 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7926 Generate binder program in C. The binder program is named
7927 @file{b_@var{mainprog}.c}.
7928 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7929 option.
7930
7931 @item ^-e^/ELABORATION_DEPENDENCIES^
7932 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7933 Output complete list of elaboration-order dependencies, showing the
7934 reason for each dependency. This output can be rather extensive but may
7935 be useful in diagnosing problems with elaboration order. The output is
7936 written to @file{stdout}.
7937
7938 @item ^-h^/HELP^
7939 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7940 Output usage information. The output is written to @file{stdout}.
7941
7942 @item ^-K^/LINKER_OPTION_LIST^
7943 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7944 Output linker options to @file{stdout}. Includes library search paths,
7945 contents of pragmas Ident and Linker_Options, and libraries added
7946 by @code{gnatbind}.
7947
7948 @item ^-l^/ORDER_OF_ELABORATION^
7949 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7950 Output chosen elaboration order. The output is written to @file{stdout}.
7951
7952 @item ^-O^/OBJECT_LIST^
7953 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7954 Output full names of all the object files that must be linked to provide
7955 the Ada component of the program. The output is written to @file{stdout}.
7956 This list includes the files explicitly supplied and referenced by the user
7957 as well as implicitly referenced run-time unit files. The latter are
7958 omitted if the corresponding units reside in shared libraries. The
7959 directory names for the run-time units depend on the system configuration.
7960
7961 @item ^-o ^/OUTPUT=^@var{file}
7962 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7963 Set name of output file to @var{file} instead of the normal
7964 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7965 binder generated body filename. In C mode you would normally give
7966 @var{file} an extension of @file{.c} because it will be a C source program.
7967 Note that if this option is used, then linking must be done manually.
7968 It is not possible to use gnatlink in this case, since it cannot locate
7969 the binder file.
7970
7971 @item ^-r^/RESTRICTION_LIST^
7972 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7973 Generate list of @code{pragma Restrictions} that could be applied to
7974 the current unit. This is useful for code audit purposes, and also may
7975 be used to improve code generation in some cases.
7976
7977 @end table
7978
7979 @node Binding with Non-Ada Main Programs
7980 @subsection Binding with Non-Ada Main Programs
7981
7982 @noindent
7983 In our description so far we have assumed that the main
7984 program is in Ada, and that the task of the binder is to generate a
7985 corresponding function @code{main} that invokes this Ada main
7986 program. GNAT also supports the building of executable programs where
7987 the main program is not in Ada, but some of the called routines are
7988 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7989 The following switch is used in this situation:
7990
7991 @table @option
7992 @item ^-n^/NOMAIN^
7993 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7994 No main program. The main program is not in Ada.
7995 @end table
7996
7997 @noindent
7998 In this case, most of the functions of the binder are still required,
7999 but instead of generating a main program, the binder generates a file
8000 containing the following callable routines:
8001
8002 @table @code
8003 @item adainit
8004 @findex adainit
8005 You must call this routine to initialize the Ada part of the program by
8006 calling the necessary elaboration routines. A call to @code{adainit} is
8007 required before the first call to an Ada subprogram.
8008
8009 Note that it is assumed that the basic execution environment must be setup
8010 to be appropriate for Ada execution at the point where the first Ada
8011 subprogram is called. In particular, if the Ada code will do any
8012 floating-point operations, then the FPU must be setup in an appropriate
8013 manner. For the case of the x86, for example, full precision mode is
8014 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8015 that the FPU is in the right state.
8016
8017 @item adafinal
8018 @findex adafinal
8019 You must call this routine to perform any library-level finalization
8020 required by the Ada subprograms. A call to @code{adafinal} is required
8021 after the last call to an Ada subprogram, and before the program
8022 terminates.
8023 @end table
8024
8025 @noindent
8026 If the @option{^-n^/NOMAIN^} switch
8027 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8028 @cindex Binder, multiple input files
8029 is given, more than one ALI file may appear on
8030 the command line for @code{gnatbind}. The normal @dfn{closure}
8031 calculation is performed for each of the specified units. Calculating
8032 the closure means finding out the set of units involved by tracing
8033 @code{with} references. The reason it is necessary to be able to
8034 specify more than one ALI file is that a given program may invoke two or
8035 more quite separate groups of Ada units.
8036
8037 The binder takes the name of its output file from the last specified ALI
8038 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8039 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8040 The output is an Ada unit in source form that can
8041 be compiled with GNAT unless the -C switch is used in which case the
8042 output is a C source file, which must be compiled using the C compiler.
8043 This compilation occurs automatically as part of the @command{gnatlink}
8044 processing.
8045
8046 Currently the GNAT run time requires a FPU using 80 bits mode
8047 precision. Under targets where this is not the default it is required to
8048 call GNAT.Float_Control.Reset before using floating point numbers (this
8049 include float computation, float input and output) in the Ada code. A
8050 side effect is that this could be the wrong mode for the foreign code
8051 where floating point computation could be broken after this call.
8052
8053 @node Binding Programs with No Main Subprogram
8054 @subsection Binding Programs with No Main Subprogram
8055
8056 @noindent
8057 It is possible to have an Ada program which does not have a main
8058 subprogram. This program will call the elaboration routines of all the
8059 packages, then the finalization routines.
8060
8061 The following switch is used to bind programs organized in this manner:
8062
8063 @table @option
8064 @item ^-z^/ZERO_MAIN^
8065 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8066 Normally the binder checks that the unit name given on the command line
8067 corresponds to a suitable main subprogram. When this switch is used,
8068 a list of ALI files can be given, and the execution of the program
8069 consists of elaboration of these units in an appropriate order. Note
8070 that the default wide character encoding method for standard Text_IO
8071 files is always set to Brackets if this switch is set (you can use
8072 the binder switch
8073 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8074 @end table
8075
8076 @node Command-Line Access
8077 @section Command-Line Access
8078
8079 @noindent
8080 The package @code{Ada.Command_Line} provides access to the command-line
8081 arguments and program name. In order for this interface to operate
8082 correctly, the two variables
8083
8084 @smallexample
8085 @group
8086 int gnat_argc;
8087 char **gnat_argv;
8088 @end group
8089 @end smallexample
8090
8091 @noindent
8092 @findex gnat_argv
8093 @findex gnat_argc
8094 are declared in one of the GNAT library routines. These variables must
8095 be set from the actual @code{argc} and @code{argv} values passed to the
8096 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8097 generates the C main program to automatically set these variables.
8098 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8099 set these variables. If they are not set, the procedures in
8100 @code{Ada.Command_Line} will not be available, and any attempt to use
8101 them will raise @code{Constraint_Error}. If command line access is
8102 required, your main program must set @code{gnat_argc} and
8103 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8104 it.
8105
8106 @node Search Paths for gnatbind
8107 @section Search Paths for @code{gnatbind}
8108
8109 @noindent
8110 The binder takes the name of an ALI file as its argument and needs to
8111 locate source files as well as other ALI files to verify object consistency.
8112
8113 For source files, it follows exactly the same search rules as @command{gcc}
8114 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8115 directories searched are:
8116
8117 @enumerate
8118 @item
8119 The directory containing the ALI file named in the command line, unless
8120 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8121
8122 @item
8123 All directories specified by @option{^-I^/SEARCH^}
8124 switches on the @code{gnatbind}
8125 command line, in the order given.
8126
8127 @item
8128 @findex ADA_PRJ_OBJECTS_FILE
8129 Each of the directories listed in the text file whose name is given
8130 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8131
8132 @noindent
8133 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8134 driver when project files are used. It should not normally be set
8135 by other means.
8136
8137 @item
8138 @findex ADA_OBJECTS_PATH
8139 Each of the directories listed in the value of the
8140 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8141 @ifset unw
8142 Construct this value
8143 exactly as the @code{PATH} environment variable: a list of directory
8144 names separated by colons (semicolons when working with the NT version
8145 of GNAT).
8146 @end ifset
8147 @ifset vms
8148 Normally, define this value as a logical name containing a comma separated
8149 list of directory names.
8150
8151 This variable can also be defined by means of an environment string
8152 (an argument to the HP C exec* set of functions).
8153
8154 Logical Name:
8155 @smallexample
8156 DEFINE ANOTHER_PATH FOO:[BAG]
8157 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8158 @end smallexample
8159
8160 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8161 first, followed by the standard Ada
8162 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8163 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8164 (Text_IO, Sequential_IO, etc)
8165 instead of the standard Ada packages. Thus, in order to get the standard Ada
8166 packages by default, ADA_OBJECTS_PATH must be redefined.
8167 @end ifset
8168
8169 @item
8170 The content of the @file{ada_object_path} file which is part of the GNAT
8171 installation tree and is used to store standard libraries such as the
8172 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8173 specified.
8174 @ifclear vms
8175 @ref{Installing a library}
8176 @end ifclear
8177 @end enumerate
8178
8179 @noindent
8180 In the binder the switch @option{^-I^/SEARCH^}
8181 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8182 is used to specify both source and
8183 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8184 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8185 instead if you want to specify
8186 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8187 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8188 if you want to specify library paths
8189 only. This means that for the binder
8190 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8191 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8192 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8193 The binder generates the bind file (a C language source file) in the
8194 current working directory.
8195
8196 @findex Ada
8197 @findex System
8198 @findex Interfaces
8199 @findex GNAT
8200 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8201 children make up the GNAT Run-Time Library, together with the package
8202 GNAT and its children, which contain a set of useful additional
8203 library functions provided by GNAT. The sources for these units are
8204 needed by the compiler and are kept together in one directory. The ALI
8205 files and object files generated by compiling the RTL are needed by the
8206 binder and the linker and are kept together in one directory, typically
8207 different from the directory containing the sources. In a normal
8208 installation, you need not specify these directory names when compiling
8209 or binding. Either the environment variables or the built-in defaults
8210 cause these files to be found.
8211
8212 Besides simplifying access to the RTL, a major use of search paths is
8213 in compiling sources from multiple directories. This can make
8214 development environments much more flexible.
8215
8216 @node Examples of gnatbind Usage
8217 @section Examples of @code{gnatbind} Usage
8218
8219 @noindent
8220 This section contains a number of examples of using the GNAT binding
8221 utility @code{gnatbind}.
8222
8223 @table @code
8224 @item gnatbind hello
8225 The main program @code{Hello} (source program in @file{hello.adb}) is
8226 bound using the standard switch settings. The generated main program is
8227 @file{b~hello.adb}. This is the normal, default use of the binder.
8228
8229 @ifclear vms
8230 @item gnatbind hello -o mainprog.adb
8231 @end ifclear
8232 @ifset vms
8233 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8234 @end ifset
8235 The main program @code{Hello} (source program in @file{hello.adb}) is
8236 bound using the standard switch settings. The generated main program is
8237 @file{mainprog.adb} with the associated spec in
8238 @file{mainprog.ads}. Note that you must specify the body here not the
8239 spec, in the case where the output is in Ada. Note that if this option
8240 is used, then linking must be done manually, since gnatlink will not
8241 be able to find the generated file.
8242
8243 @ifclear vms
8244 @item gnatbind main -C -o mainprog.c -x
8245 @end ifclear
8246 @ifset vms
8247 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8248 @end ifset
8249 The main program @code{Main} (source program in
8250 @file{main.adb}) is bound, excluding source files from the
8251 consistency checking, generating
8252 the file @file{mainprog.c}.
8253
8254 @ifclear vms
8255 @item gnatbind -x main_program -C -o mainprog.c
8256 This command is exactly the same as the previous example. Switches may
8257 appear anywhere in the command line, and single letter switches may be
8258 combined into a single switch.
8259 @end ifclear
8260
8261 @ifclear vms
8262 @item gnatbind -n math dbase -C -o ada-control.c
8263 @end ifclear
8264 @ifset vms
8265 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8266 @end ifset
8267 The main program is in a language other than Ada, but calls to
8268 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8269 to @code{gnatbind} generates the file @file{ada-control.c} containing
8270 the @code{adainit} and @code{adafinal} routines to be called before and
8271 after accessing the Ada units.
8272 @end table
8273
8274 @c ------------------------------------
8275 @node Linking Using gnatlink
8276 @chapter Linking Using @command{gnatlink}
8277 @c ------------------------------------
8278 @findex gnatlink
8279
8280 @noindent
8281 This chapter discusses @command{gnatlink}, a tool that links
8282 an Ada program and builds an executable file. This utility
8283 invokes the system linker ^(via the @command{gcc} command)^^
8284 with a correct list of object files and library references.
8285 @command{gnatlink} automatically determines the list of files and
8286 references for the Ada part of a program. It uses the binder file
8287 generated by the @command{gnatbind} to determine this list.
8288
8289 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8290 driver (see @ref{The GNAT Driver and Project Files}).
8291
8292 @menu
8293 * Running gnatlink::
8294 * Switches for gnatlink::
8295 @end menu
8296
8297 @node Running gnatlink
8298 @section Running @command{gnatlink}
8299
8300 @noindent
8301 The form of the @command{gnatlink} command is
8302
8303 @smallexample
8304 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
8305            [@var{non-Ada objects}] [@var{linker options}]
8306 @end smallexample
8307
8308 @noindent
8309 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8310 non-Ada objects
8311 or linker options) may be in any order, provided that no non-Ada object may
8312 be mistaken for a main @file{ALI} file.
8313 Any file name @file{F} without the @file{.ali}
8314 extension will be taken as the main @file{ALI} file if a file exists
8315 whose name is the concatenation of @file{F} and @file{.ali}.
8316
8317 @noindent
8318 @file{@var{mainprog}.ali} references the ALI file of the main program.
8319 The @file{.ali} extension of this file can be omitted. From this
8320 reference, @command{gnatlink} locates the corresponding binder file
8321 @file{b~@var{mainprog}.adb} and, using the information in this file along
8322 with the list of non-Ada objects and linker options, constructs a
8323 linker command file to create the executable.
8324
8325 The arguments other than the @command{gnatlink} switches and the main
8326 @file{ALI} file are passed to the linker uninterpreted.
8327 They typically include the names of
8328 object files for units written in other languages than Ada and any library
8329 references required to resolve references in any of these foreign language
8330 units, or in @code{Import} pragmas in any Ada units.
8331
8332 @var{linker options} is an optional list of linker specific
8333 switches.
8334 The default linker called by gnatlink is @var{gcc} which in
8335 turn calls the appropriate system linker.
8336 Standard options for the linker such as @option{-lmy_lib} or
8337 @option{-Ldir} can be added as is.
8338 For options that are not recognized by
8339 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
8340 @option{-Wl,}.
8341 Refer to the GCC documentation for
8342 details. Here is an example showing how to generate a linker map:
8343
8344 @smallexample
8345 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8346 @end smallexample
8347
8348 Using @var{linker options} it is possible to set the program stack and
8349 heap size.
8350 @ifclear vms
8351 See @ref{Setting Stack Size from gnatlink} and
8352 @ref{Setting Heap Size from gnatlink}.
8353 @end ifclear
8354
8355 @command{gnatlink} determines the list of objects required by the Ada
8356 program and prepends them to the list of objects passed to the linker.
8357 @command{gnatlink} also gathers any arguments set by the use of
8358 @code{pragma Linker_Options} and adds them to the list of arguments
8359 presented to the linker.
8360
8361 @ifset vms
8362 @command{gnatlink} accepts the following types of extra files on the command
8363 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
8364 options files (.OPT). These are recognized and handled according to their
8365 extension.
8366 @end ifset
8367
8368 @node Switches for gnatlink
8369 @section Switches for @command{gnatlink}
8370
8371 @noindent
8372 The following switches are available with the @command{gnatlink} utility:
8373
8374 @table @option
8375 @c !sort!
8376
8377 @item --version
8378 @cindex @option{--version} @command{gnatlink}
8379 Display Copyright and version, then exit disregarding all other options.
8380
8381 @item --help
8382 @cindex @option{--help} @command{gnatlink}
8383 If @option{--version} was not used, display usage, then exit disregarding
8384 all other options.
8385
8386 @item ^-A^/BIND_FILE=ADA^
8387 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8388 The binder has generated code in Ada. This is the default.
8389
8390 @item ^-C^/BIND_FILE=C^
8391 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8392 If instead of generating a file in Ada, the binder has generated one in
8393 C, then the linker needs to know about it. Use this switch to signal
8394 to @command{gnatlink} that the binder has generated C code rather than
8395 Ada code.
8396
8397 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8398 @cindex Command line length
8399 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8400 On some targets, the command line length is limited, and @command{gnatlink}
8401 will generate a separate file for the linker if the list of object files
8402 is too long.
8403 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8404 to be generated even if
8405 the limit is not exceeded. This is useful in some cases to deal with
8406 special situations where the command line length is exceeded.
8407
8408 @item ^-g^/DEBUG^
8409 @cindex Debugging information, including
8410 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8411 The option to include debugging information causes the Ada bind file (in
8412 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8413 @option{^-g^/DEBUG^}.
8414 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8415 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8416 Without @option{^-g^/DEBUG^}, the binder removes these files by
8417 default. The same procedure apply if a C bind file was generated using
8418 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8419 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8420
8421 @item ^-n^/NOCOMPILE^
8422 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8423 Do not compile the file generated by the binder. This may be used when
8424 a link is rerun with different options, but there is no need to recompile
8425 the binder file.
8426
8427 @item ^-v^/VERBOSE^
8428 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8429 Causes additional information to be output, including a full list of the
8430 included object files. This switch option is most useful when you want
8431 to see what set of object files are being used in the link step.
8432
8433 @item ^-v -v^/VERBOSE/VERBOSE^
8434 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8435 Very verbose mode. Requests that the compiler operate in verbose mode when
8436 it compiles the binder file, and that the system linker run in verbose mode.
8437
8438 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8439 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8440 @var{exec-name} specifies an alternate name for the generated
8441 executable program. If this switch is omitted, the executable has the same
8442 name as the main unit. For example, @code{gnatlink try.ali} creates
8443 an executable called @file{^try^TRY.EXE^}.
8444
8445 @ifclear vms
8446 @item -b @var{target}
8447 @cindex @option{-b} (@command{gnatlink})
8448 Compile your program to run on @var{target}, which is the name of a
8449 system configuration. You must have a GNAT cross-compiler built if
8450 @var{target} is not the same as your host system.
8451
8452 @item -B@var{dir}
8453 @cindex @option{-B} (@command{gnatlink})
8454 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8455 from @var{dir} instead of the default location. Only use this switch
8456 when multiple versions of the GNAT compiler are available. See the
8457 @command{gcc} manual page for further details. You would normally use the
8458 @option{-b} or @option{-V} switch instead.
8459
8460 @item --GCC=@var{compiler_name}
8461 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8462 Program used for compiling the binder file. The default is
8463 @command{gcc}. You need to use quotes around @var{compiler_name} if
8464 @code{compiler_name} contains spaces or other separator characters.
8465 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8466 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8467 inserted after your command name. Thus in the above example the compiler
8468 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8469 A limitation of this syntax is that the name and path name of the executable
8470 itself must not include any embedded spaces. If several
8471 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8472 is taken into account. However, all the additional switches are also taken
8473 into account. Thus,
8474 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8475 @option{--GCC="bar -x -y -z -t"}.
8476
8477 @item --LINK=@var{name}
8478 @cindex @option{--LINK=} (@command{gnatlink})
8479 @var{name} is the name of the linker to be invoked. This is especially
8480 useful in mixed language programs since languages such as C++ require
8481 their own linker to be used. When this switch is omitted, the default
8482 name for the linker is @command{gcc}. When this switch is used, the
8483 specified linker is called instead of @command{gcc} with exactly the same
8484 parameters that would have been passed to @command{gcc} so if the desired
8485 linker requires different parameters it is necessary to use a wrapper
8486 script that massages the parameters before invoking the real linker. It
8487 may be useful to control the exact invocation by using the verbose
8488 switch.
8489
8490 @end ifclear
8491
8492 @ifset vms
8493 @item /DEBUG=TRACEBACK
8494 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8495 This qualifier causes sufficient information to be included in the
8496 executable file to allow a traceback, but does not include the full
8497 symbol information needed by the debugger.
8498
8499 @item /IDENTIFICATION="<string>"
8500 @code{"<string>"} specifies the string to be stored in the image file
8501 identification field in the image header.
8502 It overrides any pragma @code{Ident} specified string.
8503
8504 @item /NOINHIBIT-EXEC
8505 Generate the executable file even if there are linker warnings.
8506
8507 @item /NOSTART_FILES
8508 Don't link in the object file containing the ``main'' transfer address.
8509 Used when linking with a foreign language main program compiled with an
8510 HP compiler.
8511
8512 @item /STATIC
8513 Prefer linking with object libraries over sharable images, even without
8514 /DEBUG.
8515 @end ifset
8516
8517 @end table
8518
8519 @node The GNAT Make Program gnatmake
8520 @chapter The GNAT Make Program @command{gnatmake}
8521 @findex gnatmake
8522
8523 @menu
8524 * Running gnatmake::
8525 * Switches for gnatmake::
8526 * Mode Switches for gnatmake::
8527 * Notes on the Command Line::
8528 * How gnatmake Works::
8529 * Examples of gnatmake Usage::
8530 @end menu
8531 @noindent
8532 A typical development cycle when working on an Ada program consists of
8533 the following steps:
8534
8535 @enumerate
8536 @item
8537 Edit some sources to fix bugs.
8538
8539 @item
8540 Add enhancements.
8541
8542 @item
8543 Compile all sources affected.
8544
8545 @item
8546 Rebind and relink.
8547
8548 @item
8549 Test.
8550 @end enumerate
8551
8552 @noindent
8553 The third step can be tricky, because not only do the modified files
8554 @cindex Dependency rules
8555 have to be compiled, but any files depending on these files must also be
8556 recompiled. The dependency rules in Ada can be quite complex, especially
8557 in the presence of overloading, @code{use} clauses, generics and inlined
8558 subprograms.
8559
8560 @command{gnatmake} automatically takes care of the third and fourth steps
8561 of this process. It determines which sources need to be compiled,
8562 compiles them, and binds and links the resulting object files.
8563
8564 Unlike some other Ada make programs, the dependencies are always
8565 accurately recomputed from the new sources. The source based approach of
8566 the GNAT compilation model makes this possible. This means that if
8567 changes to the source program cause corresponding changes in
8568 dependencies, they will always be tracked exactly correctly by
8569 @command{gnatmake}.
8570
8571 @node Running gnatmake
8572 @section Running @command{gnatmake}
8573
8574 @noindent
8575 The usual form of the @command{gnatmake} command is
8576
8577 @smallexample
8578 $ gnatmake [@var{switches}] @var{file_name}
8579       [@var{file_names}] [@var{mode_switches}]
8580 @end smallexample
8581
8582 @noindent
8583 The only required argument is one @var{file_name}, which specifies
8584 a compilation unit that is a main program. Several @var{file_names} can be
8585 specified: this will result in several executables being built.
8586 If @code{switches} are present, they can be placed before the first
8587 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8588 If @var{mode_switches} are present, they must always be placed after
8589 the last @var{file_name} and all @code{switches}.
8590
8591 If you are using standard file extensions (.adb and .ads), then the
8592 extension may be omitted from the @var{file_name} arguments. However, if
8593 you are using non-standard extensions, then it is required that the
8594 extension be given. A relative or absolute directory path can be
8595 specified in a @var{file_name}, in which case, the input source file will
8596 be searched for in the specified directory only. Otherwise, the input
8597 source file will first be searched in the directory where
8598 @command{gnatmake} was invoked and if it is not found, it will be search on
8599 the source path of the compiler as described in
8600 @ref{Search Paths and the Run-Time Library (RTL)}.
8601
8602 All @command{gnatmake} output (except when you specify
8603 @option{^-M^/DEPENDENCIES_LIST^}) is to
8604 @file{stderr}. The output produced by the
8605 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8606 @file{stdout}.
8607
8608 @node Switches for gnatmake
8609 @section Switches for @command{gnatmake}
8610
8611 @noindent
8612 You may specify any of the following switches to @command{gnatmake}:
8613
8614 @table @option
8615 @c !sort!
8616
8617 @item --version
8618 @cindex @option{--version} @command{gnatmake}
8619 Display Copyright and version, then exit disregarding all other options.
8620
8621 @item --help
8622 @cindex @option{--help} @command{gnatmake}
8623 If @option{--version} was not used, display usage, then exit disregarding
8624 all other options.
8625
8626 @ifclear vms
8627 @item --GCC=@var{compiler_name}
8628 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8629 Program used for compiling. The default is `@command{gcc}'. You need to use
8630 quotes around @var{compiler_name} if @code{compiler_name} contains
8631 spaces or other separator characters. As an example @option{--GCC="foo -x
8632 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8633 compiler. A limitation of this syntax is that the name and path name of
8634 the executable itself must not include any embedded spaces. Note that
8635 switch @option{-c} is always inserted after your command name. Thus in the
8636 above example the compiler command that will be used by @command{gnatmake}
8637 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
8638 used, only the last @var{compiler_name} is taken into account. However,
8639 all the additional switches are also taken into account. Thus,
8640 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8641 @option{--GCC="bar -x -y -z -t"}.
8642
8643 @item --GNATBIND=@var{binder_name}
8644 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8645 Program used for binding. The default is `@code{gnatbind}'. You need to
8646 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8647 or other separator characters. As an example @option{--GNATBIND="bar -x
8648 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8649 binder. Binder switches that are normally appended by @command{gnatmake}
8650 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8651 A limitation of this syntax is that the name and path name of the executable
8652 itself must not include any embedded spaces.
8653
8654 @item --GNATLINK=@var{linker_name}
8655 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8656 Program used for linking. The default is `@command{gnatlink}'. You need to
8657 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8658 or other separator characters. As an example @option{--GNATLINK="lan -x
8659 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8660 linker. Linker switches that are normally appended by @command{gnatmake} to
8661 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8662 A limitation of this syntax is that the name and path name of the executable
8663 itself must not include any embedded spaces.
8664
8665 @end ifclear
8666
8667 @item ^-a^/ALL_FILES^
8668 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8669 Consider all files in the make process, even the GNAT internal system
8670 files (for example, the predefined Ada library files), as well as any
8671 locked files. Locked files are files whose ALI file is write-protected.
8672 By default,
8673 @command{gnatmake} does not check these files,
8674 because the assumption is that the GNAT internal files are properly up
8675 to date, and also that any write protected ALI files have been properly
8676 installed. Note that if there is an installation problem, such that one
8677 of these files is not up to date, it will be properly caught by the
8678 binder.
8679 You may have to specify this switch if you are working on GNAT
8680 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8681 in conjunction with @option{^-f^/FORCE_COMPILE^}
8682 if you need to recompile an entire application,
8683 including run-time files, using special configuration pragmas,
8684 such as a @code{Normalize_Scalars} pragma.
8685
8686 By default
8687 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8688 internal files with
8689 @ifclear vms
8690 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8691 @end ifclear
8692 @ifset vms
8693 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8694 @end ifset
8695
8696 @item ^-b^/ACTIONS=BIND^
8697 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8698 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8699 compilation and binding, but no link.
8700 Can be combined with @option{^-l^/ACTIONS=LINK^}
8701 to do binding and linking. When not combined with
8702 @option{^-c^/ACTIONS=COMPILE^}
8703 all the units in the closure of the main program must have been previously
8704 compiled and must be up to date. The root unit specified by @var{file_name}
8705 may be given without extension, with the source extension or, if no GNAT
8706 Project File is specified, with the ALI file extension.
8707
8708 @item ^-c^/ACTIONS=COMPILE^
8709 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8710 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8711 is also specified. Do not perform linking, except if both
8712 @option{^-b^/ACTIONS=BIND^} and
8713  @option{^-l^/ACTIONS=LINK^} are also specified.
8714 If the root unit specified by @var{file_name} is not a main unit, this is the
8715 default. Otherwise @command{gnatmake} will attempt binding and linking
8716 unless all objects are up to date and the executable is more recent than
8717 the objects.
8718
8719 @item ^-C^/MAPPING^
8720 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8721 Use a temporary mapping file. A mapping file is a way to communicate to the
8722 compiler two mappings: from unit names to file names (without any directory
8723 information) and from file names to path names (with full directory
8724 information). These mappings are used by the compiler to short-circuit the path
8725 search. When @command{gnatmake} is invoked with this switch, it will create
8726 a temporary mapping file, initially populated by the project manager,
8727 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8728 Each invocation of the compiler will add the newly accessed sources to the
8729 mapping file. This will improve the source search during the next invocation
8730 of the compiler.
8731
8732 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8733 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8734 Use a specific mapping file. The file, specified as a path name (absolute or
8735 relative) by this switch, should already exist, otherwise the switch is
8736 ineffective. The specified mapping file will be communicated to the compiler.
8737 This switch is not compatible with a project file
8738 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8739 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8740
8741 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8742 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8743 Put all object files and ALI file in directory @var{dir}.
8744 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8745 and ALI files go in the current working directory.
8746
8747 This switch cannot be used when using a project file.
8748
8749 @ifclear vms
8750 @item -eL
8751 @cindex @option{-eL} (@command{gnatmake})
8752 Follow all symbolic links when processing project files.
8753 @end ifclear
8754
8755 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
8756 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
8757 Output the commands for the compiler, the binder and the linker
8758 on ^standard output^SYS$OUTPUT^,
8759 instead of ^standard error^SYS$ERROR^.
8760
8761 @item ^-f^/FORCE_COMPILE^
8762 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
8763 Force recompilations. Recompile all sources, even though some object
8764 files may be up to date, but don't recompile predefined or GNAT internal
8765 files or locked files (files with a write-protected ALI file),
8766 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8767
8768 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8769 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
8770 When using project files, if some errors or warnings are detected during
8771 parsing and verbose mode is not in effect (no use of switch
8772 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8773 file, rather than its simple file name.
8774
8775 @item ^-g^/DEBUG^
8776 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
8777 Enable debugging. This switch is simply passed to the compiler and to the
8778 linker.
8779
8780 @item ^-i^/IN_PLACE^
8781 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
8782 In normal mode, @command{gnatmake} compiles all object files and ALI files
8783 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8784 then instead object files and ALI files that already exist are overwritten
8785 in place. This means that once a large project is organized into separate
8786 directories in the desired manner, then @command{gnatmake} will automatically
8787 maintain and update this organization. If no ALI files are found on the
8788 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8789 the new object and ALI files are created in the
8790 directory containing the source being compiled. If another organization
8791 is desired, where objects and sources are kept in different directories,
8792 a useful technique is to create dummy ALI files in the desired directories.
8793 When detecting such a dummy file, @command{gnatmake} will be forced to
8794 recompile the corresponding source file, and it will be put the resulting
8795 object and ALI files in the directory where it found the dummy file.
8796
8797 @item ^-j^/PROCESSES=^@var{n}
8798 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
8799 @cindex Parallel make
8800 Use @var{n} processes to carry out the (re)compilations. On a
8801 multiprocessor machine compilations will occur in parallel. In the
8802 event of compilation errors, messages from various compilations might
8803 get interspersed (but @command{gnatmake} will give you the full ordered
8804 list of failing compiles at the end). If this is problematic, rerun
8805 the make process with n set to 1 to get a clean list of messages.
8806
8807 @item ^-k^/CONTINUE_ON_ERROR^
8808 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
8809 Keep going. Continue as much as possible after a compilation error. To
8810 ease the programmer's task in case of compilation errors, the list of
8811 sources for which the compile fails is given when @command{gnatmake}
8812 terminates.
8813
8814 If @command{gnatmake} is invoked with several @file{file_names} and with this
8815 switch, if there are compilation errors when building an executable,
8816 @command{gnatmake} will not attempt to build the following executables.
8817
8818 @item ^-l^/ACTIONS=LINK^
8819 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
8820 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8821 and linking. Linking will not be performed if combined with
8822 @option{^-c^/ACTIONS=COMPILE^}
8823 but not with @option{^-b^/ACTIONS=BIND^}.
8824 When not combined with @option{^-b^/ACTIONS=BIND^}
8825 all the units in the closure of the main program must have been previously
8826 compiled and must be up to date, and the main program needs to have been bound.
8827 The root unit specified by @var{file_name}
8828 may be given without extension, with the source extension or, if no GNAT
8829 Project File is specified, with the ALI file extension.
8830
8831 @item ^-m^/MINIMAL_RECOMPILATION^
8832 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
8833 Specify that the minimum necessary amount of recompilations
8834 be performed. In this mode @command{gnatmake} ignores time
8835 stamp differences when the only
8836 modifications to a source file consist in adding/removing comments,
8837 empty lines, spaces or tabs. This means that if you have changed the
8838 comments in a source file or have simply reformatted it, using this
8839 switch will tell gnatmake not to recompile files that depend on it
8840 (provided other sources on which these files depend have undergone no
8841 semantic modifications). Note that the debugging information may be
8842 out of date with respect to the sources if the @option{-m} switch causes
8843 a compilation to be switched, so the use of this switch represents a
8844 trade-off between compilation time and accurate debugging information.
8845
8846 @item ^-M^/DEPENDENCIES_LIST^
8847 @cindex Dependencies, producing list
8848 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
8849 Check if all objects are up to date. If they are, output the object
8850 dependences to @file{stdout} in a form that can be directly exploited in
8851 a @file{Makefile}. By default, each source file is prefixed with its
8852 (relative or absolute) directory name. This name is whatever you
8853 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8854 and @option{^-I^/SEARCH^} switches. If you use
8855 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8856 @option{^-q^/QUIET^}
8857 (see below), only the source file names,
8858 without relative paths, are output. If you just specify the
8859 @option{^-M^/DEPENDENCIES_LIST^}
8860 switch, dependencies of the GNAT internal system files are omitted. This
8861 is typically what you want. If you also specify
8862 the @option{^-a^/ALL_FILES^} switch,
8863 dependencies of the GNAT internal files are also listed. Note that
8864 dependencies of the objects in external Ada libraries (see switch
8865 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8866 are never reported.
8867
8868 @item ^-n^/DO_OBJECT_CHECK^
8869 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
8870 Don't compile, bind, or link. Checks if all objects are up to date.
8871 If they are not, the full name of the first file that needs to be
8872 recompiled is printed.
8873 Repeated use of this option, followed by compiling the indicated source
8874 file, will eventually result in recompiling all required units.
8875
8876 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8877 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
8878 Output executable name. The name of the final executable program will be
8879 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8880 name for the executable will be the name of the input file in appropriate form
8881 for an executable file on the host system.
8882
8883 This switch cannot be used when invoking @command{gnatmake} with several
8884 @file{file_names}.
8885
8886 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
8887 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
8888 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
8889 automatically missing object directories, library directories and exec
8890 directories.
8891
8892 @item ^-P^/PROJECT_FILE=^@var{project}
8893 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
8894 Use project file @var{project}. Only one such switch can be used.
8895 @xref{gnatmake and Project Files}.
8896
8897 @item ^-q^/QUIET^
8898 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
8899 Quiet. When this flag is not set, the commands carried out by
8900 @command{gnatmake} are displayed.
8901
8902 @item ^-s^/SWITCH_CHECK/^
8903 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
8904 Recompile if compiler switches have changed since last compilation.
8905 All compiler switches but -I and -o are taken into account in the
8906 following way:
8907 orders between different ``first letter'' switches are ignored, but
8908 orders between same switches are taken into account. For example,
8909 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8910 is equivalent to @option{-O -g}.
8911
8912 This switch is recommended when Integrated Preprocessing is used.
8913
8914 @item ^-u^/UNIQUE^
8915 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
8916 Unique. Recompile at most the main files. It implies -c. Combined with
8917 -f, it is equivalent to calling the compiler directly. Note that using
8918 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8919 (@pxref{Project Files and Main Subprograms}).
8920
8921 @item ^-U^/ALL_PROJECTS^
8922 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
8923 When used without a project file or with one or several mains on the command
8924 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8925 on the command line, all sources of all project files are checked and compiled
8926 if not up to date, and libraries are rebuilt, if necessary.
8927
8928 @item ^-v^/REASONS^
8929 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
8930 Verbose. Display the reason for all recompilations @command{gnatmake}
8931 decides are necessary, with the highest verbosity level.
8932
8933 @item ^-vl^/LOW_VERBOSITY^
8934 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
8935 Verbosity level Low. Display fewer lines than in verbosity Medium.
8936
8937 @item ^-vm^/MEDIUM_VERBOSITY^
8938 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
8939 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
8940
8941 @item ^-vh^/HIGH_VERBOSITY^
8942 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
8943 Verbosity level High. Equivalent to ^-v^/REASONS^.
8944
8945 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8946 Indicate the verbosity of the parsing of GNAT project files.
8947 @xref{Switches Related to Project Files}.
8948
8949 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8950 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
8951 Indicate that sources that are not part of any Project File may be compiled.
8952 Normally, when using Project Files, only sources that are part of a Project
8953 File may be compile. When this switch is used, a source outside of all Project
8954 Files may be compiled. The ALI file and the object file will be put in the
8955 object directory of the main Project. The compilation switches used will only
8956 be those specified on the command line.
8957
8958 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8959 Indicate that external variable @var{name} has the value @var{value}.
8960 The Project Manager will use this value for occurrences of
8961 @code{external(name)} when parsing the project file.
8962 @xref{Switches Related to Project Files}.
8963
8964 @item ^-z^/NOMAIN^
8965 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
8966 No main subprogram. Bind and link the program even if the unit name
8967 given on the command line is a package name. The resulting executable
8968 will execute the elaboration routines of the package and its closure,
8969 then the finalization routines.
8970
8971 @end table
8972
8973 @table @asis
8974 @item @command{gcc} @asis{switches}
8975 @ifclear vms
8976 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
8977 is passed to @command{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8978 @end ifclear
8979 @ifset vms
8980 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8981 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8982 automatically treated as a compiler switch, and passed on to all
8983 compilations that are carried out.
8984 @end ifset
8985 @end table
8986
8987 @noindent
8988 Source and library search path switches:
8989
8990 @table @option
8991 @c !sort!
8992 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8993 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
8994 When looking for source files also look in directory @var{dir}.
8995 The order in which source files search is undertaken is
8996 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8997
8998 @item ^-aL^/SKIP_MISSING=^@var{dir}
8999 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9000 Consider @var{dir} as being an externally provided Ada library.
9001 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9002 files have been located in directory @var{dir}. This allows you to have
9003 missing bodies for the units in @var{dir} and to ignore out of date bodies
9004 for the same units. You still need to specify
9005 the location of the specs for these units by using the switches
9006 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9007 or @option{^-I^/SEARCH=^@var{dir}}.
9008 Note: this switch is provided for compatibility with previous versions
9009 of @command{gnatmake}. The easier method of causing standard libraries
9010 to be excluded from consideration is to write-protect the corresponding
9011 ALI files.
9012
9013 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9014 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9015 When searching for library and object files, look in directory
9016 @var{dir}. The order in which library files are searched is described in
9017 @ref{Search Paths for gnatbind}.
9018
9019 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9020 @cindex Search paths, for @command{gnatmake}
9021 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9022 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9023 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9024
9025 @item ^-I^/SEARCH=^@var{dir}
9026 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9027 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9028 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9029
9030 @item ^-I-^/NOCURRENT_DIRECTORY^
9031 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9032 @cindex Source files, suppressing search
9033 Do not look for source files in the directory containing the source
9034 file named in the command line.
9035 Do not look for ALI or object files in the directory
9036 where @command{gnatmake} was invoked.
9037
9038 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9039 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9040 @cindex Linker libraries
9041 Add directory @var{dir} to the list of directories in which the linker
9042 will search for libraries. This is equivalent to
9043 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9044 @ifclear vms
9045 Furthermore, under Windows, the sources pointed to by the libraries path
9046 set in the registry are not searched for.
9047 @end ifclear
9048
9049 @item -nostdinc
9050 @cindex @option{-nostdinc} (@command{gnatmake})
9051 Do not look for source files in the system default directory.
9052
9053 @item -nostdlib
9054 @cindex @option{-nostdlib} (@command{gnatmake})
9055 Do not look for library files in the system default directory.
9056
9057 @item --RTS=@var{rts-path}
9058 @cindex @option{--RTS} (@command{gnatmake})
9059 Specifies the default location of the runtime library. GNAT looks for the
9060 runtime
9061 in the following directories, and stops as soon as a valid runtime is found
9062 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9063 @file{ada_object_path} present):
9064
9065 @itemize @bullet
9066 @item <current directory>/$rts_path
9067
9068 @item <default-search-dir>/$rts_path
9069
9070 @item <default-search-dir>/rts-$rts_path
9071 @end itemize
9072
9073 @noindent
9074 The selected path is handled like a normal RTS path.
9075
9076 @end table
9077
9078 @node Mode Switches for gnatmake
9079 @section Mode Switches for @command{gnatmake}
9080
9081 @noindent
9082 The mode switches (referred to as @code{mode_switches}) allow the
9083 inclusion of switches that are to be passed to the compiler itself, the
9084 binder or the linker. The effect of a mode switch is to cause all
9085 subsequent switches up to the end of the switch list, or up to the next
9086 mode switch, to be interpreted as switches to be passed on to the
9087 designated component of GNAT.
9088
9089 @table @option
9090 @c !sort!
9091 @item -cargs @var{switches}
9092 @cindex @option{-cargs} (@command{gnatmake})
9093 Compiler switches. Here @var{switches} is a list of switches
9094 that are valid switches for @command{gcc}. They will be passed on to
9095 all compile steps performed by @command{gnatmake}.
9096
9097 @item -bargs @var{switches}
9098 @cindex @option{-bargs} (@command{gnatmake})
9099 Binder switches. Here @var{switches} is a list of switches
9100 that are valid switches for @code{gnatbind}. They will be passed on to
9101 all bind steps performed by @command{gnatmake}.
9102
9103 @item -largs @var{switches}
9104 @cindex @option{-largs} (@command{gnatmake})
9105 Linker switches. Here @var{switches} is a list of switches
9106 that are valid switches for @command{gnatlink}. They will be passed on to
9107 all link steps performed by @command{gnatmake}.
9108
9109 @item -margs @var{switches}
9110 @cindex @option{-margs} (@command{gnatmake})
9111 Make switches. The switches are directly interpreted by @command{gnatmake},
9112 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9113 or @option{-largs}.
9114 @end table
9115
9116 @node Notes on the Command Line
9117 @section Notes on the Command Line
9118
9119 @noindent
9120 This section contains some additional useful notes on the operation
9121 of the @command{gnatmake} command.
9122
9123 @itemize @bullet
9124 @item
9125 @cindex Recompilation, by @command{gnatmake}
9126 If @command{gnatmake} finds no ALI files, it recompiles the main program
9127 and all other units required by the main program.
9128 This means that @command{gnatmake}
9129 can be used for the initial compile, as well as during subsequent steps of
9130 the development cycle.
9131
9132 @item
9133 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9134 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9135 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9136 warning.
9137
9138 @item
9139 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9140 is used to specify both source and
9141 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9142 instead if you just want to specify
9143 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9144 if you want to specify library paths
9145 only.
9146
9147 @item
9148 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9149 This may conveniently be used to exclude standard libraries from
9150 consideration and in particular it means that the use of the
9151 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9152 unless @option{^-a^/ALL_FILES^} is also specified.
9153
9154 @item
9155 @command{gnatmake} has been designed to make the use of Ada libraries
9156 particularly convenient. Assume you have an Ada library organized
9157 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9158 of your Ada compilation units,
9159 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9160 specs of these units, but no bodies. Then to compile a unit
9161 stored in @code{main.adb}, which uses this Ada library you would just type
9162
9163 @smallexample
9164 @ifclear vms
9165 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9166 @end ifclear
9167 @ifset vms
9168 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9169            /SKIP_MISSING=@i{[OBJ_DIR]} main
9170 @end ifset
9171 @end smallexample
9172
9173 @item
9174 Using @command{gnatmake} along with the
9175 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9176 switch provides a mechanism for avoiding unnecessary rcompilations. Using
9177 this switch,
9178 you can update the comments/format of your
9179 source files without having to recompile everything. Note, however, that
9180 adding or deleting lines in a source files may render its debugging
9181 info obsolete. If the file in question is a spec, the impact is rather
9182 limited, as that debugging info will only be useful during the
9183 elaboration phase of your program. For bodies the impact can be more
9184 significant. In all events, your debugger will warn you if a source file
9185 is more recent than the corresponding object, and alert you to the fact
9186 that the debugging information may be out of date.
9187 @end itemize
9188
9189 @node How gnatmake Works
9190 @section How @command{gnatmake} Works
9191
9192 @noindent
9193 Generally @command{gnatmake} automatically performs all necessary
9194 recompilations and you don't need to worry about how it works. However,
9195 it may be useful to have some basic understanding of the @command{gnatmake}
9196 approach and in particular to understand how it uses the results of
9197 previous compilations without incorrectly depending on them.
9198
9199 First a definition: an object file is considered @dfn{up to date} if the
9200 corresponding ALI file exists and if all the source files listed in the
9201 dependency section of this ALI file have time stamps matching those in
9202 the ALI file. This means that neither the source file itself nor any
9203 files that it depends on have been modified, and hence there is no need
9204 to recompile this file.
9205
9206 @command{gnatmake} works by first checking if the specified main unit is up
9207 to date. If so, no compilations are required for the main unit. If not,
9208 @command{gnatmake} compiles the main program to build a new ALI file that
9209 reflects the latest sources. Then the ALI file of the main unit is
9210 examined to find all the source files on which the main program depends,
9211 and @command{gnatmake} recursively applies the above procedure on all these
9212 files.
9213
9214 This process ensures that @command{gnatmake} only trusts the dependencies
9215 in an existing ALI file if they are known to be correct. Otherwise it
9216 always recompiles to determine a new, guaranteed accurate set of
9217 dependencies. As a result the program is compiled ``upside down'' from what may
9218 be more familiar as the required order of compilation in some other Ada
9219 systems. In particular, clients are compiled before the units on which
9220 they depend. The ability of GNAT to compile in any order is critical in
9221 allowing an order of compilation to be chosen that guarantees that
9222 @command{gnatmake} will recompute a correct set of new dependencies if
9223 necessary.
9224
9225 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9226 imported by several of the executables, it will be recompiled at most once.
9227
9228 Note: when using non-standard naming conventions
9229 (@pxref{Using Other File Names}), changing through a configuration pragmas
9230 file the version of a source and invoking @command{gnatmake} to recompile may
9231 have no effect, if the previous version of the source is still accessible
9232 by @command{gnatmake}. It may be necessary to use the switch
9233 ^-f^/FORCE_COMPILE^.
9234
9235 @node Examples of gnatmake Usage
9236 @section Examples of @command{gnatmake} Usage
9237
9238 @table @code
9239 @item gnatmake hello.adb
9240 Compile all files necessary to bind and link the main program
9241 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9242 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9243
9244 @item gnatmake main1 main2 main3
9245 Compile all files necessary to bind and link the main programs
9246 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9247 (containing unit @code{Main2}) and @file{main3.adb}
9248 (containing unit @code{Main3}) and bind and link the resulting object files
9249 to generate three executable files @file{^main1^MAIN1.EXE^},
9250 @file{^main2^MAIN2.EXE^}
9251 and @file{^main3^MAIN3.EXE^}.
9252
9253 @ifclear vms
9254 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9255 @end ifclear
9256
9257 @ifset vms
9258 @item gnatmake Main_Unit /QUIET
9259    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9260    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9261 @end ifset
9262 Compile all files necessary to bind and link the main program unit
9263 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9264 be done with optimization level 2 and the order of elaboration will be
9265 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9266 displaying commands it is executing.
9267 @end table
9268
9269 @c *************************
9270 @node Improving Performance
9271 @chapter Improving Performance
9272 @cindex Improving performance
9273
9274 @noindent
9275 This chapter presents several topics related to program performance.
9276 It first describes some of the tradeoffs that need to be considered
9277 and some of the techniques for making your program run faster.
9278 It then documents the @command{gnatelim} tool and unused subprogram/data
9279 elimination feature, which can reduce the size of program executables.
9280
9281 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9282 driver (see @ref{The GNAT Driver and Project Files}).
9283
9284 @ifnottex
9285 @menu
9286 * Performance Considerations::
9287 * Reducing Size of Ada Executables with gnatelim::
9288 * Reducing Size of Executables with unused subprogram/data elimination::
9289 @end menu
9290 @end ifnottex
9291
9292 @c *****************************
9293 @node Performance Considerations
9294 @section Performance Considerations
9295
9296 @noindent
9297 The GNAT system provides a number of options that allow a trade-off
9298 between
9299
9300 @itemize @bullet
9301 @item
9302 performance of the generated code
9303
9304 @item
9305 speed of compilation
9306
9307 @item
9308 minimization of dependences and recompilation
9309
9310 @item
9311 the degree of run-time checking.
9312 @end itemize
9313
9314 @noindent
9315 The defaults (if no options are selected) aim at improving the speed
9316 of compilation and minimizing dependences, at the expense of performance
9317 of the generated code:
9318
9319 @itemize @bullet
9320 @item
9321 no optimization
9322
9323 @item
9324 no inlining of subprogram calls
9325
9326 @item
9327 all run-time checks enabled except overflow and elaboration checks
9328 @end itemize
9329
9330 @noindent
9331 These options are suitable for most program development purposes. This
9332 chapter describes how you can modify these choices, and also provides
9333 some guidelines on debugging optimized code.
9334
9335 @menu
9336 * Controlling Run-Time Checks::
9337 * Use of Restrictions::
9338 * Optimization Levels::
9339 * Debugging Optimized Code::
9340 * Inlining of Subprograms::
9341 * Other Optimization Switches::
9342 * Optimization and Strict Aliasing::
9343
9344 @ifset vms
9345 * Coverage Analysis::
9346 @end ifset
9347 @end menu
9348
9349 @node Controlling Run-Time Checks
9350 @subsection Controlling Run-Time Checks
9351
9352 @noindent
9353 By default, GNAT generates all run-time checks, except arithmetic overflow
9354 checking for integer operations and checks for access before elaboration on
9355 subprogram calls. The latter are not required in default mode, because all
9356 necessary checking is done at compile time.
9357 @cindex @option{-gnatp} (@command{gcc})
9358 @cindex @option{-gnato} (@command{gcc})
9359 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9360 be modified. @xref{Run-Time Checks}.
9361
9362 Our experience is that the default is suitable for most development
9363 purposes.
9364
9365 We treat integer overflow specially because these
9366 are quite expensive and in our experience are not as important as other
9367 run-time checks in the development process. Note that division by zero
9368 is not considered an overflow check, and divide by zero checks are
9369 generated where required by default.
9370
9371 Elaboration checks are off by default, and also not needed by default, since
9372 GNAT uses a static elaboration analysis approach that avoids the need for
9373 run-time checking. This manual contains a full chapter discussing the issue
9374 of elaboration checks, and if the default is not satisfactory for your use,
9375 you should read this chapter.
9376
9377 For validity checks, the minimal checks required by the Ada Reference
9378 Manual (for case statements and assignments to array elements) are on
9379 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9380 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9381 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9382 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9383 are also suppressed entirely if @option{-gnatp} is used.
9384
9385 @cindex Overflow checks
9386 @cindex Checks, overflow
9387 @findex Suppress
9388 @findex Unsuppress
9389 @cindex pragma Suppress
9390 @cindex pragma Unsuppress
9391 Note that the setting of the switches controls the default setting of
9392 the checks. They may be modified using either @code{pragma Suppress} (to
9393 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9394 checks) in the program source.
9395
9396 @node Use of Restrictions
9397 @subsection Use of Restrictions
9398
9399 @noindent
9400 The use of pragma Restrictions allows you to control which features are
9401 permitted in your program. Apart from the obvious point that if you avoid
9402 relatively expensive features like finalization (enforceable by the use
9403 of pragma Restrictions (No_Finalization), the use of this pragma does not
9404 affect the generated code in most cases.
9405
9406 One notable exception to this rule is that the possibility of task abort
9407 results in some distributed overhead, particularly if finalization or
9408 exception handlers are used. The reason is that certain sections of code
9409 have to be marked as non-abortable.
9410
9411 If you use neither the @code{abort} statement, nor asynchronous transfer
9412 of control (@code{select .. then abort}), then this distributed overhead
9413 is removed, which may have a general positive effect in improving
9414 overall performance.  Especially code involving frequent use of tasking
9415 constructs and controlled types will show much improved performance.
9416 The relevant restrictions pragmas are
9417
9418 @smallexample @c ada
9419    pragma Restrictions (No_Abort_Statements);
9420    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9421 @end smallexample
9422
9423 @noindent
9424 It is recommended that these restriction pragmas be used if possible. Note
9425 that this also means that you can write code without worrying about the
9426 possibility of an immediate abort at any point.
9427
9428 @node Optimization Levels
9429 @subsection Optimization Levels
9430 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9431
9432 @noindent
9433 The default is optimization off. This results in the fastest compile
9434 times, but GNAT makes absolutely no attempt to optimize, and the
9435 generated programs are considerably larger and slower than when
9436 optimization is enabled. You can use the
9437 @ifclear vms
9438 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9439 @option{-O2}, @option{-O3}, and @option{-Os})
9440 @end ifclear
9441 @ifset vms
9442 @code{OPTIMIZE} qualifier
9443 @end ifset
9444 to @command{gcc} to control the optimization level:
9445
9446 @table @option
9447 @item ^-O0^/OPTIMIZE=NONE^
9448 No optimization (the default);
9449 generates unoptimized code but has
9450 the fastest compilation time.
9451
9452 Note that many other compilers do fairly extensive optimization
9453 even if "no optimization" is specified. When using gcc, it is
9454 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9455 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9456 really does mean no optimization at all. This difference between
9457 gcc and other compilers should be kept in mind when doing
9458 performance comparisons.
9459
9460 @item ^-O1^/OPTIMIZE=SOME^
9461 Moderate optimization;
9462 optimizes reasonably well but does not
9463 degrade compilation time significantly.
9464
9465 @item ^-O2^/OPTIMIZE=ALL^
9466 @ifset vms
9467 @itemx /OPTIMIZE=DEVELOPMENT
9468 @end ifset
9469 Full optimization;
9470 generates highly optimized code and has
9471 the slowest compilation time.
9472
9473 @item ^-O3^/OPTIMIZE=INLINING^
9474 Full optimization as in @option{-O2},
9475 and also attempts automatic inlining of small
9476 subprograms within a unit (@pxref{Inlining of Subprograms}).
9477
9478 @item ^-Os^/OPTIMIZE=SPACE^
9479 Optimize space usage of resulting program.
9480 @end table
9481
9482 @noindent
9483 Higher optimization levels perform more global transformations on the
9484 program and apply more expensive analysis algorithms in order to generate
9485 faster and more compact code. The price in compilation time, and the
9486 resulting improvement in execution time,
9487 both depend on the particular application and the hardware environment.
9488 You should experiment to find the best level for your application.
9489
9490 The @option{^-Os^/OPTIMIZE=SPACE^} switch is independent of the time
9491 optimizations, so you can specify both @option{^-Os^/OPTIMIZE=SPACE^}
9492 and a time optimization on the same compile command.
9493
9494 Since the precise set of optimizations done at each level will vary from
9495 release to release (and sometime from target to target), it is best to think
9496 of the optimization settings in general terms.
9497 The @cite{Using GNU GCC} manual contains details about
9498 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9499 individually enable or disable specific optimizations.
9500
9501 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9502 been tested extensively at all optimization levels. There are some bugs
9503 which appear only with optimization turned on, but there have also been
9504 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9505 level of optimization does not improve the reliability of the code
9506 generator, which in practice is highly reliable at all optimization
9507 levels.
9508
9509 Note regarding the use of @option{-O3}: The use of this optimization level
9510 is generally discouraged with GNAT, since it often results in larger
9511 executables which run more slowly. See further discussion of this point
9512 in @ref{Inlining of Subprograms}.
9513
9514 @node Debugging Optimized Code
9515 @subsection Debugging Optimized Code
9516 @cindex Debugging optimized code
9517 @cindex Optimization and debugging
9518
9519 @noindent
9520 Although it is possible to do a reasonable amount of debugging at
9521 @ifclear vms
9522 nonzero optimization levels,
9523 the higher the level the more likely that
9524 @end ifclear
9525 @ifset vms
9526 @option{/OPTIMIZE} settings other than @code{NONE},
9527 such settings will make it more likely that
9528 @end ifset
9529 source-level constructs will have been eliminated by optimization.
9530 For example, if a loop is strength-reduced, the loop
9531 control variable may be completely eliminated and thus cannot be
9532 displayed in the debugger.
9533 This can only happen at @option{-O2} or @option{-O3}.
9534 Explicit temporary variables that you code might be eliminated at
9535 ^level^setting^ @option{-O1} or higher.
9536
9537 The use of the @option{^-g^/DEBUG^} switch,
9538 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9539 which is needed for source-level debugging,
9540 affects the size of the program executable on disk,
9541 and indeed the debugging information can be quite large.
9542 However, it has no effect on the generated code (and thus does not
9543 degrade performance)
9544
9545 Since the compiler generates debugging tables for a compilation unit before
9546 it performs optimizations, the optimizing transformations may invalidate some
9547 of the debugging data.  You therefore need to anticipate certain
9548 anomalous situations that may arise while debugging optimized code.
9549 These are the most common cases:
9550
9551 @enumerate
9552 @item
9553 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
9554 commands show
9555 the PC bouncing back and forth in the code.  This may result from any of
9556 the following optimizations:
9557
9558 @itemize @bullet
9559 @item
9560 @i{Common subexpression elimination:} using a single instance of code for a
9561 quantity that the source computes several times.  As a result you
9562 may not be able to stop on what looks like a statement.
9563
9564 @item
9565 @i{Invariant code motion:} moving an expression that does not change within a
9566 loop, to the beginning of the loop.
9567
9568 @item
9569 @i{Instruction scheduling:} moving instructions so as to
9570 overlap loads and stores (typically) with other code, or in
9571 general to move computations of values closer to their uses. Often
9572 this causes you to pass an assignment statement without the assignment
9573 happening and then later bounce back to the statement when the
9574 value is actually needed.  Placing a breakpoint on a line of code
9575 and then stepping over it may, therefore, not always cause all the
9576 expected side-effects.
9577 @end itemize
9578
9579 @item
9580 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9581 two identical pieces of code are merged and the program counter suddenly
9582 jumps to a statement that is not supposed to be executed, simply because
9583 it (and the code following) translates to the same thing as the code
9584 that @emph{was} supposed to be executed.  This effect is typically seen in
9585 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9586 a @code{break} in a C @code{^switch^switch^} statement.
9587
9588 @item
9589 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9590 There are various reasons for this effect:
9591
9592 @itemize @bullet
9593 @item
9594 In a subprogram prologue, a parameter may not yet have been moved to its
9595 ``home''.
9596
9597 @item
9598 A variable may be dead, and its register re-used.  This is
9599 probably the most common cause.
9600
9601 @item
9602 As mentioned above, the assignment of a value to a variable may
9603 have been moved.
9604
9605 @item
9606 A variable may be eliminated entirely by value propagation or
9607 other means.  In this case, GCC may incorrectly generate debugging
9608 information for the variable
9609 @end itemize
9610
9611 @noindent
9612 In general, when an unexpected value appears for a local variable or parameter
9613 you should first ascertain if that value was actually computed by
9614 your program, as opposed to being incorrectly reported by the debugger.
9615 Record fields or
9616 array elements in an object designated by an access value
9617 are generally less of a problem, once you have ascertained that the access
9618 value is sensible.
9619 Typically, this means checking variables in the preceding code and in the
9620 calling subprogram to verify that the value observed is explainable from other
9621 values (one must apply the procedure recursively to those
9622 other values); or re-running the code and stopping a little earlier
9623 (perhaps before the call) and stepping to better see how the variable obtained
9624 the value in question; or continuing to step @emph{from} the point of the
9625 strange value to see if code motion had simply moved the variable's
9626 assignments later.
9627 @end enumerate
9628
9629 @noindent
9630 In light of such anomalies, a recommended technique is to use @option{-O0}
9631 early in the software development cycle, when extensive debugging capabilities
9632 are most needed, and then move to @option{-O1} and later @option{-O2} as
9633 the debugger becomes less critical.
9634 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9635 a release management issue.
9636 @ifclear vms
9637 Note that if you use @option{-g} you can then use the @command{strip} program
9638 on the resulting executable,
9639 which removes both debugging information and global symbols.
9640 @end ifclear
9641
9642 @node Inlining of Subprograms
9643 @subsection Inlining of Subprograms
9644
9645 @noindent
9646 A call to a subprogram in the current unit is inlined if all the
9647 following conditions are met:
9648
9649 @itemize @bullet
9650 @item
9651 The optimization level is at least @option{-O1}.
9652
9653 @item
9654 The called subprogram is suitable for inlining: It must be small enough
9655 and not contain nested subprograms or anything else that @command{gcc}
9656 cannot support in inlined subprograms.
9657
9658 @item
9659 The call occurs after the definition of the body of the subprogram.
9660
9661 @item
9662 @cindex pragma Inline
9663 @findex Inline
9664 Either @code{pragma Inline} applies to the subprogram or it is
9665 small and automatic inlining (optimization level @option{-O3}) is
9666 specified.
9667 @end itemize
9668
9669 @noindent
9670 Calls to subprograms in @code{with}'ed units are normally not inlined.
9671 To achieve actual inlining (that is, replacement of the call by the code
9672 in the body of the subprogram), the following conditions must all be true.
9673
9674 @itemize @bullet
9675 @item
9676 The optimization level is at least @option{-O1}.
9677
9678 @item
9679 The called subprogram is suitable for inlining: It must be small enough
9680 and not contain nested subprograms or anything else @command{gcc} cannot
9681 support in inlined subprograms.
9682
9683 @item
9684 The call appears in a body (not in a package spec).
9685
9686 @item
9687 There is a @code{pragma Inline} for the subprogram.
9688
9689 @item
9690 @cindex @option{-gnatn} (@command{gcc})
9691 The @option{^-gnatn^/INLINE^} switch
9692 is used in the @command{gcc} command line
9693 @end itemize
9694
9695 Even if all these conditions are met, it may not be possible for
9696 the compiler to inline the call, due to the length of the body,
9697 or features in the body that make it impossible for the compiler
9698 to do the inlining.
9699
9700 Note that specifying the @option{-gnatn} switch causes additional
9701 compilation dependencies. Consider the following:
9702
9703 @smallexample @c ada
9704 @cartouche
9705 package R is
9706    procedure Q;
9707    pragma Inline (Q);
9708 end R;
9709 package body R is
9710    ...
9711 end R;
9712
9713 with R;
9714 procedure Main is
9715 begin
9716    ...
9717    R.Q;
9718 end Main;
9719 @end cartouche
9720 @end smallexample
9721
9722 @noindent
9723 With the default behavior (no @option{-gnatn} switch specified), the
9724 compilation of the @code{Main} procedure depends only on its own source,
9725 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9726 means that editing the body of @code{R} does not require recompiling
9727 @code{Main}.
9728
9729 On the other hand, the call @code{R.Q} is not inlined under these
9730 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9731 is compiled, the call will be inlined if the body of @code{Q} is small
9732 enough, but now @code{Main} depends on the body of @code{R} in
9733 @file{r.adb} as well as on the spec. This means that if this body is edited,
9734 the main program must be recompiled. Note that this extra dependency
9735 occurs whether or not the call is in fact inlined by @command{gcc}.
9736
9737 The use of front end inlining with @option{-gnatN} generates similar
9738 additional dependencies.
9739
9740 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
9741 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9742 can be used to prevent
9743 all inlining. This switch overrides all other conditions and ensures
9744 that no inlining occurs. The extra dependences resulting from
9745 @option{-gnatn} will still be active, even if
9746 this switch is used to suppress the resulting inlining actions.
9747
9748 Note regarding the use of @option{-O3}: There is no difference in inlining
9749 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9750 pragma @code{Inline} assuming the use of @option{-gnatn}
9751 or @option{-gnatN} (the switches that activate inlining). If you have used
9752 pragma @code{Inline} in appropriate cases, then it is usually much better
9753 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9754 in this case only has the effect of inlining subprograms you did not
9755 think should be inlined. We often find that the use of @option{-O3} slows
9756 down code by performing excessive inlining, leading to increased instruction
9757 cache pressure from the increased code size. So the bottom line here is
9758 that you should not automatically assume that @option{-O3} is better than
9759 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9760 it actually improves performance.
9761
9762 @node Other Optimization Switches
9763 @subsection Other Optimization Switches
9764 @cindex Optimization Switches
9765
9766 Since @code{GNAT} uses the @code{gcc} back end, all the specialized
9767 @code{gcc} optimization switches are potentially usable. These switches
9768 have not been extensively tested with GNAT but can generally be expected
9769 to work. Examples of switches in this category are
9770 @option{-funroll-loops} and
9771 the various target-specific @option{-m} options (in particular, it has been
9772 observed that @option{-march=pentium4} can significantly improve performance
9773 on appropriate machines). For full details of these switches, see the
9774 @code{gcc} manual.
9775
9776 @node Optimization and Strict Aliasing
9777 @subsection Optimization and Strict Aliasing
9778 @cindex Aliasing
9779 @cindex Strict Aliasing
9780 @cindex No_Strict_Aliasing
9781
9782 @noindent
9783 The strong typing capabilities of Ada allow an optimizer to generate
9784 efficient code in situations where other languages would be forced to
9785 make worst case assumptions preventing such optimizations. Consider
9786 the following example:
9787
9788 @smallexample @c ada
9789 @cartouche
9790 procedure R is
9791    type Int1 is new Integer;
9792    type Int2 is new Integer;
9793    type Int1A is access Int1;
9794    type Int2A is access Int2;
9795    Int1V : Int1A;
9796    Int2V : Int2A;
9797    ...
9798
9799 begin
9800    ...
9801    for J in Data'Range loop
9802       if Data (J) = Int1V.all then
9803          Int2V.all := Int2V.all + 1;
9804       end if;
9805    end loop;
9806    ...
9807 end R;
9808 @end cartouche
9809 @end smallexample
9810
9811 @noindent
9812 In this example, since the variable @code{Int1V} can only access objects
9813 of type @code{Int1}, and @code{Int2V} can only access objects of type
9814 @code{Int2}, there is no possibility that the assignment to
9815 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9816 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9817 for all iterations of the loop and avoid the extra memory reference
9818 required to dereference it each time through the loop.
9819
9820 This kind of optimization, called strict aliasing analysis, is
9821 triggered by specifying an optimization level of @option{-O2} or
9822 higher and allows @code{GNAT} to generate more efficient code
9823 when access values are involved.
9824
9825 However, although this optimization is always correct in terms of
9826 the formal semantics of the Ada Reference Manual, difficulties can
9827 arise if features like @code{Unchecked_Conversion} are used to break
9828 the typing system. Consider the following complete program example:
9829
9830 @smallexample @c ada
9831 @cartouche
9832 package p1 is
9833    type int1 is new integer;
9834    type int2 is new integer;
9835    type a1 is access int1;
9836    type a2 is access int2;
9837 end p1;
9838
9839 with p1; use p1;
9840 package p2 is
9841    function to_a2 (Input : a1) return a2;
9842 end p2;
9843
9844 with Unchecked_Conversion;
9845 package body p2 is
9846    function to_a2 (Input : a1) return a2 is
9847       function to_a2u is
9848         new Unchecked_Conversion (a1, a2);
9849    begin
9850       return to_a2u (Input);
9851    end to_a2;
9852 end p2;
9853
9854 with p2; use p2;
9855 with p1; use p1;
9856 with Text_IO; use Text_IO;
9857 procedure m is
9858    v1 : a1 := new int1;
9859    v2 : a2 := to_a2 (v1);
9860 begin
9861    v1.all := 1;
9862    v2.all := 0;
9863    put_line (int1'image (v1.all));
9864 end;
9865 @end cartouche
9866 @end smallexample
9867
9868 @noindent
9869 This program prints out 0 in @code{-O0} or @code{-O1}
9870 mode, but it prints out 1 in @code{-O2} mode. That's
9871 because in strict aliasing mode, the compiler can and
9872 does assume that the assignment to @code{v2.all} could not
9873 affect the value of @code{v1.all}, since different types
9874 are involved.
9875
9876 This behavior is not a case of non-conformance with the standard, since
9877 the Ada RM specifies that an unchecked conversion where the resulting
9878 bit pattern is not a correct value of the target type can result in an
9879 abnormal value and attempting to reference an abnormal value makes the
9880 execution of a program erroneous.  That's the case here since the result
9881 does not point to an object of type @code{int2}.  This means that the
9882 effect is entirely unpredictable.
9883
9884 However, although that explanation may satisfy a language
9885 lawyer, in practice an applications programmer expects an
9886 unchecked conversion involving pointers to create true
9887 aliases and the behavior of printing 1 seems plain wrong.
9888 In this case, the strict aliasing optimization is unwelcome.
9889
9890 Indeed the compiler recognizes this possibility, and the
9891 unchecked conversion generates a warning:
9892
9893 @smallexample
9894 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9895 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9896 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9897 @end smallexample
9898
9899 @noindent
9900 Unfortunately the problem is recognized when compiling the body of
9901 package @code{p2}, but the actual "bad" code is generated while
9902 compiling the body of @code{m} and this latter compilation does not see
9903 the suspicious @code{Unchecked_Conversion}.
9904
9905 As implied by the warning message, there are approaches you can use to
9906 avoid the unwanted strict aliasing optimization in a case like this.
9907
9908 One possibility is to simply avoid the use of @code{-O2}, but
9909 that is a bit drastic, since it throws away a number of useful
9910 optimizations that do not involve strict aliasing assumptions.
9911
9912 A less drastic approach is to compile the program using the
9913 option @code{-fno-strict-aliasing}. Actually it is only the
9914 unit containing the dereferencing of the suspicious pointer
9915 that needs to be compiled. So in this case, if we compile
9916 unit @code{m} with this switch, then we get the expected
9917 value of zero printed. Analyzing which units might need
9918 the switch can be painful, so a more reasonable approach
9919 is to compile the entire program with options @code{-O2}
9920 and @code{-fno-strict-aliasing}. If the performance is
9921 satisfactory with this combination of options, then the
9922 advantage is that the entire issue of possible "wrong"
9923 optimization due to strict aliasing is avoided.
9924
9925 To avoid the use of compiler switches, the configuration
9926 pragma @code{No_Strict_Aliasing} with no parameters may be
9927 used to specify that for all access types, the strict
9928 aliasing optimization should be suppressed.
9929
9930 However, these approaches are still overkill, in that they causes
9931 all manipulations of all access values to be deoptimized. A more
9932 refined approach is to concentrate attention on the specific
9933 access type identified as problematic.
9934
9935 First, if a careful analysis of uses of the pointer shows
9936 that there are no possible problematic references, then
9937 the warning can be suppressed by bracketing the
9938 instantiation of @code{Unchecked_Conversion} to turn
9939 the warning off:
9940
9941 @smallexample @c ada
9942    pragma Warnings (Off);
9943    function to_a2u is
9944      new Unchecked_Conversion (a1, a2);
9945    pragma Warnings (On);
9946 @end smallexample
9947
9948 @noindent
9949 Of course that approach is not appropriate for this particular
9950 example, since indeed there is a problematic reference. In this
9951 case we can take one of two other approaches.
9952
9953 The first possibility is to move the instantiation of unchecked
9954 conversion to the unit in which the type is declared. In
9955 this example, we would move the instantiation of
9956 @code{Unchecked_Conversion} from the body of package
9957 @code{p2} to the spec of package @code{p1}. Now the
9958 warning disappears. That's because any use of the
9959 access type knows there is a suspicious unchecked
9960 conversion, and the strict aliasing optimization
9961 is automatically suppressed for the type.
9962
9963 If it is not practical to move the unchecked conversion to the same unit
9964 in which the destination access type is declared (perhaps because the
9965 source type is not visible in that unit), you may use pragma
9966 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9967 same declarative sequence as the declaration of the access type:
9968
9969 @smallexample @c ada
9970    type a2 is access int2;
9971    pragma No_Strict_Aliasing (a2);
9972 @end smallexample
9973
9974 @noindent
9975 Here again, the compiler now knows that the strict aliasing optimization
9976 should be suppressed for any reference to type @code{a2} and the
9977 expected behavior is obtained.
9978
9979 Finally, note that although the compiler can generate warnings for
9980 simple cases of unchecked conversions, there are tricker and more
9981 indirect ways of creating type incorrect aliases which the compiler
9982 cannot detect. Examples are the use of address overlays and unchecked
9983 conversions involving composite types containing access types as
9984 components. In such cases, no warnings are generated, but there can
9985 still be aliasing problems. One safe coding practice is to forbid the
9986 use of address clauses for type overlaying, and to allow unchecked
9987 conversion only for primitive types. This is not really a significant
9988 restriction since any possible desired effect can be achieved by
9989 unchecked conversion of access values.
9990
9991 @ifset vms
9992 @node Coverage Analysis
9993 @subsection Coverage Analysis
9994
9995 @noindent
9996 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
9997 the user to determine the distribution of execution time across a program,
9998 @pxref{Profiling} for details of usage.
9999 @end ifset
10000
10001 @node Reducing Size of Ada Executables with gnatelim
10002 @section Reducing Size of Ada Executables with @code{gnatelim}
10003 @findex gnatelim
10004
10005 @noindent
10006 This section describes @command{gnatelim}, a tool which detects unused
10007 subprograms and helps the compiler to create a smaller executable for your
10008 program.
10009
10010 @menu
10011 * About gnatelim::
10012 * Running gnatelim::
10013 * Correcting the List of Eliminate Pragmas::
10014 * Making Your Executables Smaller::
10015 * Summary of the gnatelim Usage Cycle::
10016 @end menu
10017
10018 @node About gnatelim
10019 @subsection About @code{gnatelim}
10020
10021 @noindent
10022 When a program shares a set of Ada
10023 packages with other programs, it may happen that this program uses
10024 only a fraction of the subprograms defined in these packages. The code
10025 created for these unused subprograms increases the size of the executable.
10026
10027 @code{gnatelim} tracks unused subprograms in an Ada program and
10028 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10029 subprograms that are declared but never called. By placing the list of
10030 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10031 recompiling your program, you may decrease the size of its executable,
10032 because the compiler will not generate the code for 'eliminated' subprograms.
10033 See GNAT Reference Manual for more information about this pragma.
10034
10035 @code{gnatelim} needs as its input data the name of the main subprogram
10036 and a bind file for a main subprogram.
10037
10038 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10039 the main subprogram. @code{gnatelim} can work with both Ada and C
10040 bind files; when both are present, it uses the Ada bind file.
10041 The following commands will build the program and create the bind file:
10042
10043 @smallexample
10044 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10045 $ gnatbind main_prog
10046 @end smallexample
10047
10048 Note that @code{gnatelim} needs neither object nor ALI files.
10049
10050 @node Running gnatelim
10051 @subsection Running @code{gnatelim}
10052
10053 @noindent
10054 @code{gnatelim} has the following command-line interface:
10055
10056 @smallexample
10057 $ gnatelim [options] name
10058 @end smallexample
10059
10060 @noindent
10061 @code{name} should be a name of a source file that contains the main subprogram
10062 of a program (partition).
10063
10064 @code{gnatelim} has the following switches:
10065
10066 @table @option
10067 @c !sort!
10068 @item ^-q^/QUIET^
10069 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10070 Quiet mode: by default @code{gnatelim} outputs to the standard error
10071 stream the number of program units left to be processed. This option turns
10072 this trace off.
10073
10074 @item ^-v^/VERBOSE^
10075 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10076 Verbose mode: @code{gnatelim} version information is printed as Ada
10077 comments to the standard output stream. Also, in addition to the number of
10078 program units left @code{gnatelim} will output the name of the current unit
10079 being processed.
10080
10081 @item ^-a^/ALL^
10082 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10083 Also look for subprograms from the GNAT run time that can be eliminated. Note
10084 that when @file{gnat.adc} is produced using this switch, the entire program
10085 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10086
10087 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10088 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10089 When looking for source files also look in directory @var{dir}. Specifying
10090 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10091 sources in the current directory.
10092
10093 @item ^-b^/BIND_FILE=^@var{bind_file}
10094 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10095 Specifies @var{bind_file} as the bind file to process. If not set, the name
10096 of the bind file is computed from the full expanded Ada name
10097 of a main subprogram.
10098
10099 @item ^-C^/CONFIG_FILE=^@var{config_file}
10100 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10101 Specifies a file @var{config_file} that contains configuration pragmas. The
10102 file must be specified with full path.
10103
10104 @item ^--GCC^/COMPILER^=@var{compiler_name}
10105 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10106 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10107 available on the path.
10108
10109 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10110 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10111 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10112 available on the path.
10113 @end table
10114
10115 @noindent
10116 @code{gnatelim} sends its output to the standard output stream, and all the
10117 tracing and debug information is sent to the standard error stream.
10118 In order to produce a proper GNAT configuration file
10119 @file{gnat.adc}, redirection must be used:
10120
10121 @smallexample
10122 @ifset vms
10123 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10124 @end ifset
10125 @ifclear vms
10126 $ gnatelim main_prog.adb > gnat.adc
10127 @end ifclear
10128 @end smallexample
10129
10130 @ifclear vms
10131 @noindent
10132 or
10133
10134 @smallexample
10135 $ gnatelim main_prog.adb >> gnat.adc
10136 @end smallexample
10137
10138 @noindent
10139 in order to append the @code{gnatelim} output to the existing contents of
10140 @file{gnat.adc}.
10141 @end ifclear
10142
10143 @node Correcting the List of Eliminate Pragmas
10144 @subsection Correcting the List of Eliminate Pragmas
10145
10146 @noindent
10147 In some rare cases @code{gnatelim} may try to eliminate
10148 subprograms that are actually called in the program. In this case, the
10149 compiler will generate an error message of the form:
10150
10151 @smallexample
10152 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10153 @end smallexample
10154
10155 @noindent
10156 You will need to manually remove the wrong @code{Eliminate} pragmas from
10157 the @file{gnat.adc} file. You should recompile your program
10158 from scratch after that, because you need a consistent @file{gnat.adc} file
10159 during the entire compilation.
10160
10161 @node Making Your Executables Smaller
10162 @subsection Making Your Executables Smaller
10163
10164 @noindent
10165 In order to get a smaller executable for your program you now have to
10166 recompile the program completely with the new @file{gnat.adc} file
10167 created by @code{gnatelim} in your current directory:
10168
10169 @smallexample
10170 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10171 @end smallexample
10172
10173 @noindent
10174 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10175 recompile everything
10176 with the set of pragmas @code{Eliminate} that you have obtained with
10177 @command{gnatelim}).
10178
10179 Be aware that the set of @code{Eliminate} pragmas is specific to each
10180 program. It is not recommended to merge sets of @code{Eliminate}
10181 pragmas created for different programs in one @file{gnat.adc} file.
10182
10183 @node Summary of the gnatelim Usage Cycle
10184 @subsection Summary of the gnatelim Usage Cycle
10185
10186 @noindent
10187 Here is a quick summary of the steps to be taken in order to reduce
10188 the size of your executables with @code{gnatelim}. You may use
10189 other GNAT options to control the optimization level,
10190 to produce the debugging information, to set search path, etc.
10191
10192 @enumerate
10193 @item
10194 Produce a bind file
10195
10196 @smallexample
10197 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10198 $ gnatbind main_prog
10199 @end smallexample
10200
10201 @item
10202 Generate a list of @code{Eliminate} pragmas
10203 @smallexample
10204 @ifset vms
10205 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10206 @end ifset
10207 @ifclear vms
10208 $ gnatelim main_prog >[>] gnat.adc
10209 @end ifclear
10210 @end smallexample
10211
10212 @item
10213 Recompile the application
10214
10215 @smallexample
10216 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10217 @end smallexample
10218
10219 @end enumerate
10220
10221 @node Reducing Size of Executables with unused subprogram/data elimination
10222 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10223 @findex unused subprogram/data elimination
10224
10225 @noindent
10226 This section describes how you can eliminate unused subprograms and data from
10227 your executable just by setting options at compilation time.
10228
10229 @menu
10230 * About unused subprogram/data elimination::
10231 * Compilation options::
10232 * Example of unused subprogram/data elimination::
10233 @end menu
10234
10235 @node About unused subprogram/data elimination
10236 @subsection About unused subprogram/data elimination
10237
10238 @noindent
10239 By default, an executable contains all code and data of its composing objects
10240 (directly linked or coming from statically linked libraries), even data or code
10241 never used by this executable.
10242
10243 This feature will allow you to eliminate such unused code from your
10244 executable, making it smaller (in disk and in memory).
10245
10246 This functionality is available on all Linux platforms except for the IA-64
10247 architecture and on all cross platforms using the ELF binary file format.
10248 In both cases GNU binutils version 2.16 or later are required to enable it.
10249
10250 @node Compilation options
10251 @subsection Compilation options
10252
10253 @noindent
10254 The operation of eliminating the unused code and data from the final executable
10255 is directly performed by the linker.
10256
10257 In order to do this, it has to work with objects compiled with the
10258 following options:
10259 @option{-ffunction-sections} @option{-fdata-sections}.
10260 @cindex @option{-ffunction-sections} (@command{gcc})
10261 @cindex @option{-fdata-sections} (@command{gcc})
10262 These options are usable with C and Ada files.
10263 They will place respectively each
10264 function or data in a separate section in the resulting object file.
10265
10266 Once the objects and static libraries are created with these options, the
10267 linker can perform the dead code elimination. You can do this by setting
10268 the @option{-Wl,--gc-sections} option to gcc command or in the
10269 @option{-largs} section of gnatmake. This will perform a garbage collection of
10270 code and data never referenced.
10271
10272 If the linker performs a partial link (@option{-r} ld linker option), then you
10273 will need to provide one or several entry point using the
10274 @option{-e} / @option{--entry} ld option.
10275
10276 Note that objects compiled without the @option{-ffunction-sections} and
10277 @option{-fdata-sections} options can still be linked with the executable.
10278 However, no dead code elimination will be performed on those objects (they will
10279 be linked as is).
10280
10281 The GNAT static library is now compiled with -ffunction-sections and
10282 -fdata-sections on some platforms. This allows you to eliminate the unused code
10283 and data of the GNAT library from your executable.
10284
10285 @node Example of unused subprogram/data elimination
10286 @subsection Example of unused subprogram/data elimination
10287
10288 @noindent
10289 Here is a simple example:
10290
10291 @smallexample @c ada
10292 with Aux;
10293
10294 procedure Test is
10295 begin
10296    Aux.Used (10);
10297 end Test;
10298
10299 package Aux is
10300    Used_Data   : Integer;
10301    Unused_Data : Integer;
10302
10303    procedure Used   (Data : Integer);
10304    procedure Unused (Data : Integer);
10305 end Aux;
10306
10307 package body Aux is
10308    procedure Used (Data : Integer) is
10309    begin
10310       Used_Data := Data;
10311    end Used;
10312
10313    procedure Unused (Data : Integer) is
10314    begin
10315       Unused_Data := Data;
10316    end Unused;
10317 end Aux;
10318 @end smallexample
10319
10320 @noindent
10321 @code{Unused} and @code{Unused_Data} are never referenced in this code
10322 excerpt, and hence they may be safely removed from the final executable.
10323
10324 @smallexample
10325 $ gnatmake test
10326
10327 $ nm test | grep used
10328 020015f0 T aux__unused
10329 02005d88 B aux__unused_data
10330 020015cc T aux__used
10331 02005d84 B aux__used_data
10332
10333 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10334      -largs -Wl,--gc-sections
10335
10336 $ nm test | grep used
10337 02005350 T aux__used
10338 0201ffe0 B aux__used_data
10339 @end smallexample
10340
10341 @noindent
10342 It can be observed that the procedure @code{Unused} and the object
10343 @code{Unused_Data} are removed by the linker when using the
10344 appropriate options.
10345
10346 @c ********************************
10347 @node Renaming Files Using gnatchop
10348 @chapter Renaming Files Using @code{gnatchop}
10349 @findex gnatchop
10350
10351 @noindent
10352 This chapter discusses how to handle files with multiple units by using
10353 the @code{gnatchop} utility. This utility is also useful in renaming
10354 files to meet the standard GNAT default file naming conventions.
10355
10356 @menu
10357 * Handling Files with Multiple Units::
10358 * Operating gnatchop in Compilation Mode::
10359 * Command Line for gnatchop::
10360 * Switches for gnatchop::
10361 * Examples of gnatchop Usage::
10362 @end menu
10363
10364 @node Handling Files with Multiple Units
10365 @section Handling Files with Multiple Units
10366
10367 @noindent
10368 The basic compilation model of GNAT requires that a file submitted to the
10369 compiler have only one unit and there be a strict correspondence
10370 between the file name and the unit name.
10371
10372 The @code{gnatchop} utility allows both of these rules to be relaxed,
10373 allowing GNAT to process files which contain multiple compilation units
10374 and files with arbitrary file names. @code{gnatchop}
10375 reads the specified file and generates one or more output files,
10376 containing one unit per file. The unit and the file name correspond,
10377 as required by GNAT.
10378
10379 If you want to permanently restructure a set of ``foreign'' files so that
10380 they match the GNAT rules, and do the remaining development using the
10381 GNAT structure, you can simply use @command{gnatchop} once, generate the
10382 new set of files and work with them from that point on.
10383
10384 Alternatively, if you want to keep your files in the ``foreign'' format,
10385 perhaps to maintain compatibility with some other Ada compilation
10386 system, you can set up a procedure where you use @command{gnatchop} each
10387 time you compile, regarding the source files that it writes as temporary
10388 files that you throw away.
10389
10390 @node Operating gnatchop in Compilation Mode
10391 @section Operating gnatchop in Compilation Mode
10392
10393 @noindent
10394 The basic function of @code{gnatchop} is to take a file with multiple units
10395 and split it into separate files. The boundary between files is reasonably
10396 clear, except for the issue of comments and pragmas. In default mode, the
10397 rule is that any pragmas between units belong to the previous unit, except
10398 that configuration pragmas always belong to the following unit. Any comments
10399 belong to the following unit. These rules
10400 almost always result in the right choice of
10401 the split point without needing to mark it explicitly and most users will
10402 find this default to be what they want. In this default mode it is incorrect to
10403 submit a file containing only configuration pragmas, or one that ends in
10404 configuration pragmas, to @code{gnatchop}.
10405
10406 However, using a special option to activate ``compilation mode'',
10407 @code{gnatchop}
10408 can perform another function, which is to provide exactly the semantics
10409 required by the RM for handling of configuration pragmas in a compilation.
10410 In the absence of configuration pragmas (at the main file level), this
10411 option has no effect, but it causes such configuration pragmas to be handled
10412 in a quite different manner.
10413
10414 First, in compilation mode, if @code{gnatchop} is given a file that consists of
10415 only configuration pragmas, then this file is appended to the
10416 @file{gnat.adc} file in the current directory. This behavior provides
10417 the required behavior described in the RM for the actions to be taken
10418 on submitting such a file to the compiler, namely that these pragmas
10419 should apply to all subsequent compilations in the same compilation
10420 environment. Using GNAT, the current directory, possibly containing a
10421 @file{gnat.adc} file is the representation
10422 of a compilation environment. For more information on the
10423 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
10424
10425 Second, in compilation mode, if @code{gnatchop}
10426 is given a file that starts with
10427 configuration pragmas, and contains one or more units, then these
10428 configuration pragmas are prepended to each of the chopped files. This
10429 behavior provides the required behavior described in the RM for the
10430 actions to be taken on compiling such a file, namely that the pragmas
10431 apply to all units in the compilation, but not to subsequently compiled
10432 units.
10433
10434 Finally, if configuration pragmas appear between units, they are appended
10435 to the previous unit. This results in the previous unit being illegal,
10436 since the compiler does not accept configuration pragmas that follow
10437 a unit. This provides the required RM behavior that forbids configuration
10438 pragmas other than those preceding the first compilation unit of a
10439 compilation.
10440
10441 For most purposes, @code{gnatchop} will be used in default mode. The
10442 compilation mode described above is used only if you need exactly
10443 accurate behavior with respect to compilations, and you have files
10444 that contain multiple units and configuration pragmas. In this
10445 circumstance the use of @code{gnatchop} with the compilation mode
10446 switch provides the required behavior, and is for example the mode
10447 in which GNAT processes the ACVC tests.
10448
10449 @node Command Line for gnatchop
10450 @section Command Line for @code{gnatchop}
10451
10452 @noindent
10453 The @code{gnatchop} command has the form:
10454
10455 @smallexample
10456 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
10457       [@var{directory}]
10458 @end smallexample
10459
10460 @noindent
10461 The only required argument is the file name of the file to be chopped.
10462 There are no restrictions on the form of this file name. The file itself
10463 contains one or more Ada units, in normal GNAT format, concatenated
10464 together. As shown, more than one file may be presented to be chopped.
10465
10466 When run in default mode, @code{gnatchop} generates one output file in
10467 the current directory for each unit in each of the files.
10468
10469 @var{directory}, if specified, gives the name of the directory to which
10470 the output files will be written. If it is not specified, all files are
10471 written to the current directory.
10472
10473 For example, given a
10474 file called @file{hellofiles} containing
10475
10476 @smallexample @c ada
10477 @group
10478 @cartouche
10479 procedure hello;
10480
10481 with Text_IO; use Text_IO;
10482 procedure hello is
10483 begin
10484    Put_Line ("Hello");
10485 end hello;
10486 @end cartouche
10487 @end group
10488 @end smallexample
10489
10490 @noindent
10491 the command
10492
10493 @smallexample
10494 $ gnatchop ^hellofiles^HELLOFILES.^
10495 @end smallexample
10496
10497 @noindent
10498 generates two files in the current directory, one called
10499 @file{hello.ads} containing the single line that is the procedure spec,
10500 and the other called @file{hello.adb} containing the remaining text. The
10501 original file is not affected. The generated files can be compiled in
10502 the normal manner.
10503
10504 @noindent
10505 When gnatchop is invoked on a file that is empty or that contains only empty
10506 lines and/or comments, gnatchop will not fail, but will not produce any
10507 new sources.
10508
10509 For example, given a
10510 file called @file{toto.txt} containing
10511
10512 @smallexample @c ada
10513 @group
10514 @cartouche
10515 --  Just a comment
10516 @end cartouche
10517 @end group
10518 @end smallexample
10519
10520 @noindent
10521 the command
10522
10523 @smallexample
10524 $ gnatchop ^toto.txt^TOT.TXT^
10525 @end smallexample
10526
10527 @noindent
10528 will not produce any new file and will result in the following warnings:
10529
10530 @smallexample
10531 toto.txt:1:01: warning: empty file, contains no compilation units
10532 no compilation units found
10533 no source files written
10534 @end smallexample
10535
10536 @node Switches for gnatchop
10537 @section Switches for @code{gnatchop}
10538
10539 @noindent
10540 @command{gnatchop} recognizes the following switches:
10541
10542 @table @option
10543 @c !sort!
10544
10545 @item --version
10546 @cindex @option{--version} @command{gnatchop}
10547 Display Copyright and version, then exit disregarding all other options.
10548
10549 @item --help
10550 @cindex @option{--help} @command{gnatchop}
10551 If @option{--version} was not used, display usage, then exit disregarding
10552 all other options.
10553
10554 @item ^-c^/COMPILATION^
10555 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
10556 Causes @code{gnatchop} to operate in compilation mode, in which
10557 configuration pragmas are handled according to strict RM rules. See
10558 previous section for a full description of this mode.
10559
10560 @ifclear vms
10561 @item -gnatxxx
10562 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
10563 used to parse the given file. Not all @code{xxx} options make sense,
10564 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
10565 process a source file that uses Latin-2 coding for identifiers.
10566 @end ifclear
10567
10568 @item ^-h^/HELP^
10569 Causes @code{gnatchop} to generate a brief help summary to the standard
10570 output file showing usage information.
10571
10572 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
10573 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
10574 Limit generated file names to the specified number @code{mm}
10575 of characters.
10576 This is useful if the
10577 resulting set of files is required to be interoperable with systems
10578 which limit the length of file names.
10579 @ifset vms
10580 If no value is given, or
10581 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
10582 a default of 39, suitable for OpenVMS Alpha
10583 Systems, is assumed
10584 @end ifset
10585 @ifclear vms
10586 No space is allowed between the @option{-k} and the numeric value. The numeric
10587 value may be omitted in which case a default of @option{-k8},
10588 suitable for use
10589 with DOS-like file systems, is used. If no @option{-k} switch
10590 is present then
10591 there is no limit on the length of file names.
10592 @end ifclear
10593
10594 @item ^-p^/PRESERVE^
10595 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
10596 Causes the file ^modification^creation^ time stamp of the input file to be
10597 preserved and used for the time stamp of the output file(s). This may be
10598 useful for preserving coherency of time stamps in an environment where
10599 @code{gnatchop} is used as part of a standard build process.
10600
10601 @item ^-q^/QUIET^
10602 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
10603 Causes output of informational messages indicating the set of generated
10604 files to be suppressed. Warnings and error messages are unaffected.
10605
10606 @item ^-r^/REFERENCE^
10607 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
10608 @findex Source_Reference
10609 Generate @code{Source_Reference} pragmas. Use this switch if the output
10610 files are regarded as temporary and development is to be done in terms
10611 of the original unchopped file. This switch causes
10612 @code{Source_Reference} pragmas to be inserted into each of the
10613 generated files to refers back to the original file name and line number.
10614 The result is that all error messages refer back to the original
10615 unchopped file.
10616 In addition, the debugging information placed into the object file (when
10617 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
10618 specified)
10619 also refers back to this original file so that tools like profilers and
10620 debuggers will give information in terms of the original unchopped file.
10621
10622 If the original file to be chopped itself contains
10623 a @code{Source_Reference}
10624 pragma referencing a third file, then gnatchop respects
10625 this pragma, and the generated @code{Source_Reference} pragmas
10626 in the chopped file refer to the original file, with appropriate
10627 line numbers. This is particularly useful when @code{gnatchop}
10628 is used in conjunction with @code{gnatprep} to compile files that
10629 contain preprocessing statements and multiple units.
10630
10631 @item ^-v^/VERBOSE^
10632 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
10633 Causes @code{gnatchop} to operate in verbose mode. The version
10634 number and copyright notice are output, as well as exact copies of
10635 the gnat1 commands spawned to obtain the chop control information.
10636
10637 @item ^-w^/OVERWRITE^
10638 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
10639 Overwrite existing file names. Normally @code{gnatchop} regards it as a
10640 fatal error if there is already a file with the same name as a
10641 file it would otherwise output, in other words if the files to be
10642 chopped contain duplicated units. This switch bypasses this
10643 check, and causes all but the last instance of such duplicated
10644 units to be skipped.
10645
10646 @ifclear vms
10647 @item --GCC=xxxx
10648 @cindex @option{--GCC=} (@code{gnatchop})
10649 Specify the path of the GNAT parser to be used. When this switch is used,
10650 no attempt is made to add the prefix to the GNAT parser executable.
10651 @end ifclear
10652 @end table
10653
10654 @node Examples of gnatchop Usage
10655 @section Examples of @code{gnatchop} Usage
10656
10657 @table @code
10658 @ifset vms
10659 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10660 @end ifset
10661 @ifclear vms
10662 @item gnatchop -w hello_s.ada prerelease/files
10663 @end ifclear
10664
10665 Chops the source file @file{hello_s.ada}. The output files will be
10666 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10667 overwriting any
10668 files with matching names in that directory (no files in the current
10669 directory are modified).
10670
10671 @item gnatchop ^archive^ARCHIVE.^
10672 Chops the source file @file{^archive^ARCHIVE.^}
10673 into the current directory. One
10674 useful application of @code{gnatchop} is in sending sets of sources
10675 around, for example in email messages. The required sources are simply
10676 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
10677 command), and then
10678 @command{gnatchop} is used at the other end to reconstitute the original
10679 file names.
10680
10681 @item gnatchop file1 file2 file3 direc
10682 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10683 the resulting files in the directory @file{direc}. Note that if any units
10684 occur more than once anywhere within this set of files, an error message
10685 is generated, and no files are written. To override this check, use the
10686 @option{^-w^/OVERWRITE^} switch,
10687 in which case the last occurrence in the last file will
10688 be the one that is output, and earlier duplicate occurrences for a given
10689 unit will be skipped.
10690 @end table
10691
10692 @node Configuration Pragmas
10693 @chapter Configuration Pragmas
10694 @cindex Configuration pragmas
10695 @cindex Pragmas, configuration
10696
10697 @noindent
10698 Configuration pragmas include those pragmas described as
10699 such in the Ada Reference Manual, as well as
10700 implementation-dependent pragmas that are configuration pragmas. See the
10701 individual descriptions of pragmas in the @cite{GNAT Reference Manual} for
10702 details on these additional GNAT-specific configuration pragmas. Most
10703 notably, the pragma @code{Source_File_Name}, which allows
10704 specifying non-default names for source files, is a configuration
10705 pragma. The following is a complete list of configuration pragmas
10706 recognized by GNAT:
10707
10708 @smallexample
10709    Ada_83
10710    Ada_95
10711    Ada_05
10712    C_Pass_By_Copy
10713    Component_Alignment
10714    Detect_Blocking
10715    Discard_Names
10716    Elaboration_Checks
10717    Eliminate
10718    Extend_System
10719    External_Name_Casing
10720    Float_Representation
10721    Initialize_Scalars
10722    Interrupt_State
10723    License
10724    Locking_Policy
10725    Long_Float
10726    Normalize_Scalars
10727    Persistent_BSS
10728    Polling
10729    Profile
10730    Profile_Warnings
10731    Propagate_Exceptions
10732    Queuing_Policy
10733    Ravenscar
10734    Restricted_Run_Time
10735    Restrictions
10736    Restrictions_Warnings
10737    Reviewable
10738    Source_File_Name
10739    Style_Checks
10740    Suppress
10741    Task_Dispatching_Policy
10742    Universal_Data
10743    Unsuppress
10744    Use_VADS_Size
10745    Warnings
10746    Validity_Checks
10747 @end smallexample
10748
10749 @menu
10750 * Handling of Configuration Pragmas::
10751 * The Configuration Pragmas Files::
10752 @end menu
10753
10754 @node Handling of Configuration Pragmas
10755 @section Handling of Configuration Pragmas
10756
10757 Configuration pragmas may either appear at the start of a compilation
10758 unit, in which case they apply only to that unit, or they may apply to
10759 all compilations performed in a given compilation environment.
10760
10761 GNAT also provides the @code{gnatchop} utility to provide an automatic
10762 way to handle configuration pragmas following the semantics for
10763 compilations (that is, files with multiple units), described in the RM.
10764 See @ref{Operating gnatchop in Compilation Mode} for details.
10765 However, for most purposes, it will be more convenient to edit the
10766 @file{gnat.adc} file that contains configuration pragmas directly,
10767 as described in the following section.
10768
10769 @node The Configuration Pragmas Files
10770 @section The Configuration Pragmas Files
10771 @cindex @file{gnat.adc}
10772
10773 @noindent
10774 In GNAT a compilation environment is defined by the current
10775 directory at the time that a compile command is given. This current
10776 directory is searched for a file whose name is @file{gnat.adc}. If
10777 this file is present, it is expected to contain one or more
10778 configuration pragmas that will be applied to the current compilation.
10779 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10780 considered.
10781
10782 Configuration pragmas may be entered into the @file{gnat.adc} file
10783 either by running @code{gnatchop} on a source file that consists only of
10784 configuration pragmas, or more conveniently  by
10785 direct editing of the @file{gnat.adc} file, which is a standard format
10786 source file.
10787
10788 In addition to @file{gnat.adc}, additional files containing configuration
10789 pragmas may be applied to the current compilation using the switch
10790 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10791 contains only configuration pragmas. These configuration pragmas are
10792 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10793 is present and switch @option{-gnatA} is not used).
10794
10795 It is allowed to specify several switches @option{-gnatec}, all of which
10796 will be taken into account.
10797
10798 If you are using project file, a separate mechanism is provided using
10799 project attributes, see @ref{Specifying Configuration Pragmas} for more
10800 details.
10801
10802 @ifset vms
10803 Of special interest to GNAT OpenVMS Alpha is the following
10804 configuration pragma:
10805
10806 @smallexample @c ada
10807 @cartouche
10808 pragma Extend_System (Aux_DEC);
10809 @end cartouche
10810 @end smallexample
10811
10812 @noindent
10813 In the presence of this pragma, GNAT adds to the definition of the
10814 predefined package SYSTEM all the additional types and subprograms that are
10815 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
10816 @end ifset
10817
10818 @node Handling Arbitrary File Naming Conventions Using gnatname
10819 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10820 @cindex Arbitrary File Naming Conventions
10821
10822 @menu
10823 * Arbitrary File Naming Conventions::
10824 * Running gnatname::
10825 * Switches for gnatname::
10826 * Examples of gnatname Usage::
10827 @end menu
10828
10829 @node Arbitrary File Naming Conventions
10830 @section Arbitrary File Naming Conventions
10831
10832 @noindent
10833 The GNAT compiler must be able to know the source file name of a compilation
10834 unit.  When using the standard GNAT default file naming conventions
10835 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10836 does not need additional information.
10837
10838 @noindent
10839 When the source file names do not follow the standard GNAT default file naming
10840 conventions, the GNAT compiler must be given additional information through
10841 a configuration pragmas file (@pxref{Configuration Pragmas})
10842 or a project file.
10843 When the non standard file naming conventions are well-defined,
10844 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10845 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
10846 if the file naming conventions are irregular or arbitrary, a number
10847 of pragma @code{Source_File_Name} for individual compilation units
10848 must be defined.
10849 To help maintain the correspondence between compilation unit names and
10850 source file names within the compiler,
10851 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10852 set of files.
10853
10854 @node Running gnatname
10855 @section Running @code{gnatname}
10856
10857 @noindent
10858 The usual form of the @code{gnatname} command is
10859
10860 @smallexample
10861 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10862 @end smallexample
10863
10864 @noindent
10865 All of the arguments are optional. If invoked without any argument,
10866 @code{gnatname} will display its usage.
10867
10868 @noindent
10869 When used with at least one naming pattern, @code{gnatname} will attempt to
10870 find all the compilation units in files that follow at least one of the
10871 naming patterns. To find these compilation units,
10872 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10873 regular files.
10874
10875 @noindent
10876 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10877 Each Naming Pattern is enclosed between double quotes.
10878 A Naming Pattern is a regular expression similar to the wildcard patterns
10879 used in file names by the Unix shells or the DOS prompt.
10880
10881 @noindent
10882 Examples of Naming Patterns are
10883
10884 @smallexample
10885    "*.[12].ada"
10886    "*.ad[sb]*"
10887    "body_*"    "spec_*"
10888 @end smallexample
10889
10890 @noindent
10891 For a more complete description of the syntax of Naming Patterns,
10892 see the second kind of regular expressions described in @file{g-regexp.ads}
10893 (the ``Glob'' regular expressions).
10894
10895 @noindent
10896 When invoked with no switches, @code{gnatname} will create a configuration
10897 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10898 @code{Source_File_Name} for each file that contains a valid Ada unit.
10899
10900 @node Switches for gnatname
10901 @section Switches for @code{gnatname}
10902
10903 @noindent
10904 Switches for @code{gnatname} must precede any specified Naming Pattern.
10905
10906 @noindent
10907 You may specify any of the following switches to @code{gnatname}:
10908
10909 @table @option
10910 @c !sort!
10911
10912 @item --version
10913 @cindex @option{--version} @command{gnatname}
10914 Display Copyright and version, then exit disregarding all other options.
10915
10916 @item --help
10917 @cindex @option{--help} @command{gnatname}
10918 If @option{--version} was not used, display usage, then exit disregarding
10919 all other options.
10920
10921 @item ^-c^/CONFIG_FILE=^@file{file}
10922 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10923 Create a configuration pragmas file @file{file} (instead of the default
10924 @file{gnat.adc}).
10925 @ifclear vms
10926 There may be zero, one or more space between @option{-c} and
10927 @file{file}.
10928 @end ifclear
10929 @file{file} may include directory information. @file{file} must be
10930 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10931 When a switch @option{^-c^/CONFIG_FILE^} is
10932 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10933
10934 @item ^-d^/SOURCE_DIRS=^@file{dir}
10935 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10936 Look for source files in directory @file{dir}. There may be zero, one or more
10937 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10938 When a switch @option{^-d^/SOURCE_DIRS^}
10939 is specified, the current working directory will not be searched for source
10940 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10941 or @option{^-D^/DIR_FILES^} switch.
10942 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10943 If @file{dir} is a relative path, it is relative to the directory of
10944 the configuration pragmas file specified with switch
10945 @option{^-c^/CONFIG_FILE^},
10946 or to the directory of the project file specified with switch
10947 @option{^-P^/PROJECT_FILE^} or,
10948 if neither switch @option{^-c^/CONFIG_FILE^}
10949 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10950 current working directory. The directory
10951 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10952
10953 @item ^-D^/DIRS_FILE=^@file{file}
10954 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10955 Look for source files in all directories listed in text file @file{file}.
10956 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10957 and @file{file}.
10958 @file{file} must be an existing, readable text file.
10959 Each non empty line in @file{file} must be a directory.
10960 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10961 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10962 @file{file}.
10963
10964 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10965 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10966 Foreign patterns. Using this switch, it is possible to add sources of languages
10967 other than Ada to the list of sources of a project file.
10968 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10969 For example,
10970 @smallexample
10971 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10972 @end smallexample
10973 @noindent
10974 will look for Ada units in all files with the @file{.ada} extension,
10975 and will add to the list of file for project @file{prj.gpr} the C files
10976 with extension ".^c^C^".
10977
10978 @item ^-h^/HELP^
10979 @cindex @option{^-h^/HELP^} (@code{gnatname})
10980 Output usage (help) information. The output is written to @file{stdout}.
10981
10982 @item ^-P^/PROJECT_FILE=^@file{proj}
10983 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10984 Create or update project file @file{proj}. There may be zero, one or more space
10985 between @option{-P} and @file{proj}. @file{proj} may include directory
10986 information. @file{proj} must be writable.
10987 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10988 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10989 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10990
10991 @item ^-v^/VERBOSE^
10992 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10993 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10994 This includes name of the file written, the name of the directories to search
10995 and, for each file in those directories whose name matches at least one of
10996 the Naming Patterns, an indication of whether the file contains a unit,
10997 and if so the name of the unit.
10998
10999 @item ^-v -v^/VERBOSE /VERBOSE^
11000 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11001 Very Verbose mode. In addition to the output produced in verbose mode,
11002 for each file in the searched directories whose name matches none of
11003 the Naming Patterns, an indication is given that there is no match.
11004
11005 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11006 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11007 Excluded patterns. Using this switch, it is possible to exclude some files
11008 that would match the name patterns. For example,
11009 @smallexample
11010 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11011 @end smallexample
11012 @noindent
11013 will look for Ada units in all files with the @file{.ada} extension,
11014 except those whose names end with @file{_nt.ada}.
11015
11016 @end table
11017
11018 @node Examples of gnatname Usage
11019 @section Examples of @code{gnatname} Usage
11020
11021 @ifset vms
11022 @smallexample
11023 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11024 @end smallexample
11025 @end ifset
11026
11027 @ifclear vms
11028 @smallexample
11029 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11030 @end smallexample
11031 @end ifclear
11032
11033 @noindent
11034 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11035 and be writable. In addition, the directory
11036 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11037 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11038
11039 @ifclear vms
11040 Note the optional spaces after @option{-c} and @option{-d}.
11041 @end ifclear
11042
11043 @smallexample
11044 @ifclear vms
11045 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11046   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11047 @end ifclear
11048 @ifset vms
11049 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11050   /EXCLUDED_PATTERN=*_nt_body.ada
11051   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11052   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11053 @end ifset
11054 @end smallexample
11055
11056 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11057 even in conjunction with one or several switches
11058 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11059 are used in this example.
11060
11061 @c *****************************************
11062 @c * G N A T  P r o j e c t  M a n a g e r *
11063 @c *****************************************
11064 @node GNAT Project Manager
11065 @chapter GNAT Project Manager
11066
11067 @menu
11068 * Introduction::
11069 * Examples of Project Files::
11070 * Project File Syntax::
11071 * Objects and Sources in Project Files::
11072 * Importing Projects::
11073 * Project Extension::
11074 * Project Hierarchy Extension::
11075 * External References in Project Files::
11076 * Packages in Project Files::
11077 * Variables from Imported Projects::
11078 * Naming Schemes::
11079 * Library Projects::
11080 * Stand-alone Library Projects::
11081 * Switches Related to Project Files::
11082 * Tools Supporting Project Files::
11083 * An Extended Example::
11084 * Project File Complete Syntax::
11085 @end menu
11086
11087 @c ****************
11088 @c * Introduction *
11089 @c ****************
11090
11091 @node Introduction
11092 @section Introduction
11093
11094 @noindent
11095 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11096 you to manage complex builds involving a number of source files, directories,
11097 and compilation options for different system configurations. In particular,
11098 project files allow you to specify:
11099 @itemize @bullet
11100 @item
11101 The directory or set of directories containing the source files, and/or the
11102 names of the specific source files themselves
11103 @item
11104 The directory in which the compiler's output
11105 (@file{ALI} files, object files, tree files) is to be placed
11106 @item
11107 The directory in which the executable programs is to be placed
11108 @item
11109 ^Switch^Switch^ settings for any of the project-enabled tools
11110 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11111 @code{gnatfind}); you can apply these settings either globally or to individual
11112 compilation units.
11113 @item
11114 The source files containing the main subprogram(s) to be built
11115 @item
11116 The source programming language(s) (currently Ada and/or C)
11117 @item
11118 Source file naming conventions; you can specify these either globally or for
11119 individual compilation units
11120 @end itemize
11121
11122 @menu
11123 * Project Files::
11124 @end menu
11125
11126 @node Project Files
11127 @subsection Project Files
11128
11129 @noindent
11130 Project files are written in a syntax close to that of Ada, using  familiar
11131 notions such as packages, context clauses, declarations, default values,
11132 assignments, and inheritance. Finally, project files can be built
11133 hierarchically from other project files, simplifying complex system
11134 integration and project reuse.
11135
11136 A @dfn{project} is a specific set of values for various compilation properties.
11137 The settings for a given project are described by means of
11138 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11139 Property values in project files are either strings or lists of strings.
11140 Properties that are not explicitly set receive default values.  A project
11141 file may interrogate the values of @dfn{external variables} (user-defined
11142 command-line switches or environment variables), and it may specify property
11143 settings conditionally, based on the value of such variables.
11144
11145 In simple cases, a project's source files depend only on other source files
11146 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11147 used in
11148 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11149 the Project Manager also allows more sophisticated arrangements,
11150 where the source files in one project depend on source files in other
11151 projects:
11152 @itemize @bullet
11153 @item
11154 One project can @emph{import} other projects containing needed source files.
11155 @item
11156 You can organize GNAT projects in a hierarchy: a @emph{child} project
11157 can extend a @emph{parent} project, inheriting the parent's source files and
11158 optionally overriding any of them with alternative versions
11159 @end itemize
11160
11161 @noindent
11162 More generally, the Project Manager lets you structure large development
11163 efforts into hierarchical subsystems, where build decisions are delegated
11164 to the subsystem level, and thus different compilation environments
11165 (^switch^switch^ settings) used for different subsystems.
11166
11167 The Project Manager is invoked through the
11168 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11169 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11170 @ifclear vms
11171 There may be zero, one or more spaces between @option{-P} and
11172 @option{@emph{projectfile}}.
11173 @end ifclear
11174 If you want to define (on the command line) an external variable that is
11175 queried by the project file, you must use the
11176 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11177 The Project Manager parses and interprets the project file, and drives the
11178 invoked tool based on the project settings.
11179
11180 The Project Manager supports a wide range of development strategies,
11181 for systems of all sizes.  Here are some typical practices that are
11182 easily handled:
11183 @itemize @bullet
11184 @item
11185 Using a common set of source files, but generating object files in different
11186 directories via different ^switch^switch^ settings
11187 @item
11188 Using a mostly-shared set of source files, but with different versions of
11189 some unit or units
11190 @end itemize
11191
11192 @noindent
11193 The destination of an executable can be controlled inside a project file
11194 using the @option{^-o^-o^}
11195 ^switch^switch^.
11196 In the absence of such a ^switch^switch^ either inside
11197 the project file or on the command line, any executable files generated by
11198 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11199 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11200 in the object directory of the project.
11201
11202 You can use project files to achieve some of the effects of a source
11203 versioning system (for example, defining separate projects for
11204 the different sets of sources that comprise different releases) but the
11205 Project Manager is independent of any source configuration management tools
11206 that might be used by the developers.
11207
11208 The next section introduces the main features of GNAT's project facility
11209 through a sequence of examples; subsequent sections will present the syntax
11210 and semantics in more detail. A more formal description of the project
11211 facility appears in the GNAT Reference Manual.
11212
11213 @c *****************************
11214 @c * Examples of Project Files *
11215 @c *****************************
11216
11217 @node Examples of Project Files
11218 @section Examples of Project Files
11219 @noindent
11220 This section illustrates some of the typical uses of project files and
11221 explains their basic structure and behavior.
11222
11223 @menu
11224 * Common Sources with Different ^Switches^Switches^ and Directories::
11225 * Using External Variables::
11226 * Importing Other Projects::
11227 * Extending a Project::
11228 @end menu
11229
11230 @node Common Sources with Different ^Switches^Switches^ and Directories
11231 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11232
11233 @menu
11234 * Source Files::
11235 * Specifying the Object Directory::
11236 * Specifying the Exec Directory::
11237 * Project File Packages::
11238 * Specifying ^Switch^Switch^ Settings::
11239 * Main Subprograms::
11240 * Executable File Names::
11241 * Source File Naming Conventions::
11242 * Source Language(s)::
11243 @end menu
11244
11245 @noindent
11246 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11247 @file{proc.adb} are in the @file{/common} directory.  The file
11248 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11249 package @code{Pack}.  We want to compile these source files under two sets
11250 of ^switches^switches^:
11251 @itemize @bullet
11252 @item
11253 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11254 and the @option{^-gnata^-gnata^},
11255 @option{^-gnato^-gnato^},
11256 and @option{^-gnatE^-gnatE^} switches to the
11257 compiler; the compiler's output is to appear in @file{/common/debug}
11258 @item
11259 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11260 to the compiler; the compiler's output is to appear in @file{/common/release}
11261 @end itemize
11262
11263 @noindent
11264 The GNAT project files shown below, respectively @file{debug.gpr} and
11265 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11266
11267 Schematically:
11268 @smallexample
11269 @group
11270 ^/common^[COMMON]^
11271   debug.gpr
11272   release.gpr
11273   pack.ads
11274   pack.adb
11275   proc.adb
11276 @end group
11277 @group
11278 ^/common/debug^[COMMON.DEBUG]^
11279   proc.ali, proc.o
11280   pack.ali, pack.o
11281 @end group
11282 @group
11283 ^/common/release^[COMMON.RELEASE]^
11284   proc.ali, proc.o
11285   pack.ali, pack.o
11286 @end group
11287 @end smallexample
11288 Here are the corresponding project files:
11289
11290 @smallexample @c projectfile
11291 @group
11292 project Debug is
11293   for Object_Dir use "debug";
11294   for Main use ("proc");
11295
11296   package Builder is
11297     for ^Default_Switches^Default_Switches^ ("Ada")
11298         use ("^-g^-g^");
11299     for Executable ("proc.adb") use "proc1";
11300   end Builder;
11301 @end group
11302
11303 @group
11304   package Compiler is
11305     for ^Default_Switches^Default_Switches^ ("Ada")
11306        use ("-fstack-check",
11307             "^-gnata^-gnata^",
11308             "^-gnato^-gnato^",
11309             "^-gnatE^-gnatE^");
11310   end Compiler;
11311 end Debug;
11312 @end group
11313 @end smallexample
11314
11315 @smallexample @c projectfile
11316 @group
11317 project Release is
11318   for Object_Dir use "release";
11319   for Exec_Dir use ".";
11320   for Main use ("proc");
11321
11322   package Compiler is
11323     for ^Default_Switches^Default_Switches^ ("Ada")
11324         use ("^-O2^-O2^");
11325   end Compiler;
11326 end Release;
11327 @end group
11328 @end smallexample
11329
11330 @noindent
11331 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11332 insensitive), and analogously the project defined by @file{release.gpr} is
11333 @code{"Release"}.  For consistency the file should have the same name as the
11334 project, and the project file's extension should be @code{"gpr"}. These
11335 conventions are not required, but a warning is issued if they are not followed.
11336
11337 If the current directory is @file{^/temp^[TEMP]^}, then the command
11338 @smallexample
11339 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11340 @end smallexample
11341
11342 @noindent
11343 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11344 as well as the @code{^proc1^PROC1.EXE^} executable,
11345 using the ^switch^switch^ settings defined in the project file.
11346
11347 Likewise, the command
11348 @smallexample
11349 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11350 @end smallexample
11351
11352 @noindent
11353 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11354 and the @code{^proc^PROC.EXE^}
11355 executable in @file{^/common^[COMMON]^},
11356 using the ^switch^switch^ settings from the project file.
11357
11358 @node Source Files
11359 @unnumberedsubsubsec Source Files
11360
11361 @noindent
11362 If a project file does not explicitly specify a set of source directories or
11363 a set of source files, then by default the project's source files are the
11364 Ada source files in the project file directory.  Thus @file{pack.ads},
11365 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11366
11367 @node Specifying the Object Directory
11368 @unnumberedsubsubsec Specifying the Object Directory
11369
11370 @noindent
11371 Several project properties are modeled by Ada-style @emph{attributes};
11372 a property is defined by supplying the equivalent of an Ada attribute
11373 definition clause in the project file.
11374 A project's object directory is another such a property; the corresponding
11375 attribute is @code{Object_Dir}, and its value is also a string expression,
11376 specified either as absolute or relative. In the later case,
11377 it is relative to the project file directory. Thus the compiler's
11378 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
11379 (for the @code{Debug} project)
11380 and to @file{^/common/release^[COMMON.RELEASE]^}
11381 (for the @code{Release} project).
11382 If @code{Object_Dir} is not specified, then the default is the project file
11383 directory itself.
11384
11385 @node Specifying the Exec Directory
11386 @unnumberedsubsubsec Specifying the Exec Directory
11387
11388 @noindent
11389 A project's exec directory is another property; the corresponding
11390 attribute is @code{Exec_Dir}, and its value is also a string expression,
11391 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
11392 then the default is the object directory (which may also be the project file
11393 directory if attribute @code{Object_Dir} is not specified). Thus the executable
11394 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
11395 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
11396 and in @file{^/common^[COMMON]^} for the @code{Release} project.
11397
11398 @node Project File Packages
11399 @unnumberedsubsubsec Project File Packages
11400
11401 @noindent
11402 A GNAT tool that is integrated with the Project Manager is modeled by a
11403 corresponding package in the project file. In the example above,
11404 The @code{Debug} project defines the packages @code{Builder}
11405 (for @command{gnatmake}) and @code{Compiler};
11406 the @code{Release} project defines only the @code{Compiler} package.
11407
11408 The Ada-like package syntax is not to be taken literally.  Although packages in
11409 project files bear a surface resemblance to packages in Ada source code, the
11410 notation is simply a way to convey a grouping of properties for a named
11411 entity.  Indeed, the package names permitted in project files are restricted
11412 to a predefined set, corresponding to the project-aware tools, and the contents
11413 of packages are limited to a small set of constructs.
11414 The packages in the example above contain attribute definitions.
11415
11416 @node Specifying ^Switch^Switch^ Settings
11417 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
11418
11419 @noindent
11420 ^Switch^Switch^ settings for a project-aware tool can be specified through
11421 attributes in the package that corresponds to the tool.
11422 The example above illustrates one of the relevant attributes,
11423 @code{^Default_Switches^Default_Switches^}, which is defined in packages
11424 in both project files.
11425 Unlike simple attributes like @code{Source_Dirs},
11426 @code{^Default_Switches^Default_Switches^} is
11427 known as an @emph{associative array}.  When you define this attribute, you must
11428 supply an ``index'' (a literal string), and the effect of the attribute
11429 definition is to set the value of the array at the specified index.
11430 For the @code{^Default_Switches^Default_Switches^} attribute,
11431 the index is a programming language (in our case, Ada),
11432 and the value specified (after @code{use}) must be a list
11433 of string expressions.
11434
11435 The attributes permitted in project files are restricted to a predefined set.
11436 Some may appear at project level, others in packages.
11437 For any attribute that is an associative array, the index must always be a
11438 literal string, but the restrictions on this string (e.g., a file name or a
11439 language name) depend on the individual attribute.
11440 Also depending on the attribute, its specified value will need to be either a
11441 string or a string list.
11442
11443 In the @code{Debug} project, we set the switches for two tools,
11444 @command{gnatmake} and the compiler, and thus we include the two corresponding
11445 packages; each package defines the @code{^Default_Switches^Default_Switches^}
11446 attribute with index @code{"Ada"}.
11447 Note that the package corresponding to
11448 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
11449 similar, but only includes the @code{Compiler} package.
11450
11451 In project @code{Debug} above, the ^switches^switches^ starting with
11452 @option{-gnat} that are specified in package @code{Compiler}
11453 could have been placed in package @code{Builder}, since @command{gnatmake}
11454 transmits all such ^switches^switches^ to the compiler.
11455
11456 @node Main Subprograms
11457 @unnumberedsubsubsec Main Subprograms
11458
11459 @noindent
11460 One of the specifiable properties of a project is a list of files that contain
11461 main subprograms.  This property is captured in the @code{Main} attribute,
11462 whose value is a list of strings.  If a project defines the @code{Main}
11463 attribute, it is not necessary to identify the main subprogram(s) when
11464 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
11465
11466 @node Executable File Names
11467 @unnumberedsubsubsec Executable File Names
11468
11469 @noindent
11470 By default, the executable file name corresponding to a main source is
11471 deduced from the main source file name. Through the attributes
11472 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
11473 it is possible to change this default.
11474 In project @code{Debug} above, the executable file name
11475 for main source @file{^proc.adb^PROC.ADB^} is
11476 @file{^proc1^PROC1.EXE^}.
11477 Attribute @code{Executable_Suffix}, when specified, may change the suffix
11478 of the executable files, when no attribute @code{Executable} applies:
11479 its value replace the platform-specific executable suffix.
11480 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
11481 specify a non default executable file name when several mains are built at once
11482 in a single @command{gnatmake} command.
11483
11484 @node Source File Naming Conventions
11485 @unnumberedsubsubsec Source File Naming Conventions
11486
11487 @noindent
11488 Since the project files above do not specify any source file naming
11489 conventions, the GNAT defaults are used.  The mechanism for defining source
11490 file naming conventions -- a package named @code{Naming} --
11491 is described below (@pxref{Naming Schemes}).
11492
11493 @node Source Language(s)
11494 @unnumberedsubsubsec Source Language(s)
11495
11496 @noindent
11497 Since the project files do not specify a @code{Languages} attribute, by
11498 default the GNAT tools assume that the language of the project file is Ada.
11499 More generally, a project can comprise source files
11500 in Ada, C, and/or other languages.
11501
11502 @node Using External Variables
11503 @subsection Using External Variables
11504
11505 @noindent
11506 Instead of supplying different project files for debug and release, we can
11507 define a single project file that queries an external variable (set either
11508 on the command line or via an ^environment variable^logical name^) in order to
11509 conditionally define the appropriate settings.  Again, assume that the
11510 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
11511 located in directory @file{^/common^[COMMON]^}.  The following project file,
11512 @file{build.gpr}, queries the external variable named @code{STYLE} and
11513 defines an object directory and ^switch^switch^ settings based on whether
11514 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
11515 the default is @code{"deb"}.
11516
11517 @smallexample @c projectfile
11518 @group
11519 project Build is
11520   for Main use ("proc");
11521
11522   type Style_Type is ("deb", "rel");
11523   Style : Style_Type := external ("STYLE", "deb");
11524
11525   case Style is
11526     when "deb" =>
11527       for Object_Dir use "debug";
11528
11529     when "rel" =>
11530       for Object_Dir use "release";
11531       for Exec_Dir use ".";
11532   end case;
11533 @end group
11534
11535 @group
11536   package Builder is
11537
11538     case Style is
11539       when "deb" =>
11540         for ^Default_Switches^Default_Switches^ ("Ada")
11541             use ("^-g^-g^");
11542         for Executable ("proc") use "proc1";
11543       when others =>
11544         null;
11545     end case;
11546
11547   end Builder;
11548 @end group
11549
11550 @group
11551   package Compiler is
11552
11553     case Style is
11554       when "deb" =>
11555         for ^Default_Switches^Default_Switches^ ("Ada")
11556             use ("^-gnata^-gnata^",
11557                  "^-gnato^-gnato^",
11558                  "^-gnatE^-gnatE^");
11559
11560       when "rel" =>
11561         for ^Default_Switches^Default_Switches^ ("Ada")
11562             use ("^-O2^-O2^");
11563     end case;
11564
11565   end Compiler;
11566
11567 end Build;
11568 @end group
11569 @end smallexample
11570
11571 @noindent
11572 @code{Style_Type} is an example of a @emph{string type}, which is the project
11573 file analog of an Ada enumeration type but whose components are string literals
11574 rather than identifiers.  @code{Style} is declared as a variable of this type.
11575
11576 The form @code{external("STYLE", "deb")} is known as an
11577 @emph{external reference}; its first argument is the name of an
11578 @emph{external variable}, and the second argument is a default value to be
11579 used if the external variable doesn't exist.  You can define an external
11580 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
11581 or you can use ^an environment variable^a logical name^
11582 as an external variable.
11583
11584 Each @code{case} construct is expanded by the Project Manager based on the
11585 value of @code{Style}. Thus the command
11586 @ifclear vms
11587 @smallexample
11588 gnatmake -P/common/build.gpr -XSTYLE=deb
11589 @end smallexample
11590 @end ifclear
11591
11592 @ifset vms
11593 @smallexample
11594 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
11595 @end smallexample
11596 @end ifset
11597
11598 @noindent
11599 is equivalent to the @command{gnatmake} invocation using the project file
11600 @file{debug.gpr} in the earlier example.  So is the command
11601 @smallexample
11602 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
11603 @end smallexample
11604
11605 @noindent
11606 since @code{"deb"} is the default for @code{STYLE}.
11607
11608 Analogously,
11609
11610 @ifclear vms
11611 @smallexample
11612 gnatmake -P/common/build.gpr -XSTYLE=rel
11613 @end smallexample
11614 @end ifclear
11615
11616 @ifset vms
11617 @smallexample
11618 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
11619 @end smallexample
11620 @end ifset
11621
11622 @noindent
11623 is equivalent to the @command{gnatmake} invocation using the project file
11624 @file{release.gpr} in the earlier example.
11625
11626 @node Importing Other Projects
11627 @subsection Importing Other Projects
11628 @cindex @code{ADA_PROJECT_PATH}
11629
11630 @noindent
11631 A compilation unit in a source file in one project may depend on compilation
11632 units in source files in other projects.  To compile this unit under
11633 control of a project file, the
11634 dependent project must @emph{import} the projects containing the needed source
11635 files.
11636 This effect is obtained using syntax similar to an Ada @code{with} clause,
11637 but where @code{with}ed entities are strings that denote project files.
11638
11639 As an example, suppose that the two projects @code{GUI_Proj} and
11640 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
11641 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
11642 and @file{^/comm^[COMM]^}, respectively.
11643 Suppose that the source files for @code{GUI_Proj} are
11644 @file{gui.ads} and @file{gui.adb}, and that the source files for
11645 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
11646 files is located in its respective project file directory.  Schematically:
11647
11648 @smallexample
11649 @group
11650 ^/gui^[GUI]^
11651   gui_proj.gpr
11652   gui.ads
11653   gui.adb
11654 @end group
11655
11656 @group
11657 ^/comm^[COMM]^
11658   comm_proj.gpr
11659   comm.ads
11660   comm.adb
11661 @end group
11662 @end smallexample
11663
11664 @noindent
11665 We want to develop an application in directory @file{^/app^[APP]^} that
11666 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
11667 the corresponding project files (e.g. the ^switch^switch^ settings
11668 and object directory).
11669 Skeletal code for a main procedure might be something like the following:
11670
11671 @smallexample @c ada
11672 @group
11673 with GUI, Comm;
11674 procedure App_Main is
11675    ...
11676 begin
11677    ...
11678 end App_Main;
11679 @end group
11680 @end smallexample
11681
11682 @noindent
11683 Here is a project file, @file{app_proj.gpr}, that achieves the desired
11684 effect:
11685
11686 @smallexample @c projectfile
11687 @group
11688 with "/gui/gui_proj", "/comm/comm_proj";
11689 project App_Proj is
11690    for Main use ("app_main");
11691 end App_Proj;
11692 @end group
11693 @end smallexample
11694
11695 @noindent
11696 Building an executable is achieved through the command:
11697 @smallexample
11698 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
11699 @end smallexample
11700 @noindent
11701 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
11702 in the directory where @file{app_proj.gpr} resides.
11703
11704 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
11705 (as illustrated above) the @code{with} clause can omit the extension.
11706
11707 Our example specified an absolute path for each imported project file.
11708 Alternatively, the directory name of an imported object can be omitted
11709 if either
11710 @itemize @bullet
11711 @item
11712 The imported project file is in the same directory as the importing project
11713 file, or
11714 @item
11715 You have defined ^an environment variable^a logical name^
11716 that includes the directory containing
11717 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
11718 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
11719 directory names separated by colons (semicolons on Windows).
11720 @end itemize
11721
11722 @noindent
11723 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
11724 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
11725 as follows:
11726
11727 @smallexample @c projectfile
11728 @group
11729 with "gui_proj", "comm_proj";
11730 project App_Proj is
11731    for Main use ("app_main");
11732 end App_Proj;
11733 @end group
11734 @end smallexample
11735
11736 @noindent
11737 Importing other projects can create ambiguities.
11738 For example, the same unit might be present in different imported projects, or
11739 it might be present in both the importing project and in an imported project.
11740 Both of these conditions are errors.  Note that in the current version of
11741 the Project Manager, it is illegal to have an ambiguous unit even if the
11742 unit is never referenced by the importing project.  This restriction may be
11743 relaxed in a future release.
11744
11745 @node Extending a Project
11746 @subsection Extending a Project
11747
11748 @noindent
11749 In large software systems it is common to have multiple
11750 implementations of a common interface; in Ada terms, multiple versions of a
11751 package body for the same specification.  For example, one implementation
11752 might be safe for use in tasking programs, while another might only be used
11753 in sequential applications.  This can be modeled in GNAT using the concept
11754 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
11755 another project (the ``parent'') then by default all source files of the
11756 parent project are inherited by the child, but the child project can
11757 override any of the parent's source files with new versions, and can also
11758 add new files.  This facility is the project analog of a type extension in
11759 Object-Oriented Programming.  Project hierarchies are permitted (a child
11760 project may be the parent of yet another project), and a project that
11761 inherits one project can also import other projects.
11762
11763 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11764 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11765 @file{pack.adb}, and @file{proc.adb}:
11766
11767 @smallexample
11768 @group
11769 ^/seq^[SEQ]^
11770   pack.ads
11771   pack.adb
11772   proc.adb
11773   seq_proj.gpr
11774 @end group
11775 @end smallexample
11776
11777 @noindent
11778 Note that the project file can simply be empty (that is, no attribute or
11779 package is defined):
11780
11781 @smallexample @c projectfile
11782 @group
11783 project Seq_Proj is
11784 end Seq_Proj;
11785 @end group
11786 @end smallexample
11787
11788 @noindent
11789 implying that its source files are all the Ada source files in the project
11790 directory.
11791
11792 Suppose we want to supply an alternate version of @file{pack.adb}, in
11793 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11794 @file{pack.ads} and @file{proc.adb}.  We can define a project
11795 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11796
11797 @smallexample
11798 @group
11799 ^/tasking^[TASKING]^
11800   pack.adb
11801   tasking_proj.gpr
11802 @end group
11803
11804 @group
11805 project Tasking_Proj extends "/seq/seq_proj" is
11806 end Tasking_Proj;
11807 @end group
11808 @end smallexample
11809
11810 @noindent
11811 The version of @file{pack.adb} used in a build depends on which project file
11812 is specified.
11813
11814 Note that we could have obtained the desired behavior using project import
11815 rather than project inheritance; a @code{base} project would contain the
11816 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11817 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11818 would import @code{base} and add a different version of @file{pack.adb}.  The
11819 choice depends on whether other sources in the original project need to be
11820 overridden.  If they do, then project extension is necessary, otherwise,
11821 importing is sufficient.
11822
11823 @noindent
11824 In a project file that extends another project file, it is possible to
11825 indicate that an inherited source is not part of the sources of the extending
11826 project. This is necessary sometimes when a package spec has been overloaded
11827 and no longer requires a body: in this case, it is necessary to indicate that
11828 the inherited body is not part of the sources of the project, otherwise there
11829 will be a compilation error when compiling the spec.
11830
11831 For that purpose, the attribute @code{Excluded_Source_Files} is used.
11832 Its value is a string list: a list of file names.
11833
11834 @smallexample @c @projectfile
11835 project B extends "a" is
11836    for Source_Files use ("pkg.ads");
11837    --  New spec of Pkg does not need a completion
11838    for Excluded_Source_Files use ("pkg.adb");
11839 end B;
11840 @end smallexample
11841
11842 Attribute @code{Excluded_Source_Files} may also be used to check if a source
11843 is still needed: if it is possible to build using @command{gnatmake} when such
11844 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
11845 it is possible to remove the source completely from a system that includes
11846 project P.
11847
11848 @c ***********************
11849 @c * Project File Syntax *
11850 @c ***********************
11851
11852 @node Project File Syntax
11853 @section Project File Syntax
11854
11855 @menu
11856 * Basic Syntax::
11857 * Packages::
11858 * Expressions::
11859 * String Types::
11860 * Variables::
11861 * Attributes::
11862 * Associative Array Attributes::
11863 * case Constructions::
11864 @end menu
11865
11866 @noindent
11867 This section describes the structure of project files.
11868
11869 A project may be an @emph{independent project}, entirely defined by a single
11870 project file. Any Ada source file in an independent project depends only
11871 on the predefined library and other Ada source files in the same project.
11872
11873 @noindent
11874 A project may also @dfn{depend on} other projects, in either or both of
11875 the following ways:
11876 @itemize @bullet
11877 @item It may import any number of projects
11878 @item It may extend at most one other project
11879 @end itemize
11880
11881 @noindent
11882 The dependence relation is a directed acyclic graph (the subgraph reflecting
11883 the ``extends'' relation is a tree).
11884
11885 A project's @dfn{immediate sources} are the source files directly defined by
11886 that project, either implicitly by residing in the project file's directory,
11887 or explicitly through any of the source-related attributes described below.
11888 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11889 of @var{proj} together with the immediate sources (unless overridden) of any
11890 project on which @var{proj} depends (either directly or indirectly).
11891
11892 @node Basic Syntax
11893 @subsection Basic Syntax
11894
11895 @noindent
11896 As seen in the earlier examples, project files have an Ada-like syntax.
11897 The minimal project file is:
11898 @smallexample @c projectfile
11899 @group
11900 project Empty is
11901
11902 end Empty;
11903 @end group
11904 @end smallexample
11905
11906 @noindent
11907 The identifier @code{Empty} is the name of the project.
11908 This project name must be present after the reserved
11909 word @code{end} at the end of the project file, followed by a semi-colon.
11910
11911 Any name in a project file, such as the project name or a variable name,
11912 has the same syntax as an Ada identifier.
11913
11914 The reserved words of project files are the Ada reserved words plus
11915 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11916 reserved words currently used in project file syntax are:
11917
11918 @itemize @bullet
11919 @item
11920 @code{case}
11921 @item
11922 @code{end}
11923 @item
11924 @code{for}
11925 @item
11926 @code{is}
11927 @item
11928 @code{others}
11929 @item
11930 @code{package}
11931 @item
11932 @code{renames}
11933 @item
11934 @code{type}
11935 @item
11936 @code{use}
11937 @item
11938 @code{when}
11939 @item
11940 @code{with}
11941 @end itemize
11942
11943 @noindent
11944 Comments in project files have the same syntax as in Ada, two consecutives
11945 hyphens through the end of the line.
11946
11947 @node Packages
11948 @subsection Packages
11949
11950 @noindent
11951 A project file may contain @emph{packages}. The name of a package must be one
11952 of the identifiers from the following list. A package
11953 with a given name may only appear once in a project file. Package names are
11954 case insensitive. The following package names are legal:
11955
11956 @itemize @bullet
11957 @item
11958 @code{Naming}
11959 @item
11960 @code{Builder}
11961 @item
11962 @code{Compiler}
11963 @item
11964 @code{Binder}
11965 @item
11966 @code{Linker}
11967 @item
11968 @code{Finder}
11969 @item
11970 @code{Cross_Reference}
11971 @item
11972 @code{Eliminate}
11973 @item
11974 @code{Pretty_Printer}
11975 @item
11976 @code{Metrics}
11977 @item
11978 @code{gnatls}
11979 @item
11980 @code{gnatstub}
11981 @item
11982 @code{IDE}
11983 @item
11984 @code{Language_Processing}
11985 @end itemize
11986
11987 @noindent
11988 In its simplest form, a package may be empty:
11989
11990 @smallexample @c projectfile
11991 @group
11992 project Simple is
11993   package Builder is
11994   end Builder;
11995 end Simple;
11996 @end group
11997 @end smallexample
11998
11999 @noindent
12000 A package may contain @emph{attribute declarations},
12001 @emph{variable declarations} and @emph{case constructions}, as will be
12002 described below.
12003
12004 When there is ambiguity between a project name and a package name,
12005 the name always designates the project. To avoid possible confusion, it is
12006 always a good idea to avoid naming a project with one of the
12007 names allowed for packages or any name that starts with @code{gnat}.
12008
12009 @node Expressions
12010 @subsection Expressions
12011
12012 @noindent
12013 An @emph{expression} is either a @emph{string expression} or a
12014 @emph{string list expression}.
12015
12016 A @emph{string expression} is either a @emph{simple string expression} or a
12017 @emph{compound string expression}.
12018
12019 A @emph{simple string expression} is one of the following:
12020 @itemize @bullet
12021 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
12022 @item A string-valued variable reference (@pxref{Variables})
12023 @item A string-valued attribute reference (@pxref{Attributes})
12024 @item An external reference (@pxref{External References in Project Files})
12025 @end itemize
12026
12027 @noindent
12028 A @emph{compound string expression} is a concatenation of string expressions,
12029 using the operator @code{"&"}
12030 @smallexample
12031        Path & "/" & File_Name & ".ads"
12032 @end smallexample
12033
12034 @noindent
12035 A @emph{string list expression} is either a
12036 @emph{simple string list expression} or a
12037 @emph{compound string list expression}.
12038
12039 A @emph{simple string list expression} is one of the following:
12040 @itemize @bullet
12041 @item A parenthesized list of zero or more string expressions,
12042 separated by commas
12043 @smallexample
12044    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12045    Empty_List := ();
12046 @end smallexample
12047 @item A string list-valued variable reference
12048 @item A string list-valued attribute reference
12049 @end itemize
12050
12051 @noindent
12052 A @emph{compound string list expression} is the concatenation (using
12053 @code{"&"}) of a simple string list expression and an expression.  Note that
12054 each term in a compound string list expression, except the first, may be
12055 either a string expression or a string list expression.
12056
12057 @smallexample @c projectfile
12058 @group
12059    File_Name_List := () & File_Name; --  One string in this list
12060    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12061    --  Two strings
12062    Big_List := File_Name_List & Extended_File_Name_List;
12063    --  Concatenation of two string lists: three strings
12064    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12065    --  Illegal: must start with a string list
12066 @end group
12067 @end smallexample
12068
12069 @node String Types
12070 @subsection String Types
12071
12072 @noindent
12073 A @emph{string type declaration} introduces a discrete set of string literals.
12074 If a string variable is declared to have this type, its value
12075 is restricted to the given set of literals.
12076
12077 Here is an example of a string type declaration:
12078
12079 @smallexample @c projectfile
12080    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12081 @end smallexample
12082
12083 @noindent
12084 Variables of a string type are called @emph{typed variables}; all other
12085 variables are called @emph{untyped variables}. Typed variables are
12086 particularly useful in @code{case} constructions, to support conditional
12087 attribute declarations.
12088 (@pxref{case Constructions}).
12089
12090 The string literals in the list are case sensitive and must all be different.
12091 They may include any graphic characters allowed in Ada, including spaces.
12092
12093 A string type may only be declared at the project level, not inside a package.
12094
12095 A string type may be referenced by its name if it has been declared in the same
12096 project file, or by an expanded name whose prefix is the name of the project
12097 in which it is declared.
12098
12099 @node Variables
12100 @subsection Variables
12101
12102 @noindent
12103 A variable may be declared at the project file level, or within a package.
12104 Here are some examples of variable declarations:
12105
12106 @smallexample @c projectfile
12107 @group
12108    This_OS : OS := external ("OS"); --  a typed variable declaration
12109    That_OS := "GNU/Linux";          --  an untyped variable declaration
12110 @end group
12111 @end smallexample
12112
12113 @noindent
12114 The syntax of a @emph{typed variable declaration} is identical to the Ada
12115 syntax for an object declaration. By contrast, the syntax of an untyped
12116 variable declaration is identical to an Ada assignment statement. In fact,
12117 variable declarations in project files have some of the characteristics of
12118 an assignment, in that successive declarations for the same variable are
12119 allowed. Untyped variable declarations do establish the expected kind of the
12120 variable (string or string list), and successive declarations for it must
12121 respect the initial kind.
12122
12123 @noindent
12124 A string variable declaration (typed or untyped) declares a variable
12125 whose value is a string. This variable may be used as a string expression.
12126 @smallexample @c projectfile
12127    File_Name       := "readme.txt";
12128    Saved_File_Name := File_Name & ".saved";
12129 @end smallexample
12130
12131 @noindent
12132 A string list variable declaration declares a variable whose value is a list
12133 of strings. The list may contain any number (zero or more) of strings.
12134
12135 @smallexample @c projectfile
12136    Empty_List := ();
12137    List_With_One_Element := ("^-gnaty^-gnaty^");
12138    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12139    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12140                  "pack2.ada", "util_.ada", "util.ada");
12141 @end smallexample
12142
12143 @noindent
12144 The same typed variable may not be declared more than once at project level,
12145 and it may not be declared more than once in any package; it is in effect
12146 a constant.
12147
12148 The same untyped variable may be declared several times. Declarations are
12149 elaborated in the order in which they appear, so  the new value replaces
12150 the old one, and any subsequent reference to the variable uses the new value.
12151 However, as noted above, if a variable has been declared as a string, all
12152 subsequent
12153 declarations must give it a string value. Similarly, if a variable has
12154 been declared as a string list, all subsequent declarations
12155 must give it a string list value.
12156
12157 A @emph{variable reference} may take several forms:
12158
12159 @itemize @bullet
12160 @item The simple variable name, for a variable in the current package (if any)
12161 or in the current project
12162 @item An expanded name, whose prefix is a context name.
12163 @end itemize
12164
12165 @noindent
12166 A @emph{context} may be one of the following:
12167
12168 @itemize @bullet
12169 @item The name of an existing package in the current project
12170 @item The name of an imported project of the current project
12171 @item The name of an ancestor project (i.e., a project extended by the current
12172 project, either directly or indirectly)
12173 @item An expanded name whose prefix is an imported/parent project name, and
12174 whose selector is a package name in that project.
12175 @end itemize
12176
12177 @noindent
12178 A variable reference may be used in an expression.
12179
12180 @node Attributes
12181 @subsection Attributes
12182
12183 @noindent
12184 A project (and its packages) may have @emph{attributes} that define
12185 the project's properties.  Some attributes have values that are strings;
12186 others have values that are string lists.
12187
12188 There are two categories of attributes: @emph{simple attributes}
12189 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12190
12191 Legal project attribute names, and attribute names for each legal package are
12192 listed below. Attributes names are case-insensitive.
12193
12194 The following attributes are defined on projects (all are simple attributes):
12195
12196 @multitable @columnfractions .4 .3
12197 @item @emph{Attribute Name}
12198 @tab @emph{Value}
12199 @item @code{Source_Files}
12200 @tab string list
12201 @item @code{Source_Dirs}
12202 @tab string list
12203 @item @code{Source_List_File}
12204 @tab string
12205 @item @code{Object_Dir}
12206 @tab string
12207 @item @code{Exec_Dir}
12208 @tab string
12209 @item @code{Excluded_Source_Dirs}
12210 @tab string list
12211 @item @code{Excluded_Source_Files}
12212 @tab string list
12213 @item @code{Languages}
12214 @tab string list
12215 @item @code{Main}
12216 @tab string list
12217 @item @code{Library_Dir}
12218 @tab string
12219 @item @code{Library_Name}
12220 @tab string
12221 @item @code{Library_Kind}
12222 @tab string
12223 @item @code{Library_Version}
12224 @tab string
12225 @item @code{Library_Interface}
12226 @tab string
12227 @item @code{Library_Auto_Init}
12228 @tab string
12229 @item @code{Library_Options}
12230 @tab string list
12231 @item @code{Library_Src_Dir}
12232 @tab string
12233 @item @code{Library_ALI_Dir}
12234 @tab string
12235 @item @code{Library_GCC}
12236 @tab string
12237 @item @code{Library_Symbol_File}
12238 @tab string
12239 @item @code{Library_Symbol_Policy}
12240 @tab string
12241 @item @code{Library_Reference_Symbol_File}
12242 @tab string
12243 @item @code{Externally_Built}
12244 @tab string
12245 @end multitable
12246
12247 @noindent
12248 The following attributes are defined for package  @code{Naming}
12249 (@pxref{Naming Schemes}):
12250
12251 @multitable @columnfractions .4 .2 .2 .2
12252 @item Attribute Name @tab Category @tab Index @tab Value
12253 @item @code{Spec_Suffix}
12254 @tab associative array
12255 @tab language name
12256 @tab string
12257 @item @code{Body_Suffix}
12258 @tab associative array
12259 @tab language name
12260 @tab string
12261 @item @code{Separate_Suffix}
12262 @tab simple attribute
12263 @tab n/a
12264 @tab string
12265 @item @code{Casing}
12266 @tab simple attribute
12267 @tab n/a
12268 @tab string
12269 @item @code{Dot_Replacement}
12270 @tab simple attribute
12271 @tab n/a
12272 @tab string
12273 @item @code{Spec}
12274 @tab associative array
12275 @tab Ada unit name
12276 @tab string
12277 @item @code{Body}
12278 @tab associative array
12279 @tab Ada unit name
12280 @tab string
12281 @item @code{Specification_Exceptions}
12282 @tab associative array
12283 @tab language name
12284 @tab string list
12285 @item @code{Implementation_Exceptions}
12286 @tab associative array
12287 @tab language name
12288 @tab string list
12289 @end multitable
12290
12291 @noindent
12292 The following attributes are defined for packages @code{Builder},
12293 @code{Compiler}, @code{Binder},
12294 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12295 (@pxref{^Switches^Switches^ and Project Files}).
12296
12297 @multitable @columnfractions .4 .2 .2 .2
12298 @item Attribute Name @tab Category @tab Index @tab Value
12299 @item @code{^Default_Switches^Default_Switches^}
12300 @tab associative array
12301 @tab language name
12302 @tab string list
12303 @item @code{^Switches^Switches^}
12304 @tab associative array
12305 @tab file name
12306 @tab string list
12307 @end multitable
12308
12309 @noindent
12310 In addition, package @code{Compiler} has a single string attribute
12311 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12312 string attribute @code{Global_Configuration_Pragmas}.
12313
12314 @noindent
12315 Each simple attribute has a default value: the empty string (for string-valued
12316 attributes) and the empty list (for string list-valued attributes).
12317
12318 An attribute declaration defines a new value for an attribute.
12319
12320 Examples of simple attribute declarations:
12321
12322 @smallexample @c projectfile
12323    for Object_Dir use "objects";
12324    for Source_Dirs use ("units", "test/drivers");
12325 @end smallexample
12326
12327 @noindent
12328 The syntax of a @dfn{simple attribute declaration} is similar to that of an
12329 attribute definition clause in Ada.
12330
12331 Attributes references may be appear in expressions.
12332 The general form for such a reference is @code{<entity>'<attribute>}:
12333 Associative array attributes are functions. Associative
12334 array attribute references must have an argument that is a string literal.
12335
12336 Examples are:
12337
12338 @smallexample @c projectfile
12339   project'Object_Dir
12340   Naming'Dot_Replacement
12341   Imported_Project'Source_Dirs
12342   Imported_Project.Naming'Casing
12343   Builder'^Default_Switches^Default_Switches^("Ada")
12344 @end smallexample
12345
12346 @noindent
12347 The prefix of an attribute may be:
12348 @itemize @bullet
12349 @item @code{project} for an attribute of the current project
12350 @item The name of an existing package of the current project
12351 @item The name of an imported project
12352 @item The name of a parent project that is extended by the current project
12353 @item An expanded name whose prefix is imported/parent project name,
12354       and whose selector is a package name
12355 @end itemize
12356
12357 @noindent
12358 Example:
12359 @smallexample @c projectfile
12360 @group
12361    project Prj is
12362      for Source_Dirs use project'Source_Dirs & "units";
12363      for Source_Dirs use project'Source_Dirs & "test/drivers"
12364    end Prj;
12365 @end group
12366 @end smallexample
12367
12368 @noindent
12369 In the first attribute declaration, initially the attribute @code{Source_Dirs}
12370 has the default value: an empty string list. After this declaration,
12371 @code{Source_Dirs} is a string list of one element: @code{"units"}.
12372 After the second attribute declaration @code{Source_Dirs} is a string list of
12373 two elements: @code{"units"} and @code{"test/drivers"}.
12374
12375 Note: this example is for illustration only. In practice,
12376 the project file would contain only one attribute declaration:
12377
12378 @smallexample @c projectfile
12379    for Source_Dirs use ("units", "test/drivers");
12380 @end smallexample
12381
12382 @node Associative Array Attributes
12383 @subsection Associative Array Attributes
12384
12385 @noindent
12386 Some attributes are defined as @emph{associative arrays}. An associative
12387 array may be regarded as a function that takes a string as a parameter
12388 and delivers a string or string list value as its result.
12389
12390 Here are some examples of single associative array attribute associations:
12391
12392 @smallexample @c projectfile
12393    for Body ("main") use "Main.ada";
12394    for ^Switches^Switches^ ("main.ada")
12395        use ("^-v^-v^",
12396             "^-gnatv^-gnatv^");
12397    for ^Switches^Switches^ ("main.ada")
12398             use Builder'^Switches^Switches^ ("main.ada")
12399               & "^-g^-g^";
12400 @end smallexample
12401
12402 @noindent
12403 Like untyped variables and simple attributes, associative array attributes
12404 may be declared several times. Each declaration supplies a new value for the
12405 attribute, and replaces the previous setting.
12406
12407 @noindent
12408 An associative array attribute may be declared as a full associative array
12409 declaration, with the value of the same attribute in an imported or extended
12410 project.
12411
12412 @smallexample @c projectfile
12413    package Builder is
12414       for Default_Switches use Default.Builder'Default_Switches;
12415    end Builder;
12416 @end smallexample
12417
12418 @noindent
12419 In this example, @code{Default} must be either a project imported by the
12420 current project, or the project that the current project extends. If the
12421 attribute is in a package (in this case, in package @code{Builder}), the same
12422 package needs to be specified.
12423
12424 @noindent
12425 A full associative array declaration replaces any other declaration for the
12426 attribute, including other full associative array declaration. Single
12427 associative array associations may be declare after a full associative
12428 declaration, modifying the value for a single association of the attribute.
12429
12430 @node case Constructions
12431 @subsection @code{case} Constructions
12432
12433 @noindent
12434 A @code{case} construction is used in a project file to effect conditional
12435 behavior.
12436 Here is a typical example:
12437
12438 @smallexample @c projectfile
12439 @group
12440 project MyProj is
12441    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
12442
12443    OS : OS_Type := external ("OS", "GNU/Linux");
12444 @end group
12445
12446 @group
12447    package Compiler is
12448      case OS is
12449        when "GNU/Linux" | "Unix" =>
12450          for ^Default_Switches^Default_Switches^ ("Ada")
12451              use ("^-gnath^-gnath^");
12452        when "NT" =>
12453          for ^Default_Switches^Default_Switches^ ("Ada")
12454              use ("^-gnatP^-gnatP^");
12455        when others =>
12456      end case;
12457    end Compiler;
12458 end MyProj;
12459 @end group
12460 @end smallexample
12461
12462 @noindent
12463 The syntax of a @code{case} construction is based on the Ada case statement
12464 (although there is no @code{null} construction for empty alternatives).
12465
12466 The case expression must be a typed string variable.
12467 Each alternative comprises the reserved word @code{when}, either a list of
12468 literal strings separated by the @code{"|"} character or the reserved word
12469 @code{others},  and the @code{"=>"} token.
12470 Each literal string must belong to the string type that is the type of the
12471 case variable.
12472 An @code{others} alternative, if present, must occur last.
12473
12474 After each @code{=>}, there are zero or more constructions.  The only
12475 constructions allowed in a case construction are other case constructions,
12476 attribute declarations and variable declarations. String type declarations and
12477 package declarations are not allowed. Variable declarations are restricted to
12478 variables that have already been declared before the case construction.
12479
12480 The value of the case variable is often given by an external reference
12481 (@pxref{External References in Project Files}).
12482
12483 @c ****************************************
12484 @c * Objects and Sources in Project Files *
12485 @c ****************************************
12486
12487 @node Objects and Sources in Project Files
12488 @section Objects and Sources in Project Files
12489
12490 @menu
12491 * Object Directory::
12492 * Exec Directory::
12493 * Source Directories::
12494 * Source File Names::
12495 @end menu
12496
12497 @noindent
12498 Each project has exactly one object directory and one or more source
12499 directories. The source directories must contain at least one source file,
12500 unless  the project file explicitly specifies that no source files are present
12501 (@pxref{Source File Names}).
12502
12503 @node Object Directory
12504 @subsection Object Directory
12505
12506 @noindent
12507 The object directory for a project is the directory containing the compiler's
12508 output (such as @file{ALI} files and object files) for the project's immediate
12509 sources.
12510
12511 The object directory is given by the value of the attribute @code{Object_Dir}
12512 in the project file.
12513
12514 @smallexample @c projectfile
12515    for Object_Dir use "objects";
12516 @end smallexample
12517
12518 @noindent
12519 The attribute @var{Object_Dir} has a string value, the path name of the object
12520 directory. The path name may be absolute or relative to the directory of the
12521 project file. This directory must already exist, and be readable and writable.
12522
12523 By default, when the attribute @code{Object_Dir} is not given an explicit value
12524 or when its value is the empty string, the object directory is the same as the
12525 directory containing the project file.
12526
12527 @node Exec Directory
12528 @subsection Exec Directory
12529
12530 @noindent
12531 The exec directory for a project is the directory containing the executables
12532 for the project's main subprograms.
12533
12534 The exec directory is given by the value of the attribute @code{Exec_Dir}
12535 in the project file.
12536
12537 @smallexample @c projectfile
12538    for Exec_Dir use "executables";
12539 @end smallexample
12540
12541 @noindent
12542 The attribute @var{Exec_Dir} has a string value, the path name of the exec
12543 directory. The path name may be absolute or relative to the directory of the
12544 project file. This directory must already exist, and be writable.
12545
12546 By default, when the attribute @code{Exec_Dir} is not given an explicit value
12547 or when its value is the empty string, the exec directory is the same as the
12548 object directory of the project file.
12549
12550 @node Source Directories
12551 @subsection Source Directories
12552
12553 @noindent
12554 The source directories of a project are specified by the project file
12555 attribute @code{Source_Dirs}.
12556
12557 This attribute's value is a string list. If the attribute is not given an
12558 explicit value, then there is only one source directory, the one where the
12559 project file resides.
12560
12561 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
12562 as in
12563
12564 @smallexample @c projectfile
12565     for Source_Dirs use ();
12566 @end smallexample
12567
12568 @noindent
12569 indicates that the project contains no source files.
12570
12571 Otherwise, each string in the string list designates one or more
12572 source directories.
12573
12574 @smallexample @c projectfile
12575    for Source_Dirs use ("sources", "test/drivers");
12576 @end smallexample
12577
12578 @noindent
12579 If a string in the list ends with @code{"/**"},  then the directory whose path
12580 name precedes the two asterisks, as well as all its subdirectories
12581 (recursively), are source directories.
12582
12583 @smallexample @c projectfile
12584    for Source_Dirs use ("/system/sources/**");
12585 @end smallexample
12586
12587 @noindent
12588 Here the directory @code{/system/sources} and all of its subdirectories
12589 (recursively) are source directories.
12590
12591 To specify that the source directories are the directory of the project file
12592 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
12593 @smallexample @c projectfile
12594    for Source_Dirs use ("./**");
12595 @end smallexample
12596
12597 @noindent
12598 Each of the source directories must exist and be readable.
12599
12600 @node Source File Names
12601 @subsection Source File Names
12602
12603 @noindent
12604 In a project that contains source files, their names may be specified by the
12605 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
12606 (a string). Source file names never include any directory information.
12607
12608 If the attribute @code{Source_Files} is given an explicit value, then each
12609 element of the list is a source file name.
12610
12611 @smallexample @c projectfile
12612    for Source_Files use ("main.adb");
12613    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
12614 @end smallexample
12615
12616 @noindent
12617 If the attribute @code{Source_Files} is not given an explicit value,
12618 but the attribute @code{Source_List_File} is given a string value,
12619 then the source file names are contained in the text file whose path name
12620 (absolute or relative to the directory of the project file) is the
12621 value of the attribute @code{Source_List_File}.
12622
12623 Each line in the file that is not empty or is not a comment
12624 contains a source file name.
12625
12626 @smallexample @c projectfile
12627    for Source_List_File use "source_list.txt";
12628 @end smallexample
12629
12630 @noindent
12631 By default, if neither the attribute @code{Source_Files} nor the attribute
12632 @code{Source_List_File} is given an explicit value, then each file in the
12633 source directories that conforms to the project's naming scheme
12634 (@pxref{Naming Schemes}) is an immediate source of the project.
12635
12636 A warning is issued if both attributes @code{Source_Files} and
12637 @code{Source_List_File} are given explicit values. In this case, the attribute
12638 @code{Source_Files} prevails.
12639
12640 Each source file name must be the name of one existing source file
12641 in one of the source directories.
12642
12643 A @code{Source_Files} attribute whose value is an empty list
12644 indicates that there are no source files in the project.
12645
12646 If the order of the source directories is known statically, that is if
12647 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
12648 be several files with the same source file name. In this case, only the file
12649 in the first directory is considered as an immediate source of the project
12650 file. If the order of the source directories is not known statically, it is
12651 an error to have several files with the same source file name.
12652
12653 Projects can be specified to have no Ada source
12654 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
12655 list, or the @code{"Ada"} may be absent from @code{Languages}:
12656
12657 @smallexample @c projectfile
12658    for Source_Dirs use ();
12659    for Source_Files use ();
12660    for Languages use ("C", "C++");
12661 @end smallexample
12662
12663 @noindent
12664 Otherwise, a project must contain at least one immediate source.
12665
12666 Projects with no source files are useful as template packages
12667 (@pxref{Packages in Project Files}) for other projects; in particular to
12668 define a package @code{Naming} (@pxref{Naming Schemes}).
12669
12670 @c ****************************
12671 @c * Importing Projects *
12672 @c ****************************
12673
12674 @node  Importing Projects
12675 @section Importing Projects
12676 @cindex @code{ADA_PROJECT_PATH}
12677
12678 @noindent
12679 An immediate source of a project P may depend on source files that
12680 are neither immediate sources of P nor in the predefined library.
12681 To get this effect, P must @emph{import} the projects that contain the needed
12682 source files.
12683
12684 @smallexample @c projectfile
12685 @group
12686   with "project1", "utilities.gpr";
12687   with "/namings/apex.gpr";
12688   project Main is
12689     ...
12690 @end group
12691 @end smallexample
12692
12693 @noindent
12694 As can be seen in this example, the syntax for importing projects is similar
12695 to the syntax for importing compilation units in Ada. However, project files
12696 use literal strings instead of names, and the @code{with} clause identifies
12697 project files rather than packages.
12698
12699 Each literal string is the file name or path name (absolute or relative) of a
12700 project file. If a string corresponds to a file name, with no path or a
12701 relative path, then its location is determined by the @emph{project path}. The
12702 latter can be queried using @code{gnatls -v}. It contains:
12703
12704 @itemize @bullet
12705 @item
12706 In first position, the directory containing the current project file.
12707 @item
12708 In last position, the default project directory. This default project directory
12709 is part of the GNAT installation and is the standard place to install project
12710 files giving access to standard support libraries.
12711 @ifclear vms
12712 @ref{Installing a library}
12713 @end ifclear
12714
12715 @item
12716 In between, all the directories referenced in the
12717 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
12718 @end itemize
12719
12720 @noindent
12721 If a relative pathname is used, as in
12722
12723 @smallexample @c projectfile
12724   with "tests/proj";
12725 @end smallexample
12726
12727 @noindent
12728 then the full path for the project is constructed by concatenating this
12729 relative path to those in the project path, in order, until a matching file is
12730 found. Any symbolic link will be fully resolved in the directory of the
12731 importing project file before the imported project file is examined.
12732
12733 If the @code{with}'ed project file name does not have an extension,
12734 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
12735 then the file name as specified in the @code{with} clause (no extension) will
12736 be used. In the above example, if a file @code{project1.gpr} is found, then it
12737 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
12738 then it will be used; if neither file exists, this is an error.
12739
12740 A warning is issued if the name of the project file does not match the
12741 name of the project; this check is case insensitive.
12742
12743 Any source file that is an immediate source of the imported project can be
12744 used by the immediate sources of the importing project, transitively. Thus
12745 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
12746 sources of @code{A} may depend on the immediate sources of @code{C}, even if
12747 @code{A} does not import @code{C} explicitly. However, this is not recommended,
12748 because if and when @code{B} ceases to import @code{C}, some sources in
12749 @code{A} will no longer compile.
12750
12751 A side effect of this capability is that normally cyclic dependencies are not
12752 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
12753 is not allowed to import @code{A}. However, there are cases when cyclic
12754 dependencies would be beneficial. For these cases, another form of import
12755 between projects exists, the @code{limited with}: a project @code{A} that
12756 imports a project @code{B} with a straight @code{with} may also be imported,
12757 directly or indirectly, by @code{B} on the condition that imports from @code{B}
12758 to @code{A} include at least one @code{limited with}.
12759
12760 @smallexample @c 0projectfile
12761 with "../b/b.gpr";
12762 with "../c/c.gpr";
12763 project A is
12764 end A;
12765
12766 limited with "../a/a.gpr";
12767 project B is
12768 end B;
12769
12770 with "../d/d.gpr";
12771 project C is
12772 end C;
12773
12774 limited with "../a/a.gpr";
12775 project D is
12776 end D;
12777 @end smallexample
12778
12779 @noindent
12780 In the above legal example, there are two project cycles:
12781 @itemize @bullet
12782 @item A-> B-> A
12783 @item A -> C -> D -> A
12784 @end itemize
12785
12786 @noindent
12787 In each of these cycle there is one @code{limited with}: import of @code{A}
12788 from @code{B} and import of @code{A} from @code{D}.
12789
12790 The difference between straight @code{with} and @code{limited with} is that
12791 the name of a project imported with a @code{limited with} cannot be used in the
12792 project that imports it. In particular, its packages cannot be renamed and
12793 its variables cannot be referred to.
12794
12795 An exception to the above rules for @code{limited with} is that for the main
12796 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12797 @code{limited with} is equivalent to a straight @code{with}. For example,
12798 in the example above, projects @code{B} and @code{D} could not be main
12799 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12800 each have a @code{limited with} that is the only one in a cycle of importing
12801 projects.
12802
12803 @c *********************
12804 @c * Project Extension *
12805 @c *********************
12806
12807 @node Project Extension
12808 @section Project Extension
12809
12810 @noindent
12811 During development of a large system, it is sometimes necessary to use
12812 modified versions of some of the source files, without changing the original
12813 sources. This can be achieved through the @emph{project extension} facility.
12814
12815 @smallexample @c projectfile
12816    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12817 @end smallexample
12818
12819 @noindent
12820 A project extension declaration introduces an extending project
12821 (the @emph{child}) and a project being extended (the @emph{parent}).
12822
12823 By default, a child project inherits all the sources of its parent.
12824 However, inherited sources can be overridden: a unit in a parent is hidden
12825 by a unit of the same name in the child.
12826
12827 Inherited sources are considered to be sources (but not immediate sources)
12828 of the child project; see @ref{Project File Syntax}.
12829
12830 An inherited source file retains any switches specified in the parent project.
12831
12832 For example if the project @code{Utilities} contains the specification and the
12833 body of an Ada package @code{Util_IO}, then the project
12834 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12835 The original body of @code{Util_IO} will not be considered in program builds.
12836 However, the package specification will still be found in the project
12837 @code{Utilities}.
12838
12839 A child project can have only one parent but it may import any number of other
12840 projects.
12841
12842 A project is not allowed to import directly or indirectly at the same time a
12843 child project and any of its ancestors.
12844
12845 @c *******************************
12846 @c * Project Hierarchy Extension *
12847 @c *******************************
12848
12849 @node Project Hierarchy Extension
12850 @section Project Hierarchy Extension
12851
12852 @noindent
12853 When extending a large system spanning multiple projects, it is often
12854 inconvenient to extend every project in the hierarchy that is impacted by a
12855 small change introduced. In such cases, it is possible to create a virtual
12856 extension of entire hierarchy using @code{extends all} relationship.
12857
12858 When the project is extended using @code{extends all} inheritance, all projects
12859 that are imported by it, both directly and indirectly, are considered virtually
12860 extended. That is, the Project Manager creates "virtual projects"
12861 that extend every project in the hierarchy; all these virtual projects have
12862 no sources of their own and have as object directory the object directory of
12863 the root of "extending all" project.
12864
12865 It is possible to explicitly extend one or more projects in the hierarchy
12866 in order to modify the sources. These extending projects must be imported by
12867 the "extending all" project, which will replace the corresponding virtual
12868 projects with the explicit ones.
12869
12870 When building such a project hierarchy extension, the Project Manager will
12871 ensure that both modified sources and sources in virtual extending projects
12872 that depend on them, are recompiled.
12873
12874 By means of example, consider the following hierarchy of projects.
12875
12876 @enumerate
12877 @item
12878 project A, containing package P1
12879 @item
12880 project B importing A and containing package P2 which depends on P1
12881 @item
12882 project C importing B and containing package P3 which depends on P2
12883 @end enumerate
12884
12885 @noindent
12886 We want to modify packages P1 and P3.
12887
12888 This project hierarchy will need to be extended as follows:
12889
12890 @enumerate
12891 @item
12892 Create project A1 that extends A, placing modified P1 there:
12893
12894 @smallexample @c 0projectfile
12895 project A1 extends "(...)/A" is
12896 end A1;
12897 @end smallexample
12898
12899 @item
12900 Create project C1 that "extends all" C and imports A1, placing modified
12901 P3 there:
12902
12903 @smallexample @c 0projectfile
12904 with "(...)/A1";
12905 project C1 extends all "(...)/C" is
12906 end C1;
12907 @end smallexample
12908 @end enumerate
12909
12910 When you build project C1, your entire modified project space will be
12911 recompiled, including the virtual project B1 that has been impacted by the
12912 "extending all" inheritance of project C.
12913
12914 Note that if a Library Project in the hierarchy is virtually extended,
12915 the virtual project that extends the Library Project is not a Library Project.
12916
12917 @c ****************************************
12918 @c * External References in Project Files *
12919 @c ****************************************
12920
12921 @node  External References in Project Files
12922 @section External References in Project Files
12923
12924 @noindent
12925 A project file may contain references to external variables; such references
12926 are called @emph{external references}.
12927
12928 An external variable is either defined as part of the environment (an
12929 environment variable in Unix, for example) or else specified on the command
12930 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12931 If both, then the command line value is used.
12932
12933 The value of an external reference is obtained by means of the built-in
12934 function @code{external}, which returns a string value.
12935 This function has two forms:
12936 @itemize @bullet
12937 @item @code{external (external_variable_name)}
12938 @item @code{external (external_variable_name, default_value)}
12939 @end itemize
12940
12941 @noindent
12942 Each parameter must be a string literal.  For example:
12943
12944 @smallexample @c projectfile
12945    external ("USER")
12946    external ("OS", "GNU/Linux")
12947 @end smallexample
12948
12949 @noindent
12950 In the form with one parameter, the function returns the value of
12951 the external variable given as parameter. If this name is not present in the
12952 environment, the function returns an empty string.
12953
12954 In the form with two string parameters, the second argument is
12955 the value returned when the variable given as the first argument is not
12956 present in the environment. In the example above, if @code{"OS"} is not
12957 the name of ^an environment variable^a logical name^ and is not passed on
12958 the command line, then the returned value is @code{"GNU/Linux"}.
12959
12960 An external reference may be part of a string expression or of a string
12961 list expression, and can therefore appear in a variable declaration or
12962 an attribute declaration.
12963
12964 @smallexample @c projectfile
12965 @group
12966    type Mode_Type is ("Debug", "Release");
12967    Mode : Mode_Type := external ("MODE");
12968    case Mode is
12969      when "Debug" =>
12970         ...
12971 @end group
12972 @end smallexample
12973
12974 @c *****************************
12975 @c * Packages in Project Files *
12976 @c *****************************
12977
12978 @node  Packages in Project Files
12979 @section Packages in Project Files
12980
12981 @noindent
12982 A @emph{package} defines the settings for project-aware tools within a
12983 project.
12984 For each such tool one can declare a package; the names for these
12985 packages are preset (@pxref{Packages}).
12986 A package may contain variable declarations, attribute declarations, and case
12987 constructions.
12988
12989 @smallexample @c projectfile
12990 @group
12991    project Proj is
12992       package Builder is  -- used by gnatmake
12993          for ^Default_Switches^Default_Switches^ ("Ada")
12994              use ("^-v^-v^",
12995                   "^-g^-g^");
12996       end Builder;
12997    end Proj;
12998 @end group
12999 @end smallexample
13000
13001 @noindent
13002 The syntax of package declarations mimics that of package in Ada.
13003
13004 Most of the packages have an attribute
13005 @code{^Default_Switches^Default_Switches^}.
13006 This attribute is an associative array, and its value is a string list.
13007 The index of the associative array is the name of a programming language (case
13008 insensitive). This attribute indicates the ^switch^switch^
13009 or ^switches^switches^ to be used
13010 with the corresponding tool.
13011
13012 Some packages also have another attribute, @code{^Switches^Switches^},
13013 an associative array whose value is a string list.
13014 The index is the name of a source file.
13015 This attribute indicates the ^switch^switch^
13016 or ^switches^switches^ to be used by the corresponding
13017 tool when dealing with this specific file.
13018
13019 Further information on these ^switch^switch^-related attributes is found in
13020 @ref{^Switches^Switches^ and Project Files}.
13021
13022 A package may be declared as a @emph{renaming} of another package; e.g., from
13023 the project file for an imported project.
13024
13025 @smallexample @c projectfile
13026 @group
13027   with "/global/apex.gpr";
13028   project Example is
13029     package Naming renames Apex.Naming;
13030     ...
13031   end Example;
13032 @end group
13033 @end smallexample
13034
13035 @noindent
13036 Packages that are renamed in other project files often come from project files
13037 that have no sources: they are just used as templates. Any modification in the
13038 template will be reflected automatically in all the project files that rename
13039 a package from the template.
13040
13041 In addition to the tool-oriented packages, you can also declare a package
13042 named @code{Naming} to establish specialized source file naming conventions
13043 (@pxref{Naming Schemes}).
13044
13045 @c ************************************
13046 @c * Variables from Imported Projects *
13047 @c ************************************
13048
13049 @node Variables from Imported Projects
13050 @section Variables from Imported Projects
13051
13052 @noindent
13053 An attribute or variable defined in an imported or parent project can
13054 be used in expressions in the importing / extending project.
13055 Such an attribute or variable is denoted by an expanded name whose prefix
13056 is either the name of the project or the expanded name of a package within
13057 a project.
13058
13059 @smallexample @c projectfile
13060 @group
13061   with "imported";
13062   project Main extends "base" is
13063      Var1 := Imported.Var;
13064      Var2 := Base.Var & ".new";
13065 @end group
13066
13067 @group
13068      package Builder is
13069         for ^Default_Switches^Default_Switches^ ("Ada")
13070             use Imported.Builder'Ada_^Switches^Switches^ &
13071                 "^-gnatg^-gnatg^" &
13072                 "^-v^-v^";
13073      end Builder;
13074 @end group
13075
13076 @group
13077      package Compiler is
13078         for ^Default_Switches^Default_Switches^ ("Ada")
13079             use Base.Compiler'Ada_^Switches^Switches^;
13080      end Compiler;
13081   end Main;
13082 @end group
13083 @end smallexample
13084
13085 @noindent
13086 In this example:
13087
13088 @itemize @bullet
13089 @item
13090 The value of @code{Var1} is a copy of the variable @code{Var} defined
13091 in the project file @file{"imported.gpr"}
13092 @item
13093 the value of @code{Var2} is a copy of the value of variable @code{Var}
13094 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13095 @item
13096 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13097 @code{Builder} is a string list that includes in its value a copy of the value
13098 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13099 in project file @file{imported.gpr} plus two new elements:
13100 @option{"^-gnatg^-gnatg^"}
13101 and @option{"^-v^-v^"};
13102 @item
13103 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13104 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13105 defined in the @code{Compiler} package in project file @file{base.gpr},
13106 the project being extended.
13107 @end itemize
13108
13109 @c ******************
13110 @c * Naming Schemes *
13111 @c ******************
13112
13113 @node  Naming Schemes
13114 @section Naming Schemes
13115
13116 @noindent
13117 Sometimes an Ada software system is ported from a foreign compilation
13118 environment to GNAT, and the file names do not use the default GNAT
13119 conventions. Instead of changing all the file names (which for a variety
13120 of reasons might not be possible), you can define the relevant file
13121 naming scheme in the @code{Naming} package in your project file.
13122
13123 @noindent
13124 Note that the use of pragmas described in
13125 @ref{Alternative File Naming Schemes} by mean of a configuration
13126 pragmas file is not supported when using project files. You must use
13127 the features described in this paragraph. You can however use specify
13128 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13129
13130 @ifclear vms
13131 For example, the following
13132 package models the Apex file naming rules:
13133
13134 @smallexample @c projectfile
13135 @group
13136   package Naming is
13137     for Casing               use "lowercase";
13138     for Dot_Replacement      use ".";
13139     for Spec_Suffix ("Ada")  use ".1.ada";
13140     for Body_Suffix ("Ada")  use ".2.ada";
13141   end Naming;
13142 @end group
13143 @end smallexample
13144 @end ifclear
13145
13146 @ifset vms
13147 For example, the following package models the HP Ada file naming rules:
13148
13149 @smallexample @c projectfile
13150 @group
13151   package Naming is
13152     for Casing               use "lowercase";
13153     for Dot_Replacement      use "__";
13154     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13155     for Body_Suffix ("Ada")  use ".^ada^ada^";
13156   end Naming;
13157 @end group
13158 @end smallexample
13159
13160 @noindent
13161 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13162 names in lower case)
13163 @end ifset
13164
13165 @noindent
13166 You can define the following attributes in package @code{Naming}:
13167
13168 @table @code
13169
13170 @item @var{Casing}
13171 This must be a string with one of the three values @code{"lowercase"},
13172 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13173
13174 @noindent
13175 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
13176
13177 @item @var{Dot_Replacement}
13178 This must be a string whose value satisfies the following conditions:
13179
13180 @itemize @bullet
13181 @item It must not be empty
13182 @item It cannot start or end with an alphanumeric character
13183 @item It cannot be a single underscore
13184 @item It cannot start with an underscore followed by an alphanumeric
13185 @item It cannot contain a dot @code{'.'} except if the entire string
13186 is @code{"."}
13187 @end itemize
13188
13189 @noindent
13190 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13191
13192 @item @var{Spec_Suffix}
13193 This is an associative array (indexed by the programming language name, case
13194 insensitive) whose value is a string that must satisfy the following
13195 conditions:
13196
13197 @itemize @bullet
13198 @item It must not be empty
13199 @item It must include at least one dot
13200 @end itemize
13201 @noindent
13202 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13203 @code{"^.ads^.ADS^"}.
13204
13205 @item @var{Body_Suffix}
13206 This is an associative array (indexed by the programming language name, case
13207 insensitive) whose value is a string that must satisfy the following
13208 conditions:
13209
13210 @itemize @bullet
13211 @item It must not be empty
13212 @item It must include at least one dot
13213 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13214 @end itemize
13215 @noindent
13216 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13217 same string, then a file name that ends with the longest of these two suffixes
13218 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13219 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13220
13221 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13222 @code{"^.adb^.ADB^"}.
13223
13224 @item @var{Separate_Suffix}
13225 This must be a string whose value satisfies the same conditions as
13226 @code{Body_Suffix}. The same "longest suffix" rules apply.
13227
13228 @noindent
13229 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13230 value as @code{Body_Suffix ("Ada")}.
13231
13232 @item @var{Spec}
13233 @noindent
13234 You can use the associative array attribute @code{Spec}  to define
13235 the source file name for an individual Ada compilation unit's spec. The array
13236 index must be a string literal that identifies the Ada unit (case insensitive).
13237 The value of this attribute must be a string that identifies the file that
13238 contains this unit's spec (case sensitive or insensitive depending on the
13239 operating system).
13240
13241 @smallexample @c projectfile
13242    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13243 @end smallexample
13244
13245 @item @var{Body}
13246
13247 You can use the associative array attribute @code{Body} to
13248 define the source file name for an individual Ada compilation unit's body
13249 (possibly a subunit).  The array index must be a string literal that identifies
13250 the Ada unit (case insensitive).  The value of this attribute must be a string
13251 that identifies the file that contains this unit's body or subunit (case
13252 sensitive or insensitive depending on the operating system).
13253
13254 @smallexample @c projectfile
13255    for Body ("MyPack.MyChild") use "mypack.mychild.body";
13256 @end smallexample
13257 @end table
13258
13259 @c ********************
13260 @c * Library Projects *
13261 @c ********************
13262
13263 @node Library Projects
13264 @section Library Projects
13265
13266 @noindent
13267 @emph{Library projects} are projects whose object code is placed in a library.
13268 (Note that this facility is not yet supported on all platforms)
13269
13270 To create a library project, you need to define in its project file
13271 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
13272 Additionally, you may define other library-related attributes such as
13273 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
13274 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
13275
13276 The @code{Library_Name} attribute has a string value. There is no restriction
13277 on the name of a library. It is the responsibility of the developer to
13278 choose a name that will be accepted by the platform. It is recommended to
13279 choose names that could be Ada identifiers; such names are almost guaranteed
13280 to be acceptable on all platforms.
13281
13282 The @code{Library_Dir} attribute has a string value that designates the path
13283 (absolute or relative) of the directory where the library will reside.
13284 It must designate an existing directory, and this directory must be writable,
13285 different from the project's object directory and from any source directory
13286 in the project tree.
13287
13288 If both @code{Library_Name} and @code{Library_Dir} are specified and
13289 are legal, then the project file defines a library project.  The optional
13290 library-related attributes are checked only for such project files.
13291
13292 The @code{Library_Kind} attribute has a string value that must be one of the
13293 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13294 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13295 attribute is not specified, the library is a static library, that is
13296 an archive of object files that can be potentially linked into a
13297 static executable. Otherwise, the library may be dynamic or
13298 relocatable, that is a library that is loaded only at the start of execution.
13299
13300 If you need to build both a static and a dynamic library, you should use two
13301 different object directories, since in some cases some extra code needs to
13302 be generated for the latter. For such cases, it is recommended to either use
13303 two different project files, or a single one which uses external variables
13304 to indicate what kind of library should be build.
13305
13306 The @code{Library_ALI_Dir} attribute may be specified to indicate the
13307 directory where the ALI files of the library will be copied. When it is
13308 not specified, the ALI files are copied to the directory specified in
13309 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
13310 must be writable and different from the project's object directory and from
13311 any source directory in the project tree.
13312
13313 The @code{Library_Version} attribute has a string value whose interpretation
13314 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
13315 used only for dynamic/relocatable libraries as the internal name of the
13316 library (the @code{"soname"}). If the library file name (built from the
13317 @code{Library_Name}) is different from the @code{Library_Version}, then the
13318 library file will be a symbolic link to the actual file whose name will be
13319 @code{Library_Version}.
13320
13321 Example (on Unix):
13322
13323 @smallexample @c projectfile
13324 @group
13325 project Plib is
13326
13327    Version := "1";
13328
13329    for Library_Dir use "lib_dir";
13330    for Library_Name use "dummy";
13331    for Library_Kind use "relocatable";
13332    for Library_Version use "libdummy.so." & Version;
13333
13334 end Plib;
13335 @end group
13336 @end smallexample
13337
13338 @noindent
13339 Directory @file{lib_dir} will contain the internal library file whose name
13340 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
13341 @file{libdummy.so.1}.
13342
13343 When @command{gnatmake} detects that a project file
13344 is a library project file, it will check all immediate sources of the project
13345 and rebuild the library if any of the sources have been recompiled.
13346
13347 Standard project files can import library project files. In such cases,
13348 the libraries will only be rebuilt if some of its sources are recompiled
13349 because they are in the closure of some other source in an importing project.
13350 Sources of the library project files that are not in such a closure will
13351 not be checked, unless the full library is checked, because one of its sources
13352 needs to be recompiled.
13353
13354 For instance, assume the project file @code{A} imports the library project file
13355 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
13356 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
13357 @file{l2.ads}, @file{l2.adb}.
13358
13359 If @file{l1.adb} has been modified, then the library associated with @code{L}
13360 will be rebuilt when compiling all the immediate sources of @code{A} only
13361 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
13362 @code{"with L1;"}.
13363
13364 To be sure that all the sources in the library associated with @code{L} are
13365 up to date, and that all the sources of project @code{A} are also up to date,
13366 the following two commands needs to be used:
13367
13368 @smallexample
13369 gnatmake -Pl.gpr
13370 gnatmake -Pa.gpr
13371 @end smallexample
13372
13373 When a library is built or rebuilt, an attempt is made first to delete all
13374 files in the library directory.
13375 All @file{ALI} files will also be copied from the object directory to the
13376 library directory. To build executables, @command{gnatmake} will use the
13377 library rather than the individual object files.
13378
13379 @ifclear vms
13380 It is also possible to create library project files for third-party libraries
13381 that are precompiled and cannot be compiled locally thanks to the
13382 @code{externally_built} attribute. (See @ref{Installing a library}).
13383 @end ifclear
13384
13385 @c *******************************
13386 @c * Stand-alone Library Projects *
13387 @c *******************************
13388
13389 @node Stand-alone Library Projects
13390 @section Stand-alone Library Projects
13391
13392 @noindent
13393 A Stand-alone Library is a library that contains the necessary code to
13394 elaborate the Ada units that are included in the library. A Stand-alone
13395 Library is suitable to be used in an executable when the main is not
13396 in Ada. However, Stand-alone Libraries may also be used with an Ada main
13397 subprogram.
13398
13399 A Stand-alone Library Project is a Library Project where the library is
13400 a Stand-alone Library.
13401
13402 To be a Stand-alone Library Project, in addition to the two attributes
13403 that make a project a Library Project (@code{Library_Name} and
13404 @code{Library_Dir}, see @ref{Library Projects}), the attribute
13405 @code{Library_Interface} must be defined.
13406
13407 @smallexample @c projectfile
13408 @group
13409    for Library_Dir use "lib_dir";
13410    for Library_Name use "dummy";
13411    for Library_Interface use ("int1", "int1.child");
13412 @end group
13413 @end smallexample
13414
13415 Attribute @code{Library_Interface} has a non empty string list value,
13416 each string in the list designating a unit contained in an immediate source
13417 of the project file.
13418
13419 When a Stand-alone Library is built, first the binder is invoked to build
13420 a package whose name depends on the library name
13421 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
13422 This binder-generated package includes initialization and
13423 finalization procedures whose
13424 names depend on the library name (dummyinit and dummyfinal in the example
13425 above). The object corresponding to this package is included in the library.
13426
13427 A dynamic or relocatable Stand-alone Library is automatically initialized
13428 if automatic initialization of Stand-alone Libraries is supported on the
13429 platform and if attribute @code{Library_Auto_Init} is not specified or
13430 is specified with the value "true". A static Stand-alone Library is never
13431 automatically initialized.
13432
13433 Single string attribute @code{Library_Auto_Init} may be specified with only
13434 two possible values: "false" or "true" (case-insensitive). Specifying
13435 "false" for attribute @code{Library_Auto_Init} will prevent automatic
13436 initialization of dynamic or relocatable libraries.
13437
13438 When a non automatically initialized Stand-alone Library is used
13439 in an executable, its initialization procedure must be called before
13440 any service of the library is used.
13441 When the main subprogram is in Ada, it may mean that the initialization
13442 procedure has to be called during elaboration of another package.
13443
13444 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
13445 (those that are listed in attribute @code{Library_Interface}) are copied to
13446 the Library Directory. As a consequence, only the Interface Units may be
13447 imported from Ada units outside of the library. If other units are imported,
13448 the binding phase will fail.
13449
13450 When a Stand-Alone Library is bound, the switches that are specified in
13451 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
13452 used in the call to @command{gnatbind}.
13453
13454 The string list attribute @code{Library_Options} may be used to specified
13455 additional switches to the call to @command{gcc} to link the library.
13456
13457 The attribute @code{Library_Src_Dir}, may be specified for a
13458 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
13459 single string value. Its value must be the path (absolute or relative to the
13460 project directory) of an existing directory. This directory cannot be the
13461 object directory or one of the source directories, but it can be the same as
13462 the library directory. The sources of the Interface
13463 Units of the library, necessary to an Ada client of the library, will be
13464 copied to the designated directory, called Interface Copy directory.
13465 These sources includes the specs of the Interface Units, but they may also
13466 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
13467 are used, or when there is a generic units in the spec. Before the sources
13468 are copied to the Interface Copy directory, an attempt is made to delete all
13469 files in the Interface Copy directory.
13470
13471 @c *************************************
13472 @c * Switches Related to Project Files *
13473 @c *************************************
13474 @node Switches Related to Project Files
13475 @section Switches Related to Project Files
13476
13477 @noindent
13478 The following switches are used by GNAT tools that support project files:
13479
13480 @table @option
13481
13482 @item ^-P^/PROJECT_FILE=^@var{project}
13483 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
13484 Indicates the name of a project file. This project file will be parsed with
13485 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
13486 if any, and using the external references indicated
13487 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
13488 @ifclear vms
13489 There may zero, one or more spaces between @option{-P} and @var{project}.
13490 @end ifclear
13491
13492 @noindent
13493 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
13494
13495 @noindent
13496 Since the Project Manager parses the project file only after all the switches
13497 on the command line are checked, the order of the switches
13498 @option{^-P^/PROJECT_FILE^},
13499 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
13500 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
13501
13502 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
13503 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
13504 Indicates that external variable @var{name} has the value @var{value}.
13505 The Project Manager will use this value for occurrences of
13506 @code{external(name)} when parsing the project file.
13507
13508 @ifclear vms
13509 @noindent
13510 If @var{name} or @var{value} includes a space, then @var{name=value} should be
13511 put between quotes.
13512 @smallexample
13513   -XOS=NT
13514   -X"user=John Doe"
13515 @end smallexample
13516 @end ifclear
13517
13518 @noindent
13519 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
13520 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
13521 @var{name}, only the last one is used.
13522
13523 @noindent
13524 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
13525 takes precedence over the value of the same name in the environment.
13526
13527 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
13528 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
13529 @c Previous line uses code vs option command, to stay less than 80 chars
13530 Indicates the verbosity of the parsing of GNAT project files.
13531
13532 @ifclear vms
13533 @option{-vP0} means Default;
13534 @option{-vP1} means Medium;
13535 @option{-vP2} means High.
13536 @end ifclear
13537
13538 @ifset vms
13539 There are three possible options for this qualifier: DEFAULT, MEDIUM and
13540 HIGH.
13541 @end ifset
13542
13543 @noindent
13544 The default is ^Default^DEFAULT^: no output for syntactically correct
13545 project files.
13546 @noindent
13547 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
13548 only the last one is used.
13549
13550 @end table
13551
13552 @c **********************************
13553 @c * Tools Supporting Project Files *
13554 @c **********************************
13555
13556 @node  Tools Supporting Project Files
13557 @section Tools Supporting Project Files
13558
13559 @menu
13560 * gnatmake and Project Files::
13561 * The GNAT Driver and Project Files::
13562 @end menu
13563
13564 @node gnatmake and Project Files
13565 @subsection gnatmake and Project Files
13566
13567 @noindent
13568 This section covers several topics related to @command{gnatmake} and
13569 project files: defining ^switches^switches^ for @command{gnatmake}
13570 and for the tools that it invokes; specifying configuration pragmas;
13571 the use of the @code{Main} attribute; building and rebuilding library project
13572 files.
13573
13574 @menu
13575 * ^Switches^Switches^ and Project Files::
13576 * Specifying Configuration Pragmas::
13577 * Project Files and Main Subprograms::
13578 * Library Project Files::
13579 @end menu
13580
13581 @node ^Switches^Switches^ and Project Files
13582 @subsubsection ^Switches^Switches^ and Project Files
13583
13584 @ifset vms
13585 It is not currently possible to specify VMS style qualifiers in the project
13586 files; only Unix style ^switches^switches^ may be specified.
13587 @end ifset
13588
13589 @noindent
13590 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
13591 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
13592 attribute, a @code{^Switches^Switches^} attribute, or both;
13593 as their names imply, these ^switch^switch^-related
13594 attributes affect the ^switches^switches^ that are used for each of these GNAT
13595 components when
13596 @command{gnatmake} is invoked.  As will be explained below, these
13597 component-specific ^switches^switches^ precede
13598 the ^switches^switches^ provided on the @command{gnatmake} command line.
13599
13600 The @code{^Default_Switches^Default_Switches^} attribute is an associative
13601 array indexed by language name (case insensitive) whose value is a string list.
13602 For example:
13603
13604 @smallexample @c projectfile
13605 @group
13606 package Compiler is
13607   for ^Default_Switches^Default_Switches^ ("Ada")
13608       use ("^-gnaty^-gnaty^",
13609            "^-v^-v^");
13610 end Compiler;
13611 @end group
13612 @end smallexample
13613
13614 @noindent
13615 The @code{^Switches^Switches^} attribute is also an associative array,
13616 indexed by a file name (which may or may not be case sensitive, depending
13617 on the operating system) whose value is a string list.  For example:
13618
13619 @smallexample @c projectfile
13620 @group
13621 package Builder is
13622    for ^Switches^Switches^ ("main1.adb")
13623        use ("^-O2^-O2^");
13624    for ^Switches^Switches^ ("main2.adb")
13625        use ("^-g^-g^");
13626 end Builder;
13627 @end group
13628 @end smallexample
13629
13630 @noindent
13631 For the @code{Builder} package, the file names must designate source files
13632 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
13633 file names must designate @file{ALI} or source files for main subprograms.
13634 In each case just the file name without an explicit extension is acceptable.
13635
13636 For each tool used in a program build (@command{gnatmake}, the compiler, the
13637 binder, and the linker), the corresponding package @dfn{contributes} a set of
13638 ^switches^switches^ for each file on which the tool is invoked, based on the
13639 ^switch^switch^-related attributes defined in the package.
13640 In particular, the ^switches^switches^
13641 that each of these packages contributes for a given file @var{f} comprise:
13642
13643 @itemize @bullet
13644 @item
13645 the value of attribute @code{^Switches^Switches^ (@var{f})},
13646 if it is specified in the package for the given file,
13647 @item
13648 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
13649 if it is specified in the package.
13650 @end itemize
13651
13652 @noindent
13653 If neither of these attributes is defined in the package, then the package does
13654 not contribute any ^switches^switches^ for the given file.
13655
13656 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
13657 two sets, in the following order: those contributed for the file
13658 by the @code{Builder} package;
13659 and the switches passed on the command line.
13660
13661 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
13662 the ^switches^switches^ passed to the tool comprise three sets,
13663 in the following order:
13664
13665 @enumerate
13666 @item
13667 the applicable ^switches^switches^ contributed for the file
13668 by the @code{Builder} package in the project file supplied on the command line;
13669
13670 @item
13671 those contributed for the file by the package (in the relevant project file --
13672 see below) corresponding to the tool; and
13673
13674 @item
13675 the applicable switches passed on the command line.
13676 @end enumerate
13677
13678 @noindent
13679 The term @emph{applicable ^switches^switches^} reflects the fact that
13680 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
13681 tools, depending on the individual ^switch^switch^.
13682
13683 @command{gnatmake} may invoke the compiler on source files from different
13684 projects. The Project Manager will use the appropriate project file to
13685 determine the @code{Compiler} package for each source file being compiled.
13686 Likewise for the @code{Binder} and @code{Linker} packages.
13687
13688 As an example, consider the following package in a project file:
13689
13690 @smallexample @c projectfile
13691 @group
13692 project Proj1 is
13693    package Compiler is
13694       for ^Default_Switches^Default_Switches^ ("Ada")
13695           use ("^-g^-g^");
13696       for ^Switches^Switches^ ("a.adb")
13697           use ("^-O1^-O1^");
13698       for ^Switches^Switches^ ("b.adb")
13699           use ("^-O2^-O2^",
13700                "^-gnaty^-gnaty^");
13701    end Compiler;
13702 end Proj1;
13703 @end group
13704 @end smallexample
13705
13706 @noindent
13707 If @command{gnatmake} is invoked with this project file, and it needs to
13708 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
13709 @file{a.adb} will be compiled with the ^switch^switch^
13710 @option{^-O1^-O1^},
13711 @file{b.adb} with ^switches^switches^
13712 @option{^-O2^-O2^}
13713 and @option{^-gnaty^-gnaty^},
13714 and @file{c.adb} with @option{^-g^-g^}.
13715
13716 The following example illustrates the ordering of the ^switches^switches^
13717 contributed by different packages:
13718
13719 @smallexample @c projectfile
13720 @group
13721 project Proj2 is
13722    package Builder is
13723       for ^Switches^Switches^ ("main.adb")
13724           use ("^-g^-g^",
13725                "^-O1^-)1^",
13726                "^-f^-f^");
13727    end Builder;
13728 @end group
13729
13730 @group
13731    package Compiler is
13732       for ^Switches^Switches^ ("main.adb")
13733           use ("^-O2^-O2^");
13734    end Compiler;
13735 end Proj2;
13736 @end group
13737 @end smallexample
13738
13739 @noindent
13740 If you issue the command:
13741
13742 @smallexample
13743     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
13744 @end smallexample
13745
13746 @noindent
13747 then the compiler will be invoked on @file{main.adb} with the following
13748 sequence of ^switches^switches^
13749
13750 @smallexample
13751    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
13752 @end smallexample
13753
13754 with the last @option{^-O^-O^}
13755 ^switch^switch^ having precedence over the earlier ones;
13756 several other ^switches^switches^
13757 (such as @option{^-c^-c^}) are added implicitly.
13758
13759 The ^switches^switches^
13760 @option{^-g^-g^}
13761 and @option{^-O1^-O1^} are contributed by package
13762 @code{Builder},  @option{^-O2^-O2^} is contributed
13763 by the package @code{Compiler}
13764 and @option{^-O0^-O0^} comes from the command line.
13765
13766 The @option{^-g^-g^}
13767 ^switch^switch^ will also be passed in the invocation of
13768 @command{Gnatlink.}
13769
13770 A final example illustrates switch contributions from packages in different
13771 project files:
13772
13773 @smallexample @c projectfile
13774 @group
13775 project Proj3 is
13776    for Source_Files use ("pack.ads", "pack.adb");
13777    package Compiler is
13778       for ^Default_Switches^Default_Switches^ ("Ada")
13779           use ("^-gnata^-gnata^");
13780    end Compiler;
13781 end Proj3;
13782 @end group
13783
13784 @group
13785 with "Proj3";
13786 project Proj4 is
13787    for Source_Files use ("foo_main.adb", "bar_main.adb");
13788    package Builder is
13789       for ^Switches^Switches^ ("foo_main.adb")
13790           use ("^-s^-s^",
13791                "^-g^-g^");
13792    end Builder;
13793 end Proj4;
13794 @end group
13795
13796 @group
13797 -- Ada source file:
13798 with Pack;
13799 procedure Foo_Main is
13800    ...
13801 end Foo_Main;
13802 @end group
13803 @end smallexample
13804
13805 If the command is
13806 @smallexample
13807 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13808 @end smallexample
13809
13810 @noindent
13811 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13812 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13813 @option{^-gnato^-gnato^} (passed on the command line).
13814 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13815 are @option{^-g^-g^} from @code{Proj4.Builder},
13816 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13817 and @option{^-gnato^-gnato^} from the command line.
13818
13819 @noindent
13820 When using @command{gnatmake} with project files, some ^switches^switches^ or
13821 arguments may be expressed as relative paths. As the working directory where
13822 compilation occurs may change, these relative paths are converted to absolute
13823 paths. For the ^switches^switches^ found in a project file, the relative paths
13824 are relative to the project file directory, for the switches on the command
13825 line, they are relative to the directory where @command{gnatmake} is invoked.
13826 The ^switches^switches^ for which this occurs are:
13827 ^-I^-I^,
13828 ^-A^-A^,
13829 ^-L^-L^,
13830 ^-aO^-aO^,
13831 ^-aL^-aL^,
13832 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13833 ^switch^switch^
13834 ^-o^-o^, object files specified in package @code{Linker} or after
13835 -largs on the command line). The exception to this rule is the ^switch^switch^
13836 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13837
13838 @node Specifying Configuration Pragmas
13839 @subsubsection Specifying Configuration Pragmas
13840
13841 When using @command{gnatmake} with project files, if there exists a file
13842 @file{gnat.adc} that contains configuration pragmas, this file will be
13843 ignored.
13844
13845 Configuration pragmas can be defined by means of the following attributes in
13846 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13847 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13848
13849 Both these attributes are single string attributes. Their values is the path
13850 name of a file containing configuration pragmas. If a path name is relative,
13851 then it is relative to the project directory of the project file where the
13852 attribute is defined.
13853
13854 When compiling a source, the configuration pragmas used are, in order,
13855 those listed in the file designated by attribute
13856 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13857 project file, if it is specified, and those listed in the file designated by
13858 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13859 the project file of the source, if it exists.
13860
13861 @node Project Files and Main Subprograms
13862 @subsubsection Project Files and Main Subprograms
13863
13864 @noindent
13865 When using a project file, you can invoke @command{gnatmake}
13866 with one or several main subprograms, by specifying their source files on the
13867 command line.
13868
13869 @smallexample
13870     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13871 @end smallexample
13872
13873 @noindent
13874 Each of these needs to be a source file of the same project, except
13875 when the switch ^-u^/UNIQUE^ is used.
13876
13877 @noindent
13878 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13879 same project, one of the project in the tree rooted at the project specified
13880 on the command line. The package @code{Builder} of this common project, the
13881 "main project" is the one that is considered by @command{gnatmake}.
13882
13883 @noindent
13884 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13885 imported directly or indirectly by the project specified on the command line.
13886 Note that if such a source file is not part of the project specified on the
13887 command line, the ^switches^switches^ found in package @code{Builder} of the
13888 project specified on the command line, if any, that are transmitted
13889 to the compiler will still be used, not those found in the project file of
13890 the source file.
13891
13892 @noindent
13893 When using a project file, you can also invoke @command{gnatmake} without
13894 explicitly specifying any main, and the effect depends on whether you have
13895 defined the @code{Main} attribute.  This attribute has a string list value,
13896 where each element in the list is the name of a source file (the file
13897 extension is optional) that contains a unit that can be a main subprogram.
13898
13899 If the @code{Main} attribute is defined in a project file as a non-empty
13900 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13901 line, then invoking @command{gnatmake} with this project file but without any
13902 main on the command line is equivalent to invoking @command{gnatmake} with all
13903 the file names in the @code{Main} attribute on the command line.
13904
13905 Example:
13906 @smallexample @c projectfile
13907 @group
13908    project Prj is
13909       for Main use ("main1", "main2", "main3");
13910    end Prj;
13911 @end group
13912 @end smallexample
13913
13914 @noindent
13915 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13916 is equivalent to
13917 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13918
13919 When the project attribute @code{Main} is not specified, or is specified
13920 as an empty string list, or when the switch @option{-u} is used on the command
13921 line, then invoking @command{gnatmake} with no main on the command line will
13922 result in all immediate sources of the project file being checked, and
13923 potentially recompiled. Depending on the presence of the switch @option{-u},
13924 sources from other project files on which the immediate sources of the main
13925 project file depend are also checked and potentially recompiled. In other
13926 words, the @option{-u} switch is applied to all of the immediate sources of the
13927 main project file.
13928
13929 When no main is specified on the command line and attribute @code{Main} exists
13930 and includes several mains, or when several mains are specified on the
13931 command line, the default ^switches^switches^ in package @code{Builder} will
13932 be used for all mains, even if there are specific ^switches^switches^
13933 specified for one or several mains.
13934
13935 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13936 the specific ^switches^switches^ for each main, if they are specified.
13937
13938 @node Library Project Files
13939 @subsubsection Library Project Files
13940
13941 @noindent
13942 When @command{gnatmake} is invoked with a main project file that is a library
13943 project file, it is not allowed to specify one or more mains on the command
13944 line.
13945
13946 @noindent
13947 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13948 ^-l^/ACTION=LINK^ have special meanings.
13949
13950 @itemize @bullet
13951 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13952 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13953 library.
13954
13955 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13956 to @command{gnatmake} that the binder generated file should be compiled
13957 (in the case of a stand-alone library) and that the library should be built.
13958
13959 @end itemize
13960
13961 @node The GNAT Driver and Project Files
13962 @subsection The GNAT Driver and Project Files
13963
13964 @noindent
13965 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13966 can benefit from project files:
13967 @command{^gnatbind^gnatbind^},
13968 @command{^gnatcheck^gnatcheck^}),
13969 @command{^gnatclean^gnatclean^}),
13970 @command{^gnatelim^gnatelim^},
13971 @command{^gnatfind^gnatfind^},
13972 @command{^gnatlink^gnatlink^},
13973 @command{^gnatls^gnatls^},
13974 @command{^gnatmetric^gnatmetric^},
13975 @command{^gnatpp^gnatpp^},
13976 @command{^gnatstub^gnatstub^},
13977 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13978 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13979 They must be invoked through the @command{gnat} driver.
13980
13981 The @command{gnat} driver is a wrapper that accepts a number of commands and
13982 calls the corresponding tool. It was designed initially for VMS platforms (to
13983 convert VMS qualifiers to Unix-style switches), but it is now available on all
13984 GNAT platforms.
13985
13986 On non-VMS platforms, the @command{gnat} driver accepts the following commands
13987 (case insensitive):
13988
13989 @itemize @bullet
13990 @item
13991 BIND to invoke @command{^gnatbind^gnatbind^}
13992 @item
13993 CHOP to invoke @command{^gnatchop^gnatchop^}
13994 @item
13995 CLEAN to invoke @command{^gnatclean^gnatclean^}
13996 @item
13997 COMP or COMPILE to invoke the compiler
13998 @item
13999 ELIM to invoke @command{^gnatelim^gnatelim^}
14000 @item
14001 FIND to invoke @command{^gnatfind^gnatfind^}
14002 @item
14003 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14004 @item
14005 LINK to invoke @command{^gnatlink^gnatlink^}
14006 @item
14007 LS or LIST to invoke @command{^gnatls^gnatls^}
14008 @item
14009 MAKE to invoke @command{^gnatmake^gnatmake^}
14010 @item
14011 NAME to invoke @command{^gnatname^gnatname^}
14012 @item
14013 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14014 @item
14015 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14016 @item
14017 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14018 @item
14019 STUB to invoke @command{^gnatstub^gnatstub^}
14020 @item
14021 XREF to invoke @command{^gnatxref^gnatxref^}
14022 @end itemize
14023
14024 @noindent
14025 (note that the compiler is invoked using the command
14026 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14027
14028 @noindent
14029 On non VMS platforms, between @command{gnat} and the command, two
14030 special switches may be used:
14031
14032 @itemize @bullet
14033 @item
14034 @command{-v} to display the invocation of the tool.
14035 @item
14036 @command{-dn} to prevent the @command{gnat} driver from removing
14037 the temporary files it has created. These temporary files are
14038 configuration files and temporary file list files.
14039 @end itemize
14040
14041 @noindent
14042 The command may be followed by switches and arguments for the invoked
14043 tool.
14044
14045 @smallexample
14046   gnat bind -C main.ali
14047   gnat ls -a main
14048   gnat chop foo.txt
14049 @end smallexample
14050
14051 @noindent
14052 Switches may also be put in text files, one switch per line, and the text
14053 files may be specified with their path name preceded by '@@'.
14054
14055 @smallexample
14056    gnat bind @@args.txt main.ali
14057 @end smallexample
14058
14059 @noindent
14060 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14061 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14062 (@option{^-P^/PROJECT_FILE^},
14063 @option{^-X^/EXTERNAL_REFERENCE^} and
14064 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14065 the switches of the invoking tool.
14066
14067 @noindent
14068 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14069 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14070 the immediate sources of the specified project file.
14071
14072 @noindent
14073 When GNAT METRIC is used with a project file, but with no source
14074 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14075 with all the immediate sources of the specified project file and with
14076 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14077 of the project.
14078
14079 @noindent
14080 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14081 a project file, no source is specified on the command line and
14082 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14083 the underlying tool (^gnatpp^gnatpp^ or
14084 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14085 not only for the immediate sources of the main project.
14086 @ifclear vms
14087 (-U stands for Universal or Union of the project files of the project tree)
14088 @end ifclear
14089
14090 @noindent
14091 For each of the following commands, there is optionally a corresponding
14092 package in the main project.
14093
14094 @itemize @bullet
14095 @item
14096 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14097
14098 @item
14099 package @code{Check} for command CHECK (invoking
14100 @code{^gnatcheck^gnatcheck^})
14101
14102 @item
14103 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14104
14105 @item
14106 package @code{Cross_Reference} for command XREF (invoking
14107 @code{^gnatxref^gnatxref^})
14108
14109 @item
14110 package @code{Eliminate} for command ELIM (invoking
14111 @code{^gnatelim^gnatelim^})
14112
14113 @item
14114 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14115
14116 @item
14117 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14118
14119 @item
14120 package @code{Gnatstub} for command STUB
14121 (invoking @code{^gnatstub^gnatstub^})
14122
14123 @item
14124 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14125
14126 @item
14127 package @code{Metrics} for command METRIC
14128 (invoking @code{^gnatmetric^gnatmetric^})
14129
14130 @item
14131 package @code{Pretty_Printer} for command PP or PRETTY
14132 (invoking @code{^gnatpp^gnatpp^})
14133
14134 @end itemize
14135
14136 @noindent
14137 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14138 a simple variable with a string list value. It contains ^switches^switches^
14139 for the invocation of @code{^gnatls^gnatls^}.
14140
14141 @smallexample @c projectfile
14142 @group
14143 project Proj1 is
14144    package gnatls is
14145       for ^Switches^Switches^
14146           use ("^-a^-a^",
14147                "^-v^-v^");
14148    end gnatls;
14149 end Proj1;
14150 @end group
14151 @end smallexample
14152
14153 @noindent
14154 All other packages have two attribute @code{^Switches^Switches^} and
14155 @code{^Default_Switches^Default_Switches^}.
14156
14157 @noindent
14158 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14159 source file name, that has a string list value: the ^switches^switches^ to be
14160 used when the tool corresponding to the package is invoked for the specific
14161 source file.
14162
14163 @noindent
14164 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14165 indexed by  the programming language that has a string list value.
14166 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14167 ^switches^switches^ for the invocation of the tool corresponding
14168 to the package, except if a specific @code{^Switches^Switches^} attribute
14169 is specified for the source file.
14170
14171 @smallexample @c projectfile
14172 @group
14173 project Proj is
14174
14175    for Source_Dirs use ("./**");
14176
14177    package gnatls is
14178       for ^Switches^Switches^ use
14179           ("^-a^-a^",
14180            "^-v^-v^");
14181    end gnatls;
14182 @end group
14183 @group
14184
14185    package Compiler is
14186       for ^Default_Switches^Default_Switches^ ("Ada")
14187           use ("^-gnatv^-gnatv^",
14188                "^-gnatwa^-gnatwa^");
14189    end Binder;
14190 @end group
14191 @group
14192
14193    package Binder is
14194       for ^Default_Switches^Default_Switches^ ("Ada")
14195           use ("^-C^-C^",
14196                "^-e^-e^");
14197    end Binder;
14198 @end group
14199 @group
14200
14201    package Linker is
14202       for ^Default_Switches^Default_Switches^ ("Ada")
14203           use ("^-C^-C^");
14204       for ^Switches^Switches^ ("main.adb")
14205           use ("^-C^-C^",
14206                "^-v^-v^",
14207                "^-v^-v^");
14208    end Linker;
14209 @end group
14210 @group
14211
14212    package Finder is
14213       for ^Default_Switches^Default_Switches^ ("Ada")
14214            use ("^-a^-a^",
14215                 "^-f^-f^");
14216    end Finder;
14217 @end group
14218 @group
14219
14220    package Cross_Reference is
14221       for ^Default_Switches^Default_Switches^ ("Ada")
14222           use ("^-a^-a^",
14223                "^-f^-f^",
14224                "^-d^-d^",
14225                "^-u^-u^");
14226    end Cross_Reference;
14227 end Proj;
14228 @end group
14229 @end smallexample
14230
14231 @noindent
14232 With the above project file, commands such as
14233
14234 @smallexample
14235    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
14236    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
14237    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
14238    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
14239    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
14240 @end smallexample
14241
14242 @noindent
14243 will set up the environment properly and invoke the tool with the switches
14244 found in the package corresponding to the tool:
14245 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
14246 except @code{^Switches^Switches^ ("main.adb")}
14247 for @code{^gnatlink^gnatlink^}.
14248 It is also possible to invoke some of the tools,
14249 @code{^gnatcheck^gnatcheck^}),
14250 @code{^gnatmetric^gnatmetric^}),
14251 and @code{^gnatpp^gnatpp^})
14252 on a set of project units thanks to the combination of the switches
14253 @code{-P}, @code{-U} and possibly the main unit when one is interested
14254 in its closure. For instance,
14255 @smallexample
14256 gnat metric -Pproj
14257 @end smallexample
14258 will compute the metrics for all the immediate units of project
14259 @code{proj}.
14260 @smallexample
14261 gnat metric -Pproj -U
14262 @end smallexample
14263 will compute the metrics for all the units of the closure of projects
14264 rooted at @code{proj}.
14265 @smallexample
14266 gnat metric -Pproj -U main_unit
14267 @end smallexample
14268 will compute the metrics for the closure of units rooted at
14269 @code{main_unit}. This last possibility relies implicitly
14270 on @command{gnatbind}'s option @option{-R}.
14271
14272 @c **********************
14273 @node An Extended Example
14274 @section An Extended Example
14275
14276 @noindent
14277 Suppose that we have two programs, @var{prog1} and @var{prog2},
14278 whose sources are in corresponding directories. We would like
14279 to build them with a single @command{gnatmake} command, and we want to place
14280 their object files into @file{build} subdirectories of the source directories.
14281 Furthermore, we want to have to have two separate subdirectories
14282 in @file{build}  -- @file{release} and @file{debug} -- which will contain
14283 the object files compiled with different set of compilation flags.
14284
14285 In other words, we have the following structure:
14286
14287 @smallexample
14288 @group
14289    main
14290      |- prog1
14291      |    |- build
14292      |         | debug
14293      |         | release
14294      |- prog2
14295           |- build
14296                | debug
14297                | release
14298 @end group
14299 @end smallexample
14300
14301 @noindent
14302 Here are the project files that we must place in a directory @file{main}
14303 to maintain this structure:
14304
14305 @enumerate
14306
14307 @item We create a @code{Common} project with a package @code{Compiler} that
14308 specifies the compilation ^switches^switches^:
14309
14310 @smallexample
14311 File "common.gpr":
14312 @group
14313 @b{project} Common @b{is}
14314
14315    @b{for} Source_Dirs @b{use} (); -- No source files
14316 @end group
14317
14318 @group
14319    @b{type} Build_Type @b{is} ("release", "debug");
14320    Build : Build_Type := External ("BUILD", "debug");
14321 @end group
14322 @group
14323    @b{package} Compiler @b{is}
14324       @b{case} Build @b{is}
14325          @b{when} "release" =>
14326            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14327                    @b{use} ("^-O2^-O2^");
14328          @b{when} "debug"   =>
14329            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14330                    @b{use} ("^-g^-g^");
14331       @b{end case};
14332    @b{end} Compiler;
14333
14334 @b{end} Common;
14335 @end group
14336 @end smallexample
14337
14338 @item We create separate projects for the two programs:
14339
14340 @smallexample
14341 @group
14342 File "prog1.gpr":
14343
14344 @b{with} "common";
14345 @b{project} Prog1 @b{is}
14346
14347     @b{for} Source_Dirs @b{use} ("prog1");
14348     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
14349
14350     @b{package} Compiler @b{renames} Common.Compiler;
14351
14352 @b{end} Prog1;
14353 @end group
14354 @end smallexample
14355
14356 @smallexample
14357 @group
14358 File "prog2.gpr":
14359
14360 @b{with} "common";
14361 @b{project} Prog2 @b{is}
14362
14363     @b{for} Source_Dirs @b{use} ("prog2");
14364     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
14365
14366     @b{package} Compiler @b{renames} Common.Compiler;
14367
14368 @end group
14369 @b{end} Prog2;
14370 @end smallexample
14371
14372 @item We create a wrapping project @code{Main}:
14373
14374 @smallexample
14375 @group
14376 File "main.gpr":
14377
14378 @b{with} "common";
14379 @b{with} "prog1";
14380 @b{with} "prog2";
14381 @b{project} Main @b{is}
14382
14383    @b{package} Compiler @b{renames} Common.Compiler;
14384
14385 @b{end} Main;
14386 @end group
14387 @end smallexample
14388
14389 @item Finally we need to create a dummy procedure that @code{with}s (either
14390 explicitly or implicitly) all the sources of our two programs.
14391
14392 @end enumerate
14393
14394 @noindent
14395 Now we can build the programs using the command
14396
14397 @smallexample
14398    gnatmake ^-P^/PROJECT_FILE=^main dummy
14399 @end smallexample
14400
14401 @noindent
14402 for the Debug mode, or
14403
14404 @ifclear vms
14405 @smallexample
14406    gnatmake -Pmain -XBUILD=release
14407 @end smallexample
14408 @end ifclear
14409
14410 @ifset vms
14411 @smallexample
14412    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
14413 @end smallexample
14414 @end ifset
14415
14416 @noindent
14417 for the Release mode.
14418
14419 @c ********************************
14420 @c * Project File Complete Syntax *
14421 @c ********************************
14422
14423 @node Project File Complete Syntax
14424 @section Project File Complete Syntax
14425
14426 @smallexample
14427 project ::=
14428   context_clause project_declaration
14429
14430 context_clause ::=
14431   @{with_clause@}
14432
14433 with_clause ::=
14434   @b{with} path_name @{ , path_name @} ;
14435
14436 path_name ::=
14437    string_literal
14438
14439 project_declaration ::=
14440   simple_project_declaration | project_extension
14441
14442 simple_project_declaration ::=
14443   @b{project} <project_>simple_name @b{is}
14444     @{declarative_item@}
14445   @b{end} <project_>simple_name;
14446
14447 project_extension ::=
14448   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
14449     @{declarative_item@}
14450   @b{end} <project_>simple_name;
14451
14452 declarative_item ::=
14453   package_declaration |
14454   typed_string_declaration |
14455   other_declarative_item
14456
14457 package_declaration ::=
14458   package_specification | package_renaming
14459
14460 package_specification ::=
14461   @b{package} package_identifier @b{is}
14462     @{simple_declarative_item@}
14463   @b{end} package_identifier ;
14464
14465 package_identifier ::=
14466   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
14467   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
14468   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
14469
14470 package_renaming ::==
14471   @b{package} package_identifier @b{renames}
14472        <project_>simple_name.package_identifier ;
14473
14474 typed_string_declaration ::=
14475   @b{type} <typed_string_>_simple_name @b{is}
14476    ( string_literal @{, string_literal@} );
14477
14478 other_declarative_item ::=
14479   attribute_declaration |
14480   typed_variable_declaration |
14481   variable_declaration |
14482   case_construction
14483
14484 attribute_declaration ::=
14485   full_associative_array_declaration |
14486   @b{for} attribute_designator @b{use} expression ;
14487
14488 full_associative_array_declaration ::=
14489   @b{for} <associative_array_attribute_>simple_name @b{use}
14490   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
14491
14492 attribute_designator ::=
14493   <simple_attribute_>simple_name |
14494   <associative_array_attribute_>simple_name ( string_literal )
14495
14496 typed_variable_declaration ::=
14497   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
14498
14499 variable_declaration ::=
14500   <variable_>simple_name := expression;
14501
14502 expression ::=
14503   term @{& term@}
14504
14505 term ::=
14506   literal_string |
14507   string_list |
14508   <variable_>name |
14509   external_value |
14510   attribute_reference
14511
14512 string_literal ::=
14513   (same as Ada)
14514
14515 string_list ::=
14516   ( <string_>expression @{ , <string_>expression @} )
14517
14518 external_value ::=
14519   @b{external} ( string_literal [, string_literal] )
14520
14521 attribute_reference ::=
14522   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
14523
14524 attribute_prefix ::=
14525   @b{project} |
14526   <project_>simple_name | package_identifier |
14527   <project_>simple_name . package_identifier
14528
14529 case_construction ::=
14530   @b{case} <typed_variable_>name @b{is}
14531     @{case_item@}
14532   @b{end case} ;
14533
14534 case_item ::=
14535   @b{when} discrete_choice_list =>
14536       @{case_construction | attribute_declaration@}
14537
14538 discrete_choice_list ::=
14539   string_literal @{| string_literal@} |
14540   @b{others}
14541
14542 name ::=
14543   simple_name @{. simple_name@}
14544
14545 simple_name ::=
14546   identifier (same as Ada)
14547
14548 @end smallexample
14549
14550 @node The Cross-Referencing Tools gnatxref and gnatfind
14551 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
14552 @findex gnatxref
14553 @findex gnatfind
14554
14555 @noindent
14556 The compiler generates cross-referencing information (unless
14557 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
14558 This information indicates where in the source each entity is declared and
14559 referenced. Note that entities in package Standard are not included, but
14560 entities in all other predefined units are included in the output.
14561
14562 Before using any of these two tools, you need to compile successfully your
14563 application, so that GNAT gets a chance to generate the cross-referencing
14564 information.
14565
14566 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
14567 information to provide the user with the capability to easily locate the
14568 declaration and references to an entity. These tools are quite similar,
14569 the difference being that @code{gnatfind} is intended for locating
14570 definitions and/or references to a specified entity or entities, whereas
14571 @code{gnatxref} is oriented to generating a full report of all
14572 cross-references.
14573
14574 To use these tools, you must not compile your application using the
14575 @option{-gnatx} switch on the @command{gnatmake} command line
14576 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
14577 information will not be generated.
14578
14579 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
14580 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14581
14582 @menu
14583 * gnatxref Switches::
14584 * gnatfind Switches::
14585 * Project Files for gnatxref and gnatfind::
14586 * Regular Expressions in gnatfind and gnatxref::
14587 * Examples of gnatxref Usage::
14588 * Examples of gnatfind Usage::
14589 @end menu
14590
14591 @node gnatxref Switches
14592 @section @code{gnatxref} Switches
14593
14594 @noindent
14595 The command invocation for @code{gnatxref} is:
14596 @smallexample
14597 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
14598 @end smallexample
14599
14600 @noindent
14601 where
14602
14603 @table @code
14604 @item sourcefile1, sourcefile2
14605 identifies the source files for which a report is to be generated. The
14606 ``with''ed units will be processed too. You must provide at least one file.
14607
14608 These file names are considered to be regular expressions, so for instance
14609 specifying @file{source*.adb} is the same as giving every file in the current
14610 directory whose name starts with @file{source} and whose extension is
14611 @file{adb}.
14612
14613 You shouldn't specify any directory name, just base names. @command{gnatxref}
14614 and @command{gnatfind} will be able to locate these files by themselves using
14615 the source path. If you specify directories, no result is produced.
14616
14617 @end table
14618
14619 @noindent
14620 The switches can be :
14621 @table @option
14622 @c !sort!
14623 @item --version
14624 @cindex @option{--version} @command{gnatxref}
14625 Display Copyright and version, then exit disregarding all other options.
14626
14627 @item --help
14628 @cindex @option{--help} @command{gnatxref}
14629 If @option{--version} was not used, display usage, then exit disregarding
14630 all other options.
14631
14632 @item ^-a^/ALL_FILES^
14633 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
14634 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14635 the read-only files found in the library search path. Otherwise, these files
14636 will be ignored. This option can be used to protect Gnat sources or your own
14637 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14638 much faster, and their output much smaller. Read-only here refers to access
14639 or permissions status in the file system for the current user.
14640
14641 @item -aIDIR
14642 @cindex @option{-aIDIR} (@command{gnatxref})
14643 When looking for source files also look in directory DIR. The order in which
14644 source file search is undertaken is the same as for @command{gnatmake}.
14645
14646 @item -aODIR
14647 @cindex @option{-aODIR} (@command{gnatxref})
14648 When searching for library and object files, look in directory
14649 DIR. The order in which library files are searched is the same as for
14650 @command{gnatmake}.
14651
14652 @item -nostdinc
14653 @cindex @option{-nostdinc} (@command{gnatxref})
14654 Do not look for sources in the system default directory.
14655
14656 @item -nostdlib
14657 @cindex @option{-nostdlib} (@command{gnatxref})
14658 Do not look for library files in the system default directory.
14659
14660 @item --RTS=@var{rts-path}
14661 @cindex @option{--RTS} (@command{gnatxref})
14662 Specifies the default location of the runtime library. Same meaning as the
14663 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14664
14665 @item ^-d^/DERIVED_TYPES^
14666 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
14667 If this switch is set @code{gnatxref} will output the parent type
14668 reference for each matching derived types.
14669
14670 @item ^-f^/FULL_PATHNAME^
14671 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
14672 If this switch is set, the output file names will be preceded by their
14673 directory (if the file was found in the search path). If this switch is
14674 not set, the directory will not be printed.
14675
14676 @item ^-g^/IGNORE_LOCALS^
14677 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
14678 If this switch is set, information is output only for library-level
14679 entities, ignoring local entities. The use of this switch may accelerate
14680 @code{gnatfind} and @code{gnatxref}.
14681
14682 @item -IDIR
14683 @cindex @option{-IDIR} (@command{gnatxref})
14684 Equivalent to @samp{-aODIR -aIDIR}.
14685
14686 @item -pFILE
14687 @cindex @option{-pFILE} (@command{gnatxref})
14688 Specify a project file to use @xref{Project Files}.
14689 If you need to use the @file{.gpr}
14690 project files, you should use gnatxref through the GNAT driver
14691 (@command{gnat xref -Pproject}).
14692
14693 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14694 project file in the current directory.
14695
14696 If a project file is either specified or found by the tools, then the content
14697 of the source directory and object directory lines are added as if they
14698 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
14699 and @samp{^-aO^OBJECT_SEARCH^}.
14700 @item ^-u^/UNUSED^
14701 Output only unused symbols. This may be really useful if you give your
14702 main compilation unit on the command line, as @code{gnatxref} will then
14703 display every unused entity and 'with'ed package.
14704
14705 @ifclear vms
14706 @item -v
14707 Instead of producing the default output, @code{gnatxref} will generate a
14708 @file{tags} file that can be used by vi. For examples how to use this
14709 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
14710 to the standard output, thus you will have to redirect it to a file.
14711 @end ifclear
14712
14713 @end table
14714
14715 @noindent
14716 All these switches may be in any order on the command line, and may even
14717 appear after the file names. They need not be separated by spaces, thus
14718 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14719 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14720
14721 @node gnatfind Switches
14722 @section @code{gnatfind} Switches
14723
14724 @noindent
14725 The command line for @code{gnatfind} is:
14726
14727 @smallexample
14728 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
14729       [file1 file2 ...]
14730 @end smallexample
14731
14732 @noindent
14733 where
14734
14735 @table @code
14736 @item pattern
14737 An entity will be output only if it matches the regular expression found
14738 in @samp{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
14739
14740 Omitting the pattern is equivalent to specifying @samp{*}, which
14741 will match any entity. Note that if you do not provide a pattern, you
14742 have to provide both a sourcefile and a line.
14743
14744 Entity names are given in Latin-1, with uppercase/lowercase equivalence
14745 for matching purposes. At the current time there is no support for
14746 8-bit codes other than Latin-1, or for wide characters in identifiers.
14747
14748 @item sourcefile
14749 @code{gnatfind} will look for references, bodies or declarations
14750 of symbols referenced in @file{sourcefile}, at line @samp{line}
14751 and column @samp{column}. See @ref{Examples of gnatfind Usage}
14752 for syntax examples.
14753
14754 @item line
14755 is a decimal integer identifying the line number containing
14756 the reference to the entity (or entities) to be located.
14757
14758 @item column
14759 is a decimal integer identifying the exact location on the
14760 line of the first character of the identifier for the
14761 entity reference. Columns are numbered from 1.
14762
14763 @item file1 file2 ...
14764 The search will be restricted to these source files. If none are given, then
14765 the search will be done for every library file in the search path.
14766 These file must appear only after the pattern or sourcefile.
14767
14768 These file names are considered to be regular expressions, so for instance
14769 specifying 'source*.adb' is the same as giving every file in the current
14770 directory whose name starts with 'source' and whose extension is 'adb'.
14771
14772 The location of the spec of the entity will always be displayed, even if it
14773 isn't in one of file1, file2,... The occurrences of the entity in the
14774 separate units of the ones given on the command line will also be displayed.
14775
14776 Note that if you specify at least one file in this part, @code{gnatfind} may
14777 sometimes not be able to find the body of the subprograms...
14778
14779 @end table
14780
14781 @noindent
14782 At least one of 'sourcefile' or 'pattern' has to be present on
14783 the command line.
14784
14785 The following switches are available:
14786 @table @option
14787 @c !sort!
14788
14789 @cindex @option{--version} @command{gnatfind}
14790 Display Copyright and version, then exit disregarding all other options.
14791
14792 @item --help
14793 @cindex @option{--help} @command{gnatfind}
14794 If @option{--version} was not used, display usage, then exit disregarding
14795 all other options.
14796
14797 @item ^-a^/ALL_FILES^
14798 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
14799 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14800 the read-only files found in the library search path. Otherwise, these files
14801 will be ignored. This option can be used to protect Gnat sources or your own
14802 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14803 much faster, and their output much smaller. Read-only here refers to access
14804 or permission status in the file system for the current user.
14805
14806 @item -aIDIR
14807 @cindex @option{-aIDIR} (@command{gnatfind})
14808 When looking for source files also look in directory DIR. The order in which
14809 source file search is undertaken is the same as for @command{gnatmake}.
14810
14811 @item -aODIR
14812 @cindex @option{-aODIR} (@command{gnatfind})
14813 When searching for library and object files, look in directory
14814 DIR. The order in which library files are searched is the same as for
14815 @command{gnatmake}.
14816
14817 @item -nostdinc
14818 @cindex @option{-nostdinc} (@command{gnatfind})
14819 Do not look for sources in the system default directory.
14820
14821 @item -nostdlib
14822 @cindex @option{-nostdlib} (@command{gnatfind})
14823 Do not look for library files in the system default directory.
14824
14825 @item --RTS=@var{rts-path}
14826 @cindex @option{--RTS} (@command{gnatfind})
14827 Specifies the default location of the runtime library. Same meaning as the
14828 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14829
14830 @item ^-d^/DERIVED_TYPE_INFORMATION^
14831 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
14832 If this switch is set, then @code{gnatfind} will output the parent type
14833 reference for each matching derived types.
14834
14835 @item ^-e^/EXPRESSIONS^
14836 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14837 By default, @code{gnatfind} accept the simple regular expression set for
14838 @samp{pattern}. If this switch is set, then the pattern will be
14839 considered as full Unix-style regular expression.
14840
14841 @item ^-f^/FULL_PATHNAME^
14842 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14843 If this switch is set, the output file names will be preceded by their
14844 directory (if the file was found in the search path). If this switch is
14845 not set, the directory will not be printed.
14846
14847 @item ^-g^/IGNORE_LOCALS^
14848 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14849 If this switch is set, information is output only for library-level
14850 entities, ignoring local entities. The use of this switch may accelerate
14851 @code{gnatfind} and @code{gnatxref}.
14852
14853 @item -IDIR
14854 @cindex @option{-IDIR} (@command{gnatfind})
14855 Equivalent to @samp{-aODIR -aIDIR}.
14856
14857 @item -pFILE
14858 @cindex @option{-pFILE} (@command{gnatfind})
14859 Specify a project file (@pxref{Project Files}) to use.
14860 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14861 project file in the current directory.
14862
14863 If a project file is either specified or found by the tools, then the content
14864 of the source directory and object directory lines are added as if they
14865 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14866 @samp{^-aO^/OBJECT_SEARCH^}.
14867
14868 @item ^-r^/REFERENCES^
14869 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14870 By default, @code{gnatfind} will output only the information about the
14871 declaration, body or type completion of the entities. If this switch is
14872 set, the @code{gnatfind} will locate every reference to the entities in
14873 the files specified on the command line (or in every file in the search
14874 path if no file is given on the command line).
14875
14876 @item ^-s^/PRINT_LINES^
14877 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14878 If this switch is set, then @code{gnatfind} will output the content
14879 of the Ada source file lines were the entity was found.
14880
14881 @item ^-t^/TYPE_HIERARCHY^
14882 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14883 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14884 the specified type. It act like -d option but recursively from parent
14885 type to parent type. When this switch is set it is not possible to
14886 specify more than one file.
14887
14888 @end table
14889
14890 @noindent
14891 All these switches may be in any order on the command line, and may even
14892 appear after the file names. They need not be separated by spaces, thus
14893 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14894 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14895
14896 As stated previously, gnatfind will search in every directory in the
14897 search path. You can force it to look only in the current directory if
14898 you specify @code{*} at the end of the command line.
14899
14900 @node Project Files for gnatxref and gnatfind
14901 @section Project Files for @command{gnatxref} and @command{gnatfind}
14902
14903 @noindent
14904 Project files allow a programmer to specify how to compile its
14905 application, where to find sources, etc.  These files are used
14906 @ifclear vms
14907 primarily by GPS, but they can also be used
14908 @end ifclear
14909 by the two tools
14910 @code{gnatxref} and @code{gnatfind}.
14911
14912 A project file name must end with @file{.gpr}. If a single one is
14913 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14914 extract the information from it. If multiple project files are found, none of
14915 them is read, and you have to use the @samp{-p} switch to specify the one
14916 you want to use.
14917
14918 The following lines can be included, even though most of them have default
14919 values which can be used in most cases.
14920 The lines can be entered in any order in the file.
14921 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14922 each line. If you have multiple instances, only the last one is taken into
14923 account.
14924
14925 @table @code
14926 @item src_dir=DIR
14927 [default: @code{"^./^[]^"}]
14928 specifies a directory where to look for source files. Multiple @code{src_dir}
14929 lines can be specified and they will be searched in the order they
14930 are specified.
14931
14932 @item obj_dir=DIR
14933 [default: @code{"^./^[]^"}]
14934 specifies a directory where to look for object and library files. Multiple
14935 @code{obj_dir} lines can be specified, and they will be searched in the order
14936 they are specified
14937
14938 @item comp_opt=SWITCHES
14939 [default: @code{""}]
14940 creates a variable which can be referred to subsequently by using
14941 the @code{$@{comp_opt@}} notation. This is intended to store the default
14942 switches given to @command{gnatmake} and @command{gcc}.
14943
14944 @item bind_opt=SWITCHES
14945 [default: @code{""}]
14946 creates a variable which can be referred to subsequently by using
14947 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14948 switches given to @command{gnatbind}.
14949
14950 @item link_opt=SWITCHES
14951 [default: @code{""}]
14952 creates a variable which can be referred to subsequently by using
14953 the @samp{$@{link_opt@}} notation. This is intended to store the default
14954 switches given to @command{gnatlink}.
14955
14956 @item main=EXECUTABLE
14957 [default: @code{""}]
14958 specifies the name of the executable for the application. This variable can
14959 be referred to in the following lines by using the @samp{$@{main@}} notation.
14960
14961 @ifset vms
14962 @item comp_cmd=COMMAND
14963 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14964 @end ifset
14965 @ifclear vms
14966 @item comp_cmd=COMMAND
14967 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14968 @end ifclear
14969 specifies the command used to compile a single file in the application.
14970
14971 @ifset vms
14972 @item make_cmd=COMMAND
14973 [default: @code{"GNAT MAKE $@{main@}
14974 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14975 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14976 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14977 @end ifset
14978 @ifclear vms
14979 @item make_cmd=COMMAND
14980 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14981  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14982  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14983 @end ifclear
14984 specifies the command used to recompile the whole application.
14985
14986 @item run_cmd=COMMAND
14987 [default: @code{"$@{main@}"}]
14988 specifies the command used to run the application.
14989
14990 @item debug_cmd=COMMAND
14991 [default: @code{"gdb $@{main@}"}]
14992 specifies the command used to debug the application
14993
14994 @end table
14995
14996 @noindent
14997 @command{gnatxref} and @command{gnatfind} only take into account the
14998 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14999
15000 @node Regular Expressions in gnatfind and gnatxref
15001 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15002
15003 @noindent
15004 As specified in the section about @command{gnatfind}, the pattern can be a
15005 regular expression. Actually, there are to set of regular expressions
15006 which are recognized by the program :
15007
15008 @table @code
15009 @item globbing patterns
15010 These are the most usual regular expression. They are the same that you
15011 generally used in a Unix shell command line, or in a DOS session.
15012
15013 Here is a more formal grammar :
15014 @smallexample
15015 @group
15016 @iftex
15017 @leftskip=.5cm
15018 @end iftex
15019 regexp ::= term
15020 term   ::= elmt            -- matches elmt
15021 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15022 term   ::= *               -- any string of 0 or more characters
15023 term   ::= ?               -- matches any character
15024 term   ::= [char @{char@}] -- matches any character listed
15025 term   ::= [char - char]   -- matches any character in range
15026 @end group
15027 @end smallexample
15028
15029 @item full regular expression
15030 The second set of regular expressions is much more powerful. This is the
15031 type of regular expressions recognized by utilities such a @file{grep}.
15032
15033 The following is the form of a regular expression, expressed in Ada
15034 reference manual style BNF is as follows
15035
15036 @smallexample
15037 @iftex
15038 @leftskip=.5cm
15039 @end iftex
15040 @group
15041 regexp ::= term @{| term@} -- alternation (term or term ...)
15042
15043 term ::= item @{item@}     -- concatenation (item then item)
15044
15045 item ::= elmt              -- match elmt
15046 item ::= elmt *            -- zero or more elmt's
15047 item ::= elmt +            -- one or more elmt's
15048 item ::= elmt ?            -- matches elmt or nothing
15049 @end group
15050 @group
15051 elmt ::= nschar            -- matches given character
15052 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15053 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15054 elmt ::= [char - char]     -- matches chars in given range
15055 elmt ::= \ char            -- matches given character
15056 elmt ::= .                 -- matches any single character
15057 elmt ::= ( regexp )        -- parens used for grouping
15058
15059 char ::= any character, including special characters
15060 nschar ::= any character except ()[].*+?^^^
15061 @end group
15062 @end smallexample
15063
15064 Following are a few examples :
15065
15066 @table @samp
15067 @item abcde|fghi
15068 will match any of the two strings 'abcde' and 'fghi'.
15069
15070 @item abc*d
15071 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
15072
15073 @item [a-z]+
15074 will match any string which has only lowercase characters in it (and at
15075 least one character
15076
15077 @end table
15078 @end table
15079
15080 @node Examples of gnatxref Usage
15081 @section Examples of @code{gnatxref} Usage
15082
15083 @subsection General Usage
15084
15085 @noindent
15086 For the following examples, we will consider the following units :
15087
15088 @smallexample @c ada
15089 @group
15090 @cartouche
15091 main.ads:
15092 1: with Bar;
15093 2: package Main is
15094 3:     procedure Foo (B : in Integer);
15095 4:     C : Integer;
15096 5: private
15097 6:     D : Integer;
15098 7: end Main;
15099
15100 main.adb:
15101 1: package body Main is
15102 2:     procedure Foo (B : in Integer) is
15103 3:     begin
15104 4:        C := B;
15105 5:        D := B;
15106 6:        Bar.Print (B);
15107 7:        Bar.Print (C);
15108 8:     end Foo;
15109 9: end Main;
15110
15111 bar.ads:
15112 1: package Bar is
15113 2:     procedure Print (B : Integer);
15114 3: end bar;
15115 @end cartouche
15116 @end group
15117 @end smallexample
15118
15119 @table @code
15120
15121 @noindent
15122 The first thing to do is to recompile your application (for instance, in
15123 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15124 the cross-referencing information.
15125 You can then issue any of the following commands:
15126
15127 @item gnatxref main.adb
15128 @code{gnatxref} generates cross-reference information for main.adb
15129 and every unit 'with'ed by main.adb.
15130
15131 The output would be:
15132 @smallexample
15133 @iftex
15134 @leftskip=0cm
15135 @end iftex
15136 B                                                      Type: Integer
15137   Decl: bar.ads           2:22
15138 B                                                      Type: Integer
15139   Decl: main.ads          3:20
15140   Body: main.adb          2:20
15141   Ref:  main.adb          4:13     5:13     6:19
15142 Bar                                                    Type: Unit
15143   Decl: bar.ads           1:9
15144   Ref:  main.adb          6:8      7:8
15145        main.ads           1:6
15146 C                                                      Type: Integer
15147   Decl: main.ads          4:5
15148   Modi: main.adb          4:8
15149   Ref:  main.adb          7:19
15150 D                                                      Type: Integer
15151   Decl: main.ads          6:5
15152   Modi: main.adb          5:8
15153 Foo                                                    Type: Unit
15154   Decl: main.ads          3:15
15155   Body: main.adb          2:15
15156 Main                                                    Type: Unit
15157   Decl: main.ads          2:9
15158   Body: main.adb          1:14
15159 Print                                                   Type: Unit
15160   Decl: bar.ads           2:15
15161   Ref:  main.adb          6:12     7:12
15162 @end smallexample
15163
15164 @noindent
15165 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15166 its body is in main.adb, line 1, column 14 and is not referenced any where.
15167
15168 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15169 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15170
15171 @item gnatxref package1.adb package2.ads
15172 @code{gnatxref} will generates cross-reference information for
15173 package1.adb, package2.ads and any other package 'with'ed by any
15174 of these.
15175
15176 @end table
15177
15178 @ifclear vms
15179 @subsection Using gnatxref with vi
15180
15181 @code{gnatxref} can generate a tags file output, which can be used
15182 directly from @file{vi}. Note that the standard version of @file{vi}
15183 will not work properly with overloaded symbols. Consider using another
15184 free implementation of @file{vi}, such as @file{vim}.
15185
15186 @smallexample
15187 $ gnatxref -v gnatfind.adb > tags
15188 @end smallexample
15189
15190 @noindent
15191 will generate the tags file for @code{gnatfind} itself (if the sources
15192 are in the search path!).
15193
15194 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
15195 (replacing @i{entity} by whatever you are looking for), and vi will
15196 display a new file with the corresponding declaration of entity.
15197 @end ifclear
15198
15199 @node Examples of gnatfind Usage
15200 @section Examples of @code{gnatfind} Usage
15201
15202 @table @code
15203
15204 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15205 Find declarations for all entities xyz referenced at least once in
15206 main.adb. The references are search in every library file in the search
15207 path.
15208
15209 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15210 switch is set)
15211
15212 The output will look like:
15213 @smallexample
15214 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15215 ^directory/^[directory]^main.adb:24:10: xyz <= body
15216 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15217 @end smallexample
15218
15219 @noindent
15220 that is to say, one of the entities xyz found in main.adb is declared at
15221 line 12 of main.ads (and its body is in main.adb), and another one is
15222 declared at line 45 of foo.ads
15223
15224 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
15225 This is the same command as the previous one, instead @code{gnatfind} will
15226 display the content of the Ada source file lines.
15227
15228 The output will look like:
15229
15230 @smallexample
15231 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15232    procedure xyz;
15233 ^directory/^[directory]^main.adb:24:10: xyz <= body
15234    procedure xyz is
15235 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15236    xyz : Integer;
15237 @end smallexample
15238
15239 @noindent
15240 This can make it easier to find exactly the location your are looking
15241 for.
15242
15243 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
15244 Find references to all entities containing an x that are
15245 referenced on line 123 of main.ads.
15246 The references will be searched only in main.ads and foo.adb.
15247
15248 @item gnatfind main.ads:123
15249 Find declarations and bodies for all entities that are referenced on
15250 line 123 of main.ads.
15251
15252 This is the same as @code{gnatfind "*":main.adb:123}.
15253
15254 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
15255 Find the declaration for the entity referenced at column 45 in
15256 line 123 of file main.adb in directory mydir. Note that it
15257 is usual to omit the identifier name when the column is given,
15258 since the column position identifies a unique reference.
15259
15260 The column has to be the beginning of the identifier, and should not
15261 point to any character in the middle of the identifier.
15262
15263 @end table
15264
15265 @c *********************************
15266 @node The GNAT Pretty-Printer gnatpp
15267 @chapter The GNAT Pretty-Printer @command{gnatpp}
15268 @findex gnatpp
15269 @cindex Pretty-Printer
15270
15271 @noindent
15272 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
15273 for source reformatting / pretty-printing.
15274 It takes an Ada source file as input and generates a reformatted
15275 version as output.
15276 You can specify various style directives via switches; e.g.,
15277 identifier case conventions, rules of indentation, and comment layout.
15278
15279 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
15280 tree for the input source and thus requires the input to be syntactically and
15281 semantically legal.
15282 If this condition is not met, @command{gnatpp} will terminate with an
15283 error message; no output file will be generated.
15284
15285 If the source files presented to @command{gnatpp} contain
15286 preprocessing directives, then the output file will
15287 correspond to the generated source after all
15288 preprocessing is carried out. There is no way
15289 using @command{gnatpp} to obtain pretty printed files that
15290 include the preprocessing directives.
15291
15292 If the compilation unit
15293 contained in the input source depends semantically upon units located
15294 outside the current directory, you have to provide the source search path
15295 when invoking @command{gnatpp}, if these units are contained in files with
15296 names that do not follow the GNAT file naming rules, you have to provide
15297 the configuration file describing the corresponding naming scheme;
15298 see the description of the @command{gnatpp}
15299 switches below. Another possibility is to use a project file and to
15300 call @command{gnatpp} through the @command{gnat} driver
15301
15302 The @command{gnatpp} command has the form
15303
15304 @smallexample
15305 $ gnatpp [@var{switches}] @var{filename}
15306 @end smallexample
15307
15308 @noindent
15309 where
15310 @itemize @bullet
15311 @item
15312 @var{switches} is an optional sequence of switches defining such properties as
15313 the formatting rules, the source search path, and the destination for the
15314 output source file
15315
15316 @item
15317 @var{filename} is the name (including the extension) of the source file to
15318 reformat; ``wildcards'' or several file names on the same gnatpp command are
15319 allowed.  The file name may contain path information; it does not have to
15320 follow the GNAT file naming rules
15321 @end itemize
15322
15323 @menu
15324 * Switches for gnatpp::
15325 * Formatting Rules::
15326 @end menu
15327
15328 @node Switches for gnatpp
15329 @section Switches for @command{gnatpp}
15330
15331 @noindent
15332 The following subsections describe the various switches accepted by
15333 @command{gnatpp}, organized by category.
15334
15335 @ifclear vms
15336 You specify a switch by supplying a name and generally also a value.
15337 In many cases the values for a switch with a given name are incompatible with
15338 each other
15339 (for example the switch that controls the casing of a reserved word may have
15340 exactly one value: upper case, lower case, or
15341 mixed case) and thus exactly one such switch can be in effect for an
15342 invocation of @command{gnatpp}.
15343 If more than one is supplied, the last one is used.
15344 However, some values for the same switch are mutually compatible.
15345 You may supply several such switches to @command{gnatpp}, but then
15346 each must be specified in full, with both the name and the value.
15347 Abbreviated forms (the name appearing once, followed by each value) are
15348 not permitted.
15349 For example, to set
15350 the alignment of the assignment delimiter both in declarations and in
15351 assignment statements, you must write @option{-A2A3}
15352 (or @option{-A2 -A3}), but not @option{-A23}.
15353 @end ifclear
15354
15355 @ifset vms
15356 In many cases the set of options for a given qualifier are incompatible with
15357 each other (for example the qualifier that controls the casing of a reserved
15358 word may have exactly one option, which specifies either upper case, lower
15359 case, or mixed case), and thus exactly one such option can be in effect for
15360 an invocation of @command{gnatpp}.
15361 If more than one is supplied, the last one is used.
15362 However, some qualifiers have options that are mutually compatible,
15363 and then you may then supply several such options when invoking
15364 @command{gnatpp}.
15365 @end ifset
15366
15367 In most cases, it is obvious whether or not the
15368 ^values for a switch with a given name^options for a given qualifier^
15369 are compatible with each other.
15370 When the semantics might not be evident, the summaries below explicitly
15371 indicate the effect.
15372
15373 @menu
15374 * Alignment Control::
15375 * Casing Control::
15376 * Construct Layout Control::
15377 * General Text Layout Control::
15378 * Other Formatting Options::
15379 * Setting the Source Search Path::
15380 * Output File Control::
15381 * Other gnatpp Switches::
15382 @end menu
15383
15384 @node Alignment Control
15385 @subsection Alignment Control
15386 @cindex Alignment control in @command{gnatpp}
15387
15388 @noindent
15389 Programs can be easier to read if certain constructs are vertically aligned.
15390 By default all alignments are set ON.
15391 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
15392 OFF, and then use one or more of the other
15393 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
15394 to activate alignment for specific constructs.
15395
15396 @table @option
15397 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
15398
15399 @ifset vms
15400 @item /ALIGN=ON
15401 Set all alignments to ON
15402 @end ifset
15403
15404 @item ^-A0^/ALIGN=OFF^
15405 Set all alignments to OFF
15406
15407 @item ^-A1^/ALIGN=COLONS^
15408 Align @code{:} in declarations
15409
15410 @item ^-A2^/ALIGN=DECLARATIONS^
15411 Align @code{:=} in initializations in declarations
15412
15413 @item ^-A3^/ALIGN=STATEMENTS^
15414 Align @code{:=} in assignment statements
15415
15416 @item ^-A4^/ALIGN=ARROWS^
15417 Align @code{=>} in associations
15418
15419 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
15420 Align @code{at} keywords in the component clauses in record
15421 representation clauses
15422 @end table
15423
15424 @noindent
15425 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
15426 is allowed.
15427
15428 @node Casing Control
15429 @subsection Casing Control
15430 @cindex Casing control in @command{gnatpp}
15431
15432 @noindent
15433 @command{gnatpp} allows you to specify the casing for reserved words,
15434 pragma names, attribute designators and identifiers.
15435 For identifiers you may define a
15436 general rule for name casing but also override this rule
15437 via a set of dictionary files.
15438
15439 Three types of casing are supported: lower case, upper case, and mixed case.
15440 Lower and upper case are self-explanatory (but since some letters in
15441 Latin1 and other GNAT-supported character sets
15442 exist only in lower-case form, an upper case conversion will have no
15443 effect on them.)
15444 ``Mixed case'' means that the first letter, and also each letter immediately
15445 following an underscore, are converted to their uppercase forms;
15446 all the other letters are converted to their lowercase forms.
15447
15448 @table @option
15449 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
15450 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
15451 Attribute designators are lower case
15452
15453 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
15454 Attribute designators are upper case
15455
15456 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
15457 Attribute designators are mixed case (this is the default)
15458
15459 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
15460 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
15461 Keywords (technically, these are known in Ada as @emph{reserved words}) are
15462 lower case (this is the default)
15463
15464 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
15465 Keywords are upper case
15466
15467 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
15468 @item ^-nD^/NAME_CASING=AS_DECLARED^
15469 Name casing for defining occurrences are as they appear in the source file
15470 (this is the default)
15471
15472 @item ^-nU^/NAME_CASING=UPPER_CASE^
15473 Names are in upper case
15474
15475 @item ^-nL^/NAME_CASING=LOWER_CASE^
15476 Names are in lower case
15477
15478 @item ^-nM^/NAME_CASING=MIXED_CASE^
15479 Names are in mixed case
15480
15481 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
15482 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
15483 Pragma names are lower case
15484
15485 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
15486 Pragma names are upper case
15487
15488 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
15489 Pragma names are mixed case (this is the default)
15490
15491 @item ^-D@var{file}^/DICTIONARY=@var{file}^
15492 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
15493 Use @var{file} as a @emph{dictionary file} that defines
15494 the casing for a set of specified names,
15495 thereby overriding the effect on these names by
15496 any explicit or implicit
15497 ^-n^/NAME_CASING^ switch.
15498 To supply more than one dictionary file,
15499 use ^several @option{-D} switches^a list of files as options^.
15500
15501 @noindent
15502 @option{gnatpp} implicitly uses a @emph{default dictionary file}
15503 to define the casing for the Ada predefined names and
15504 the names declared in the GNAT libraries.
15505
15506 @item ^-D-^/SPECIFIC_CASING^
15507 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
15508 Do not use the default dictionary file;
15509 instead, use the casing
15510 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
15511 dictionary file(s)
15512 @end table
15513
15514 @noindent
15515 The structure of a dictionary file, and details on the conventions
15516 used in the default dictionary file, are defined in @ref{Name Casing}.
15517
15518 The @option{^-D-^/SPECIFIC_CASING^} and
15519 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
15520 compatible.
15521
15522 @node Construct Layout Control
15523 @subsection Construct Layout Control
15524 @cindex Layout control in @command{gnatpp}
15525
15526 @noindent
15527 This group of @command{gnatpp} switches controls the layout of comments and
15528 complex syntactic constructs.  See @ref{Formatting Comments} for details
15529 on their effect.
15530
15531 @table @option
15532 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
15533 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
15534 All the comments remain unchanged
15535
15536 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
15537 GNAT-style comment line indentation (this is the default).
15538
15539 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
15540 Reference-manual comment line indentation.
15541
15542 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
15543 GNAT-style comment beginning
15544
15545 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
15546 Reformat comment blocks
15547
15548 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
15549 Keep unchanged special form comments
15550
15551 Reformat comment blocks
15552
15553 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
15554 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
15555 GNAT-style layout (this is the default)
15556
15557 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
15558 Compact layout
15559
15560 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
15561 Uncompact layout
15562
15563 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
15564 @item ^-N^/NOTABS^
15565 All the VT characters are removed from the comment text. All the HT characters
15566 are expanded with the sequences of space characters to get to the next tab
15567 stops.
15568
15569 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
15570 @item ^--no-separate-is^/NO_SEPARATE_IS^
15571 Do not place the keyword @code{is} on a separate line in a subprogram body in
15572 case if the specification occupies more then one line.
15573
15574 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
15575 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
15576 Place the keyword @code{loop} in FOR and WHILE loop statements and the
15577 keyword @code{then} in IF statements on a separate line.
15578
15579 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
15580 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
15581 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
15582 keyw0rd @code{then} in IF statements on a separate line. This option is
15583 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
15584
15585 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
15586 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
15587 Start each USE clause in a context clause from a separate line.
15588
15589 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
15590 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
15591 Use a separate line for a loop or block statement name, but do not use an extra
15592 indentation level for the statement itself.
15593
15594 @end table
15595
15596 @ifclear vms
15597 @noindent
15598 The @option{-c1} and @option{-c2} switches are incompatible.
15599 The @option{-c3} and @option{-c4} switches are compatible with each other and
15600 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
15601 the other comment formatting switches.
15602
15603 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
15604 @end ifclear
15605
15606 @ifset vms
15607 @noindent
15608 For the @option{/COMMENTS_LAYOUT} qualifier:
15609 @itemize @bullet
15610 @item
15611 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
15612 @item
15613 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
15614 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
15615 @end itemize
15616
15617 @noindent
15618 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
15619 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
15620 @end ifset
15621
15622 @node General Text Layout Control
15623 @subsection General Text Layout Control
15624
15625 @noindent
15626 These switches allow control over line length and indentation.
15627
15628 @table @option
15629 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
15630 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
15631 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
15632
15633 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
15634 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
15635 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
15636
15637 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
15638 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
15639 Indentation level for continuation lines (relative to the line being
15640 continued), @i{nnn} from 1 .. 9.
15641 The default
15642 value is one less then the (normal) indentation level, unless the
15643 indentation is set to 1 (in which case the default value for continuation
15644 line indentation is also 1)
15645 @end table
15646
15647 @node Other Formatting Options
15648 @subsection Other Formatting Options
15649
15650 @noindent
15651 These switches control the inclusion of missing end/exit labels, and
15652 the indentation level in @b{case} statements.
15653
15654 @table @option
15655 @item ^-e^/NO_MISSED_LABELS^
15656 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
15657 Do not insert missing end/exit labels. An end label is the name of
15658 a construct that may optionally be repeated at the end of the
15659 construct's declaration;
15660 e.g., the names of packages, subprograms, and tasks.
15661 An exit label is the name of a loop that may appear as target
15662 of an exit statement within the loop.
15663 By default, @command{gnatpp} inserts these end/exit labels when
15664 they are absent from the original source. This option suppresses such
15665 insertion, so that the formatted source reflects the original.
15666
15667 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
15668 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
15669 Insert a Form Feed character after a pragma Page.
15670
15671 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
15672 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
15673 Do not use an additional indentation level for @b{case} alternatives
15674 and variants if there are @i{nnn} or more (the default
15675 value is 10).
15676 If @i{nnn} is 0, an additional indentation level is
15677 used for @b{case} alternatives and variants regardless of their number.
15678 @end table
15679
15680 @node Setting the Source Search Path
15681 @subsection Setting the Source Search Path
15682
15683 @noindent
15684 To define the search path for the input source file, @command{gnatpp}
15685 uses the same switches as the GNAT compiler, with the same effects.
15686
15687 @table @option
15688 @item ^-I^/SEARCH=^@var{dir}
15689 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
15690 The same as the corresponding gcc switch
15691
15692 @item ^-I-^/NOCURRENT_DIRECTORY^
15693 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
15694 The same as the corresponding gcc switch
15695
15696 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
15697 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
15698 The same as the corresponding gcc switch
15699
15700 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
15701 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
15702 The same as the corresponding gcc switch
15703
15704 @end table
15705
15706 @node Output File Control
15707 @subsection Output File Control
15708
15709 @noindent
15710 By default the output is sent to the file whose name is obtained by appending
15711 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
15712 (if the file with this name already exists, it is unconditionally overwritten).
15713 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
15714 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
15715 as output file.
15716 The output may be redirected by the following switches:
15717
15718 @table @option
15719 @item ^-pipe^/STANDARD_OUTPUT^
15720 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
15721 Send the output to @code{Standard_Output}
15722
15723 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
15724 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
15725 Write the output into @var{output_file}.
15726 If @var{output_file} already exists, @command{gnatpp} terminates without
15727 reading or processing the input file.
15728
15729 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
15730 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
15731 Write the output into @var{output_file}, overwriting the existing file
15732 (if one is present).
15733
15734 @item ^-r^/REPLACE^
15735 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
15736 Replace the input source file with the reformatted output, and copy the
15737 original input source into the file whose name is obtained by appending the
15738 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
15739 If a file with this name already exists, @command{gnatpp} terminates without
15740 reading or processing the input file.
15741
15742 @item ^-rf^/OVERRIDING_REPLACE^
15743 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
15744 Like @option{^-r^/REPLACE^} except that if the file with the specified name
15745 already exists, it is overwritten.
15746
15747 @item ^-rnb^/NO_BACKUP^
15748 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
15749 Replace the input source file with the reformatted output without
15750 creating any backup copy of the input source.
15751
15752 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
15753 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
15754 Specifies the format of the reformatted output file. The @var{xxx}
15755 ^string specified with the switch^option^ may be either
15756 @itemize @bullet
15757 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
15758 @item ``@option{^crlf^CRLF^}''
15759 the same as @option{^crlf^CRLF^}
15760 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
15761 @item ``@option{^lf^LF^}''
15762 the same as @option{^unix^UNIX^}
15763 @end itemize
15764
15765 @item ^-W^/RESULT_ENCODING=^@var{e}
15766 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
15767 Specify the wide character encoding method used to write the code in the
15768 result file
15769 @var{e} is one of the following:
15770
15771 @itemize @bullet
15772
15773 @item ^h^HEX^
15774 Hex encoding
15775
15776 @item ^u^UPPER^
15777 Upper half encoding
15778
15779 @item ^s^SHIFT_JIS^
15780 Shift/JIS encoding
15781
15782 @item ^e^EUC^
15783 EUC encoding
15784
15785 @item ^8^UTF8^
15786 UTF-8 encoding
15787
15788 @item ^b^BRACKETS^
15789 Brackets encoding (default value)
15790 @end itemize
15791
15792 @end table
15793
15794 @noindent
15795 Options @option{^-pipe^/STANDARD_OUTPUT^},
15796 @option{^-o^/OUTPUT^} and
15797 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
15798 contains only one file to reformat.
15799 Option
15800 @option{^--eol^/END_OF_LINE^}
15801 and
15802 @option{^-W^/RESULT_ENCODING^}
15803 cannot be used together
15804 with @option{^-pipe^/STANDARD_OUTPUT^} option.
15805
15806 @node Other gnatpp Switches
15807 @subsection Other @code{gnatpp} Switches
15808
15809 @noindent
15810 The additional @command{gnatpp} switches are defined in this subsection.
15811
15812 @table @option
15813 @item ^-files @var{filename}^/FILES=@var{output_file}^
15814 @cindex @option{^-files^/FILES^} (@code{gnatpp})
15815 Take the argument source files from the specified file. This file should be an
15816 ordinary textual file containing file names separated by spaces or
15817 line breaks. You can use this switch more then once in the same call to
15818 @command{gnatpp}. You also can combine this switch with explicit list of
15819 files.
15820
15821 @item ^-v^/VERBOSE^
15822 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
15823 Verbose mode;
15824 @command{gnatpp} generates version information and then
15825 a trace of the actions it takes to produce or obtain the ASIS tree.
15826
15827 @item ^-w^/WARNINGS^
15828 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
15829 Warning mode;
15830 @command{gnatpp} generates a warning whenever it cannot provide
15831 a required layout in the result source.
15832 @end table
15833
15834 @node Formatting Rules
15835 @section Formatting Rules
15836
15837 @noindent
15838 The following subsections show how @command{gnatpp} treats ``white space'',
15839 comments, program layout, and name casing.
15840 They provide the detailed descriptions of the switches shown above.
15841
15842 @menu
15843 * White Space and Empty Lines::
15844 * Formatting Comments::
15845 * Construct Layout::
15846 * Name Casing::
15847 @end menu
15848
15849 @node White Space and Empty Lines
15850 @subsection White Space and Empty Lines
15851
15852 @noindent
15853 @command{gnatpp} does not have an option to control space characters.
15854 It will add or remove spaces according to the style illustrated by the
15855 examples in the @cite{Ada Reference Manual}.
15856
15857 The only format effectors
15858 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
15859 that will appear in the output file are platform-specific line breaks,
15860 and also format effectors within (but not at the end of) comments.
15861 In particular, each horizontal tab character that is not inside
15862 a comment will be treated as a space and thus will appear in the
15863 output file as zero or more spaces depending on
15864 the reformatting of the line in which it appears.
15865 The only exception is a Form Feed character, which is inserted after a
15866 pragma @code{Page} when @option{-ff} is set.
15867
15868 The output file will contain no lines with trailing ``white space'' (spaces,
15869 format effectors).
15870
15871 Empty lines in the original source are preserved
15872 only if they separate declarations or statements.
15873 In such contexts, a
15874 sequence of two or more empty lines is replaced by exactly one empty line.
15875 Note that a blank line will be removed if it separates two ``comment blocks''
15876 (a comment block is a sequence of whole-line comments).
15877 In order to preserve a visual separation between comment blocks, use an
15878 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
15879 Likewise, if for some reason you wish to have a sequence of empty lines,
15880 use a sequence of empty comments instead.
15881
15882 @node Formatting Comments
15883 @subsection Formatting Comments
15884
15885 @noindent
15886 Comments in Ada code are of two kinds:
15887 @itemize @bullet
15888 @item
15889 a @emph{whole-line comment}, which appears by itself (possibly preceded by
15890 ``white space'') on a line
15891
15892 @item
15893 an @emph{end-of-line comment}, which follows some other Ada lexical element
15894 on the same line.
15895 @end itemize
15896
15897 @noindent
15898 The indentation of a whole-line comment is that of either
15899 the preceding or following line in
15900 the formatted source, depending on switch settings as will be described below.
15901
15902 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
15903 between the end of the preceding Ada lexical element and the beginning
15904 of the comment as appear in the original source,
15905 unless either the comment has to be split to
15906 satisfy the line length limitation, or else the next line contains a
15907 whole line comment that is considered a continuation of this end-of-line
15908 comment (because it starts at the same position).
15909 In the latter two
15910 cases, the start of the end-of-line comment is moved right to the nearest
15911 multiple of the indentation level.
15912 This may result in a ``line overflow'' (the right-shifted comment extending
15913 beyond the maximum line length), in which case the comment is split as
15914 described below.
15915
15916 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15917 (GNAT-style comment line indentation)
15918 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15919 (reference-manual comment line indentation).
15920 With reference-manual style, a whole-line comment is indented as if it
15921 were a declaration or statement at the same place
15922 (i.e., according to the indentation of the preceding line(s)).
15923 With GNAT style, a whole-line comment that is immediately followed by an
15924 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15925 word @b{begin}, is indented based on the construct that follows it.
15926
15927 For example:
15928 @smallexample @c ada
15929 @cartouche
15930 if A then
15931     null;
15932        -- some comment
15933 else
15934    null;
15935 end if;
15936 @end cartouche
15937 @end smallexample
15938
15939 @noindent
15940 Reference-manual indentation produces:
15941
15942 @smallexample @c ada
15943 @cartouche
15944 if A then
15945    null;
15946    --  some comment
15947 else
15948    null;
15949 end if;
15950 @end cartouche
15951 @end smallexample
15952
15953 @noindent
15954 while GNAT-style indentation produces:
15955
15956 @smallexample @c ada
15957 @cartouche
15958 if A then
15959    null;
15960 --  some comment
15961 else
15962    null;
15963 end if;
15964 @end cartouche
15965 @end smallexample
15966
15967 @noindent
15968 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15969 (GNAT style comment beginning) has the following
15970 effect:
15971
15972 @itemize @bullet
15973 @item
15974 For each whole-line comment that does not end with two hyphens,
15975 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15976 to ensure that there are at least two spaces between these hyphens and the
15977 first non-blank character of the comment.
15978 @end itemize
15979
15980 @noindent
15981 For an end-of-line comment, if in the original source the next line is a
15982 whole-line comment that starts at the same position
15983 as the end-of-line comment,
15984 then the whole-line comment (and all whole-line comments
15985 that follow it and that start at the same position)
15986 will start at this position in the output file.
15987
15988 @noindent
15989 That is, if in the original source we have:
15990
15991 @smallexample @c ada
15992 @cartouche
15993 begin
15994 A := B + C;            --  B must be in the range Low1..High1
15995                        --  C must be in the range Low2..High2
15996              --B+C will be in the range Low1+Low2..High1+High2
15997 X := X + 1;
15998 @end cartouche
15999 @end smallexample
16000
16001 @noindent
16002 Then in the formatted source we get
16003
16004 @smallexample @c ada
16005 @cartouche
16006 begin
16007    A := B + C;            --  B must be in the range Low1..High1
16008                           --  C must be in the range Low2..High2
16009    --  B+C will be in the range Low1+Low2..High1+High2
16010    X := X + 1;
16011 @end cartouche
16012 @end smallexample
16013
16014 @noindent
16015 A comment that exceeds the line length limit will be split.
16016 Unless switch
16017 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16018 the line belongs to a reformattable block, splitting the line generates a
16019 @command{gnatpp} warning.
16020 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16021 comments may be reformatted in typical
16022 word processor style (that is, moving words between lines and putting as
16023 many words in a line as possible).
16024
16025 @noindent
16026 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16027 that has a special format (that is, a character that is neither a letter nor digit
16028 not white space nor line break immediatelly following the leading @code{--} of
16029 the comment) should be without any change moved from the argument source
16030 into reformatted source. This switch allows to preserve comments that are used
16031 as a special marks in the code (e.g. SPARK annotation).
16032
16033 @node Construct Layout
16034 @subsection Construct Layout
16035
16036 @noindent
16037 In several cases the suggested layout in the Ada Reference Manual includes
16038 an extra level of indentation that many programmers prefer to avoid. The
16039 affected cases include:
16040
16041 @itemize @bullet
16042
16043 @item Record type declaration (RM 3.8)
16044
16045 @item Record representation clause (RM 13.5.1)
16046
16047 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16048
16049 @item Block statement in case if a block has a statement identifier (RM 5.6)
16050 @end itemize
16051
16052 @noindent
16053 In compact mode (when GNAT style layout or compact layout is set),
16054 the pretty printer uses one level of indentation instead
16055 of two. This is achieved in the record definition and record representation
16056 clause cases by putting the @code{record} keyword on the same line as the
16057 start of the declaration or representation clause, and in the block and loop
16058 case by putting the block or loop header on the same line as the statement
16059 identifier.
16060
16061 @noindent
16062 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16063 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16064 layout on the one hand, and uncompact layout
16065 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16066 can be illustrated by the following examples:
16067
16068 @iftex
16069 @cartouche
16070 @multitable @columnfractions .5 .5
16071 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16072
16073 @item
16074 @smallexample @c ada
16075 type q is record
16076    a : integer;
16077    b : integer;
16078 end record;
16079 @end smallexample
16080 @tab
16081 @smallexample @c ada
16082 type q is
16083    record
16084       a : integer;
16085       b : integer;
16086    end record;
16087 @end smallexample
16088
16089 @item
16090 @smallexample @c ada
16091 for q use record
16092    a at 0 range  0 .. 31;
16093    b at 4 range  0 .. 31;
16094 end record;
16095 @end smallexample
16096 @tab
16097 @smallexample @c ada
16098 for q use
16099    record
16100       a at 0 range  0 .. 31;
16101       b at 4 range  0 .. 31;
16102    end record;
16103 @end smallexample
16104
16105 @item
16106 @smallexample @c ada
16107 Block : declare
16108    A : Integer := 3;
16109 begin
16110    Proc (A, A);
16111 end Block;
16112 @end smallexample
16113 @tab
16114 @smallexample @c ada
16115 Block :
16116    declare
16117       A : Integer := 3;
16118    begin
16119       Proc (A, A);
16120    end Block;
16121 @end smallexample
16122
16123 @item
16124 @smallexample @c ada
16125 Clear : for J in 1 .. 10 loop
16126    A (J) := 0;
16127 end loop Clear;
16128 @end smallexample
16129 @tab
16130 @smallexample @c ada
16131 Clear :
16132    for J in 1 .. 10 loop
16133       A (J) := 0;
16134    end loop Clear;
16135 @end smallexample
16136 @end multitable
16137 @end cartouche
16138 @end iftex
16139
16140 @ifnottex
16141 @smallexample
16142 @cartouche
16143 GNAT style, compact layout              Uncompact layout
16144
16145 type q is record                        type q is
16146    a : integer;                            record
16147    b : integer;                               a : integer;
16148 end record;                                   b : integer;
16149                                            end record;
16150
16151 for q use record                        for q use
16152    a at 0 range  0 .. 31;                  record
16153    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16154 end record;                                   b at 4 range  0 .. 31;
16155                                            end record;
16156
16157 Block : declare                         Block :
16158    A : Integer := 3;                       declare
16159 begin                                         A : Integer := 3;
16160    Proc (A, A);                            begin
16161 end Block;                                    Proc (A, A);
16162                                            end Block;
16163
16164 Clear : for J in 1 .. 10 loop           Clear :
16165    A (J) := 0;                             for J in 1 .. 10 loop
16166 end loop Clear;                               A (J) := 0;
16167                                            end loop Clear;
16168 @end cartouche
16169 @end smallexample
16170 @end ifnottex
16171
16172 @noindent
16173 A further difference between GNAT style layout and compact layout is that
16174 GNAT style layout inserts empty lines as separation for
16175 compound statements, return statements and bodies.
16176
16177 Note that the layout specified by
16178 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16179 for named block and loop statements overrides the layout defined by these
16180 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16181 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16182 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16183
16184 @node Name Casing
16185 @subsection Name Casing
16186
16187 @noindent
16188 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16189 the same casing as the corresponding defining identifier.
16190
16191 You control the casing for defining occurrences via the
16192 @option{^-n^/NAME_CASING^} switch.
16193 @ifclear vms
16194 With @option{-nD} (``as declared'', which is the default),
16195 @end ifclear
16196 @ifset vms
16197 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16198 @end ifset
16199 defining occurrences appear exactly as in the source file
16200 where they are declared.
16201 The other ^values for this switch^options for this qualifier^ ---
16202 @option{^-nU^UPPER_CASE^},
16203 @option{^-nL^LOWER_CASE^},
16204 @option{^-nM^MIXED_CASE^} ---
16205 result in
16206 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16207 If @command{gnatpp} changes the casing of a defining
16208 occurrence, it analogously changes the casing of all the
16209 usage occurrences of this name.
16210
16211 If the defining occurrence of a name is not in the source compilation unit
16212 currently being processed by @command{gnatpp}, the casing of each reference to
16213 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16214 switch (subject to the dictionary file mechanism described below).
16215 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16216 had affected the
16217 casing for the defining occurrence of the name.
16218
16219 Some names may need to be spelled with casing conventions that are not
16220 covered by the upper-, lower-, and mixed-case transformations.
16221 You can arrange correct casing by placing such names in a
16222 @emph{dictionary file},
16223 and then supplying a @option{^-D^/DICTIONARY^} switch.
16224 The casing of names from dictionary files overrides
16225 any @option{^-n^/NAME_CASING^} switch.
16226
16227 To handle the casing of Ada predefined names and the names from GNAT libraries,
16228 @command{gnatpp} assumes a default dictionary file.
16229 The name of each predefined entity is spelled with the same casing as is used
16230 for the entity in the @cite{Ada Reference Manual}.
16231 The name of each entity in the GNAT libraries is spelled with the same casing
16232 as is used in the declaration of that entity.
16233
16234 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
16235 default dictionary file.
16236 Instead, the casing for predefined and GNAT-defined names will be established
16237 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
16238 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
16239 will appear as just shown,
16240 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
16241 To ensure that even such names are rendered in uppercase,
16242 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
16243 (or else, less conveniently, place these names in upper case in a dictionary
16244 file).
16245
16246 A dictionary file is
16247 a plain text file; each line in this file can be either a blank line
16248 (containing only space characters and ASCII.HT characters), an Ada comment
16249 line, or the specification of exactly one @emph{casing schema}.
16250
16251 A casing schema is a string that has the following syntax:
16252
16253 @smallexample
16254 @cartouche
16255   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
16256
16257   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
16258 @end cartouche
16259 @end smallexample
16260
16261 @noindent
16262 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
16263 @var{identifier} lexical element and the @var{letter_or_digit} category.)
16264
16265 The casing schema string can be followed by white space and/or an Ada-style
16266 comment; any amount of white space is allowed before the string.
16267
16268 If a dictionary file is passed as
16269 @ifclear vms
16270 the value of a @option{-D@var{file}} switch
16271 @end ifclear
16272 @ifset vms
16273 an option to the @option{/DICTIONARY} qualifier
16274 @end ifset
16275 then for every
16276 simple name and every identifier, @command{gnatpp} checks if the dictionary
16277 defines the casing for the name or for some of its parts (the term ``subword''
16278 is used below to denote the part of a name which is delimited by ``_'' or by
16279 the beginning or end of the word and which does not contain any ``_'' inside):
16280
16281 @itemize @bullet
16282 @item
16283 if the whole name is in the dictionary, @command{gnatpp} uses for this name
16284 the casing defined by the dictionary; no subwords are checked for this word
16285
16286 @item
16287 for every subword @command{gnatpp} checks if the dictionary contains the
16288 corresponding string of the form @code{*@var{simple_identifier}*},
16289 and if it does, the casing of this @var{simple_identifier} is used
16290 for this subword
16291
16292 @item
16293 if the whole name does not contain any ``_'' inside, and if for this name
16294 the dictionary contains two entries - one of the form @var{identifier},
16295 and another - of the form *@var{simple_identifier}*, then the first one
16296 is applied to define the casing of this name
16297
16298 @item
16299 if more than one dictionary file is passed as @command{gnatpp} switches, each
16300 dictionary adds new casing exceptions and overrides all the existing casing
16301 exceptions set by the previous dictionaries
16302
16303 @item
16304 when @command{gnatpp} checks if the word or subword is in the dictionary,
16305 this check is not case sensitive
16306 @end itemize
16307
16308 @noindent
16309 For example, suppose we have the following source to reformat:
16310
16311 @smallexample @c ada
16312 @cartouche
16313 procedure test is
16314    name1 : integer := 1;
16315    name4_name3_name2 : integer := 2;
16316    name2_name3_name4 : Boolean;
16317    name1_var : Float;
16318 begin
16319    name2_name3_name4 := name4_name3_name2 > name1;
16320 end;
16321 @end cartouche
16322 @end smallexample
16323
16324 @noindent
16325 And suppose we have two dictionaries:
16326
16327 @smallexample
16328 @cartouche
16329 @i{dict1:}
16330    NAME1
16331    *NaMe3*
16332    *Name1*
16333 @end cartouche
16334
16335 @cartouche
16336 @i{dict2:}
16337   *NAME3*
16338 @end cartouche
16339 @end smallexample
16340
16341 @noindent
16342 If @command{gnatpp} is called with the following switches:
16343
16344 @smallexample
16345 @ifclear vms
16346 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
16347 @end ifclear
16348 @ifset vms
16349 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
16350 @end ifset
16351 @end smallexample
16352
16353 @noindent
16354 then we will get the following name casing in the @command{gnatpp} output:
16355
16356 @smallexample @c ada
16357 @cartouche
16358 procedure Test is
16359    NAME1             : Integer := 1;
16360    Name4_NAME3_Name2 : Integer := 2;
16361    Name2_NAME3_Name4 : Boolean;
16362    Name1_Var         : Float;
16363 begin
16364    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
16365 end Test;
16366 @end cartouche
16367 @end smallexample
16368
16369 @c *********************************
16370 @node The GNAT Metric Tool gnatmetric
16371 @chapter The GNAT Metric Tool @command{gnatmetric}
16372 @findex gnatmetric
16373 @cindex Metric tool
16374
16375 @noindent
16376 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
16377 for computing various program metrics.
16378 It takes an Ada source file as input and generates a file containing the
16379 metrics data as output. Various switches control which
16380 metrics are computed and output.
16381
16382 @command{gnatmetric} generates and uses the ASIS
16383 tree for the input source and thus requires the input to be syntactically and
16384 semantically legal.
16385 If this condition is not met, @command{gnatmetric} will generate
16386 an error message; no metric information for this file will be
16387 computed and reported.
16388
16389 If the compilation unit contained in the input source depends semantically
16390 upon units in files located outside the current directory, you have to provide
16391 the source search path when invoking @command{gnatmetric}.
16392 If it depends semantically upon units that are contained
16393 in files with names that do not follow the GNAT file naming rules, you have to
16394 provide the configuration file describing the corresponding naming scheme (see
16395 the description of the @command{gnatmetric} switches below.)
16396 Alternatively, you may use a project file and invoke @command{gnatmetric}
16397 through the @command{gnat} driver.
16398
16399 The @command{gnatmetric} command has the form
16400
16401 @smallexample
16402 $ gnatmetric [@i{switches}] @{@i{filename}@} [@i{-cargs gcc_switches}]
16403 @end smallexample
16404
16405 @noindent
16406 where
16407 @itemize @bullet
16408 @item
16409 @i{switches} specify the metrics to compute and define the destination for
16410 the output
16411
16412 @item
16413 Each @i{filename} is the name (including the extension) of a source
16414 file to process. ``Wildcards'' are allowed, and
16415 the file name may contain path information.
16416 If no @i{filename} is supplied, then the @i{switches} list must contain
16417 at least one
16418 @option{-files} switch (@pxref{Other gnatmetric Switches}).
16419 Including both a @option{-files} switch and one or more
16420 @i{filename} arguments is permitted.
16421
16422 @item
16423 @i{-cargs gcc_switches} is a list of switches for
16424 @command{gcc}. They will be passed on to all compiler invocations made by
16425 @command{gnatmetric} to generate the ASIS trees. Here you can provide
16426 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
16427 and use the @option{-gnatec} switch to set the configuration file.
16428 @end itemize
16429
16430 @menu
16431 * Switches for gnatmetric::
16432 @end menu
16433
16434 @node Switches for gnatmetric
16435 @section Switches for @command{gnatmetric}
16436
16437 @noindent
16438 The following subsections describe the various switches accepted by
16439 @command{gnatmetric}, organized by category.
16440
16441 @menu
16442 * Output Files Control::
16443 * Disable Metrics For Local Units::
16444 * Specifying a set of metrics to compute::
16445 * Other gnatmetric Switches::
16446 * Generate project-wide metrics::
16447 @end menu
16448
16449 @node Output Files Control
16450 @subsection Output File Control
16451 @cindex Output file control in @command{gnatmetric}
16452
16453 @noindent
16454 @command{gnatmetric} has two output formats. It can generate a
16455 textual (human-readable) form, and also XML. By default only textual
16456 output is generated.
16457
16458 When generating the output in textual form, @command{gnatmetric} creates
16459 for each Ada source file a corresponding text file
16460 containing the computed metrics, except for the case when the set of metrics
16461 specified by gnatmetric parameters consists only of metrics that are computed
16462 for the whole set of analyzed sources, but not for each Ada source.
16463 By default, this file is placed in the same directory as where the source
16464 file is located, and its name is obtained
16465 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
16466 input file.
16467
16468 All the output information generated in XML format is placed in a single
16469 file. By default this file is placed in the current directory and has the
16470 name ^@file{metrix.xml}^@file{METRIX$XML}^.
16471
16472 Some of the computed metrics are summed over the units passed to
16473 @command{gnatmetric}; for example, the total number of lines of code.
16474 By default this information is sent to @file{stdout}, but a file
16475 can be specified with the @option{-og} switch.
16476
16477 The following switches control the @command{gnatmetric} output:
16478
16479 @table @option
16480 @cindex @option{^-x^/XML^} (@command{gnatmetric})
16481 @item ^-x^/XML^
16482 Generate the XML output
16483
16484 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
16485 @item ^-nt^/NO_TEXT^
16486 Do not generate the output in text form (implies @option{^-x^/XML^})
16487
16488 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
16489 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
16490 Put textual files with detailed metrics into @var{output_dir}
16491
16492 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
16493 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
16494 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
16495 in the name of the output file.
16496
16497 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
16498 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
16499 Put global metrics into @var{file_name}
16500
16501 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
16502 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
16503 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
16504
16505 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
16506 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
16507 Use ``short'' source file names in the output.  (The @command{gnatmetric}
16508 output includes the name(s) of the Ada source file(s) from which the metrics
16509 are computed.  By default each name includes the absolute path. The
16510 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
16511 to exclude all directory information from the file names that are output.)
16512
16513 @end table
16514
16515 @node Disable Metrics For Local Units
16516 @subsection Disable Metrics For Local Units
16517 @cindex Disable Metrics For Local Units in @command{gnatmetric}
16518
16519 @noindent
16520 @command{gnatmetric} relies on the GNAT compilation model @minus{}
16521 one compilation
16522 unit per one source file. It computes line metrics for the whole source
16523 file, and it also computes syntax
16524 and complexity metrics for the file's outermost unit.
16525
16526 By default, @command{gnatmetric} will also compute all metrics for certain
16527 kinds of locally declared program units:
16528
16529 @itemize @bullet
16530 @item
16531 subprogram (and generic subprogram) bodies;
16532
16533 @item
16534 package (and generic package) specifications and bodies;
16535
16536 @item
16537 task object and type specifications and bodies;
16538
16539 @item
16540 protected object and type specifications and bodies.
16541 @end itemize
16542
16543 @noindent
16544 These kinds of entities will be referred to as
16545 @emph{eligible local program units}, or simply @emph{eligible local units},
16546 @cindex Eligible local unit (for @command{gnatmetric})
16547 in the discussion below.
16548
16549 Note that a subprogram declaration, generic instantiation,
16550 or renaming declaration only receives metrics
16551 computation when it appear as the outermost entity
16552 in a source file.
16553
16554 Suppression of metrics computation for eligible local units can be
16555 obtained via the following switch:
16556
16557 @table @option
16558 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16559 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
16560 Do not compute detailed metrics for eligible local program units
16561
16562 @end table
16563
16564 @node Specifying a set of metrics to compute
16565 @subsection Specifying a set of metrics to compute
16566
16567 @noindent
16568 By default all the metrics are computed and reported. The switches
16569 described in this subsection allow you to control, on an individual
16570 basis, whether metrics are computed and
16571 reported. If at least one positive metric
16572 switch is specified (that is, a switch that defines that a given
16573 metric or set of metrics is to be computed), then only
16574 explicitly specified metrics are reported.
16575
16576 @menu
16577 * Line Metrics Control::
16578 * Syntax Metrics Control::
16579 * Complexity Metrics Control::
16580 @end menu
16581
16582 @node Line Metrics Control
16583 @subsubsection Line Metrics Control
16584 @cindex Line metrics control in @command{gnatmetric}
16585
16586 @noindent
16587 For any (legal) source file, and for each of its
16588 eligible local program units, @command{gnatmetric} computes the following
16589 metrics:
16590
16591 @itemize @bullet
16592 @item
16593 the total number of lines;
16594
16595 @item
16596 the total number of code lines (i.e., non-blank lines that are not comments)
16597
16598 @item
16599 the number of comment lines
16600
16601 @item
16602 the number of code lines containing end-of-line comments;
16603
16604 @item
16605 the comment percentage: the ratio between the number of lines that contain
16606 comments and the number of all non-blank lines, expressed as a percentage;
16607
16608 @item
16609 the number of empty lines and lines containing only space characters and/or
16610 format effectors (blank lines)
16611
16612 @item
16613 the average number of code lines in subprogram bodies, task bodies, entry
16614 bodies and statement sequences in package bodies (this metric is only computed
16615 across the whole set of the analyzed units)
16616
16617 @end itemize
16618
16619 @noindent
16620 @command{gnatmetric} sums the values of the line metrics for all the
16621 files being processed and then generates the cumulative results. The tool
16622 also computes for all the files being processed the average number of code
16623 lines in bodies.
16624
16625 You can use the following switches to select the specific line metrics
16626 to be computed and reported.
16627
16628 @table @option
16629 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
16630
16631 @ifclear vms
16632 @cindex @option{--no-lines@var{x}}
16633 @end ifclear
16634
16635 @item ^--lines-all^/LINE_COUNT_METRICS=ALL_ON^
16636 Report all the line metrics
16637
16638 @item ^--no-lines-all^/LINE_COUNT_METRICS=ALL_OFF^
16639 Do not report any of line metrics
16640
16641 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES_ON^
16642 Report the number of all lines
16643
16644 @item ^--no-lines^/LINE_COUNT_METRICS=ALL_LINES_OFF^
16645 Do not report the number of all lines
16646
16647 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES_ON^
16648 Report the number of code lines
16649
16650 @item ^--no-lines-code^/LINE_COUNT_METRICS=CODE_LINES_OFF^
16651 Do not report the number of code lines
16652
16653 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_ON^
16654 Report the number of comment lines
16655
16656 @item ^--no-lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_OFF^
16657 Do not report the number of comment lines
16658
16659 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_ON^
16660 Report the number of code lines containing
16661 end-of-line comments
16662
16663 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_OFF^
16664 Do not report the number of code lines containing
16665 end-of-line comments
16666
16667 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_ON^
16668 Report the comment percentage in the program text
16669
16670 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_OFF^
16671 Do not report the comment percentage in the program text
16672
16673 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_ON^
16674 Report the number of blank lines
16675
16676 @item ^--no-lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_OFF^
16677 Do not report the number of blank lines
16678
16679 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_ON^
16680 Report the average number of code lines in subprogram bodies, task bodies,
16681 entry bodies and statement sequences in package bodies. The metric is computed
16682 and reported for the whole set of processed Ada sources only.
16683
16684 @item ^--no-lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_OFF^
16685 Do not report the average number of code lines in subprogram bodies,
16686 task bodies, entry bodies and statement sequences in package bodies.
16687
16688 @end table
16689
16690 @node Syntax Metrics Control
16691 @subsubsection Syntax Metrics Control
16692 @cindex Syntax metrics control in @command{gnatmetric}
16693
16694 @noindent
16695 @command{gnatmetric} computes various syntactic metrics for the
16696 outermost unit and for each eligible local unit:
16697
16698 @table @emph
16699 @item LSLOC (``Logical Source Lines Of Code'')
16700 The total number of declarations and the total number of statements
16701
16702 @item Maximal static nesting level of inner program units
16703 According to
16704 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
16705 package, a task unit, a protected unit, a
16706 protected entry, a generic unit, or an explicitly declared subprogram other
16707 than an enumeration literal.''
16708
16709 @item Maximal nesting level of composite syntactic constructs
16710 This corresponds to the notion of the
16711 maximum nesting level in the GNAT built-in style checks
16712 (@pxref{Style Checking})
16713 @end table
16714
16715 @noindent
16716 For the outermost unit in the file, @command{gnatmetric} additionally computes
16717 the following metrics:
16718
16719 @table @emph
16720 @item Public subprograms
16721 This metric is computed for package specifications. It is the
16722 number of subprograms and generic subprograms declared in the visible
16723 part (including the visible part of nested packages, protected objects, and
16724 protected types).
16725
16726 @item All subprograms
16727 This metric is computed for bodies and subunits. The
16728 metric is equal to a total number of subprogram bodies in the compilation
16729 unit.
16730 Neither generic instantiations nor renamings-as-a-body nor body stubs
16731 are counted. Any subprogram body is counted, independently of its nesting
16732 level and enclosing constructs. Generic bodies and bodies of protected
16733 subprograms are counted in the same way as ``usual'' subprogram bodies.
16734
16735 @item Public types
16736 This metric is computed for package specifications and
16737 generic package declarations. It is the total number of types
16738 that can be referenced from outside this compilation unit, plus the
16739 number of types from all the visible parts of all the visible generic
16740 packages. Generic formal types are not counted.  Only types, not subtypes,
16741 are included.
16742
16743 @noindent
16744 Along with the total number of public types, the following
16745 types are counted and reported separately:
16746
16747 @itemize @bullet
16748 @item
16749 Abstract types
16750
16751 @item
16752 Root tagged types (abstract, non-abstract, private, non-private). Type
16753 extensions are @emph{not} counted
16754
16755 @item
16756 Private types (including private extensions)
16757
16758 @item
16759 Task types
16760
16761 @item
16762 Protected types
16763
16764 @end itemize
16765
16766 @item All types
16767 This metric is computed for any compilation unit. It is equal to the total
16768 number of the declarations of different types given in the compilation unit.
16769 The private and the corresponding full type declaration are counted as one
16770 type declaration. Incomplete type declarations and generic formal types
16771 are not counted.
16772 No distinction is made among different kinds of types (abstract,
16773 private etc.); the total number of types is computed and reported.
16774
16775 @end table
16776
16777 @noindent
16778 By default, all the syntax metrics are computed and reported. You can use the
16779 following switches to select specific syntax metrics.
16780
16781 @table @option
16782
16783 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
16784
16785 @ifclear vms
16786 @cindex @option{--no-syntax@var{x}}
16787 @end ifclear
16788
16789 @item ^--syntax-all^/SYNTAX_METRICS=ALL_ON^
16790 Report all the syntax metrics
16791
16792 @item ^--no-syntax-all^/ALL_OFF^
16793 Do not report any of syntax metrics
16794
16795 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS_ON^
16796 Report the total number of declarations
16797
16798 @item ^--no-declarations^/SYNTAX_METRICS=DECLARATIONS_OFF^
16799 Do not report the total number of declarations
16800
16801 @item ^--statements^/SYNTAX_METRICS=STATEMENTS_ON^
16802 Report the total number of statements
16803
16804 @item ^--no-statements^/SYNTAX_METRICS=STATEMENTS_OFF^
16805 Do not report the total number of statements
16806
16807 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_ON^
16808 Report the number of public subprograms in a compilation unit
16809
16810 @item ^--no-public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_OFF^
16811 Do not report the number of public subprograms in a compilation unit
16812
16813 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_ON^
16814 Report the number of all the subprograms in a compilation unit
16815
16816 @item ^--no-all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_OFF^
16817 Do not report the number of all the subprograms in a compilation unit
16818
16819 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES_ON^
16820 Report the number of public types in a compilation unit
16821
16822 @item ^--no-public-types^/SYNTAX_METRICS=PUBLIC_TYPES_OFF^
16823 Do not report the number of public types in a compilation unit
16824
16825 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES_ON^
16826 Report the number of all the types in a compilation unit
16827
16828 @item ^--no-all-types^/SYNTAX_METRICS=ALL_TYPES_OFF^
16829 Do not report the number of all the types in a compilation unit
16830
16831 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_ON^
16832 Report the maximal program unit nesting level
16833
16834 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
16835 Do not report the maximal program unit nesting level
16836
16837 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_ON^
16838 Report the maximal construct nesting level
16839
16840 @item ^--no-construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_OFF^
16841 Do not report the maximal construct nesting level
16842
16843 @end table
16844
16845 @node Complexity Metrics Control
16846 @subsubsection Complexity Metrics Control
16847 @cindex Complexity metrics control in @command{gnatmetric}
16848
16849 @noindent
16850 For a program unit that is an executable body (a subprogram body (including
16851 generic bodies), task body, entry body or a package body containing
16852 its own statement sequence) @command{gnatmetric} computes the following
16853 complexity metrics:
16854
16855 @itemize @bullet
16856 @item
16857 McCabe cyclomatic complexity;
16858
16859 @item
16860 McCabe essential complexity;
16861
16862 @item
16863 maximal loop nesting level
16864
16865 @end itemize
16866
16867 @noindent
16868 The McCabe complexity metrics are defined
16869 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
16870
16871 According to McCabe, both control statements and short-circuit control forms
16872 should be taken into account when computing cyclomatic complexity. For each
16873 body, we compute three metric values:
16874
16875 @itemize @bullet
16876 @item
16877 the complexity introduced by control
16878 statements only, without taking into account short-circuit forms,
16879
16880 @item
16881 the complexity introduced by short-circuit control forms only, and
16882
16883 @item
16884 the total
16885 cyclomatic complexity, which is the sum of these two values.
16886 @end itemize
16887
16888 @noindent
16889 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16890 the code in the exception handlers and in all the nested program units.
16891
16892 By default, all the complexity metrics are computed and reported.
16893 For more fine-grained control you can use
16894 the following switches:
16895
16896 @table @option
16897 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
16898
16899 @ifclear vms
16900 @cindex @option{--no-complexity@var{x}}
16901 @end ifclear
16902
16903 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL_ON^
16904 Report all the complexity metrics
16905
16906 @item ^--no-complexity-all^/COMPLEXITY_METRICS=ALL_OFF^
16907 Do not report any of complexity metrics
16908
16909 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_ON^
16910 Report the McCabe Cyclomatic Complexity
16911
16912 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_OFF^
16913 Do not report the McCabe Cyclomatic Complexity
16914
16915 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_ON^
16916 Report the Essential Complexity
16917
16918 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_OFF^
16919 Do not report the Essential Complexity
16920
16921 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
16922 Report maximal loop nesting level
16923
16924 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_OFF^
16925 Do not report maximal loop nesting level
16926
16927 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_ON^
16928 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
16929 task bodies, entry bodies and statement sequences in package bodies.
16930 The metric is computed and reported for whole set of processed Ada sources
16931 only.
16932
16933 @item ^--no-complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_OFF^
16934 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
16935 bodies, task bodies, entry bodies and statement sequences in package bodies
16936
16937 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
16938 @item ^-ne^/NO_EXITS_AS_GOTOS^
16939 Do not consider @code{exit} statements as @code{goto}s when
16940 computing Essential Complexity
16941
16942 @end table
16943
16944 @node Other gnatmetric Switches
16945 @subsection Other @code{gnatmetric} Switches
16946
16947 @noindent
16948 Additional @command{gnatmetric} switches are as follows:
16949
16950 @table @option
16951 @item ^-files @var{filename}^/FILES=@var{filename}^
16952 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16953 Take the argument source files from the specified file. This file should be an
16954 ordinary text file containing file names separated by spaces or
16955 line breaks. You can use this switch more then once in the same call to
16956 @command{gnatmetric}. You also can combine this switch with
16957 an explicit list of files.
16958
16959 @item ^-v^/VERBOSE^
16960 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16961 Verbose mode;
16962 @command{gnatmetric} generates version information and then
16963 a trace of sources being processed.
16964
16965 @item ^-dv^/DEBUG_OUTPUT^
16966 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
16967 Debug mode;
16968 @command{gnatmetric} generates various messages useful to understand what
16969 happens during the metrics computation
16970
16971 @item ^-q^/QUIET^
16972 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16973 Quiet mode.
16974 @end table
16975
16976 @node Generate project-wide metrics
16977 @subsection Generate project-wide metrics
16978
16979 In order to compute metrics on all units of a given project, you can use
16980 the @command{gnat} driver along with the @option{-P} option:
16981 @smallexample
16982    gnat metric -Pproj
16983 @end smallexample
16984
16985 @noindent
16986 If the project @code{proj} depends upon other projects, you can compute
16987 the metrics on the project closure using the @option{-U} option:
16988 @smallexample
16989    gnat metric -Pproj -U
16990 @end smallexample
16991
16992 @noindent
16993 Finally, if not all the units are relevant to a particular main
16994 program in the project closure, you can generate metrics for the set
16995 of units needed to create a given main program (unit closure) using
16996 the @option{-U} option followed by the name of the main unit:
16997 @smallexample
16998    gnat metric -Pproj -U main
16999 @end smallexample
17000
17001
17002 @c ***********************************
17003 @node File Name Krunching Using gnatkr
17004 @chapter File Name Krunching Using @code{gnatkr}
17005 @findex gnatkr
17006
17007 @noindent
17008 This chapter discusses the method used by the compiler to shorten
17009 the default file names chosen for Ada units so that they do not
17010 exceed the maximum length permitted. It also describes the
17011 @code{gnatkr} utility that can be used to determine the result of
17012 applying this shortening.
17013 @menu
17014 * About gnatkr::
17015 * Using gnatkr::
17016 * Krunching Method::
17017 * Examples of gnatkr Usage::
17018 @end menu
17019
17020 @node About gnatkr
17021 @section About @code{gnatkr}
17022
17023 @noindent
17024 The default file naming rule in GNAT
17025 is that the file name must be derived from
17026 the unit name. The exact default rule is as follows:
17027 @itemize @bullet
17028 @item
17029 Take the unit name and replace all dots by hyphens.
17030 @item
17031 If such a replacement occurs in the
17032 second character position of a name, and the first character is
17033 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
17034 ^~ (tilde)^$ (dollar sign)^
17035 instead of a minus.
17036 @end itemize
17037 The reason for this exception is to avoid clashes
17038 with the standard names for children of System, Ada, Interfaces,
17039 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
17040 respectively.
17041
17042 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17043 switch of the compiler activates a ``krunching''
17044 circuit that limits file names to nn characters (where nn is a decimal
17045 integer). For example, using OpenVMS,
17046 where the maximum file name length is
17047 39, the value of nn is usually set to 39, but if you want to generate
17048 a set of files that would be usable if ported to a system with some
17049 different maximum file length, then a different value can be specified.
17050 The default value of 39 for OpenVMS need not be specified.
17051
17052 The @code{gnatkr} utility can be used to determine the krunched name for
17053 a given file, when krunched to a specified maximum length.
17054
17055 @node Using gnatkr
17056 @section Using @code{gnatkr}
17057
17058 @noindent
17059 The @code{gnatkr} command has the form
17060
17061 @ifclear vms
17062 @smallexample
17063 $ gnatkr @var{name} [@var{length}]
17064 @end smallexample
17065 @end ifclear
17066
17067 @ifset vms
17068 @smallexample
17069 $ gnatkr @var{name} /COUNT=nn
17070 @end smallexample
17071 @end ifset
17072
17073 @noindent
17074 @var{name} is the uncrunched file name, derived from the name of the unit
17075 in the standard manner described in the previous section (i.e. in particular
17076 all dots are replaced by hyphens). The file name may or may not have an
17077 extension (defined as a suffix of the form period followed by arbitrary
17078 characters other than period). If an extension is present then it will
17079 be preserved in the output. For example, when krunching @file{hellofile.ads}
17080 to eight characters, the result will be hellofil.ads.
17081
17082 Note: for compatibility with previous versions of @code{gnatkr} dots may
17083 appear in the name instead of hyphens, but the last dot will always be
17084 taken as the start of an extension. So if @code{gnatkr} is given an argument
17085 such as @file{Hello.World.adb} it will be treated exactly as if the first
17086 period had been a hyphen, and for example krunching to eight characters
17087 gives the result @file{hellworl.adb}.
17088
17089 Note that the result is always all lower case (except on OpenVMS where it is
17090 all upper case). Characters of the other case are folded as required.
17091
17092 @var{length} represents the length of the krunched name. The default
17093 when no argument is given is ^8^39^ characters. A length of zero stands for
17094 unlimited, in other words do not chop except for system files where the
17095 implied crunching length is always eight characters.
17096
17097 @noindent
17098 The output is the krunched name. The output has an extension only if the
17099 original argument was a file name with an extension.
17100
17101 @node Krunching Method
17102 @section Krunching Method
17103
17104 @noindent
17105 The initial file name is determined by the name of the unit that the file
17106 contains. The name is formed by taking the full expanded name of the
17107 unit and replacing the separating dots with hyphens and
17108 using ^lowercase^uppercase^
17109 for all letters, except that a hyphen in the second character position is
17110 replaced by a ^tilde^dollar sign^ if the first character is
17111 ^a, i, g, or s^A, I, G, or S^.
17112 The extension is @code{.ads} for a
17113 specification and @code{.adb} for a body.
17114 Krunching does not affect the extension, but the file name is shortened to
17115 the specified length by following these rules:
17116
17117 @itemize @bullet
17118 @item
17119 The name is divided into segments separated by hyphens, tildes or
17120 underscores and all hyphens, tildes, and underscores are
17121 eliminated. If this leaves the name short enough, we are done.
17122
17123 @item
17124 If the name is too long, the longest segment is located (left-most
17125 if there are two of equal length), and shortened by dropping
17126 its last character. This is repeated until the name is short enough.
17127
17128 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
17129 to fit the name into 8 characters as required by some operating systems.
17130
17131 @smallexample
17132 our-strings-wide_fixed 22
17133 our strings wide fixed 19
17134 our string  wide fixed 18
17135 our strin   wide fixed 17
17136 our stri    wide fixed 16
17137 our stri    wide fixe  15
17138 our str     wide fixe  14
17139 our str     wid  fixe  13
17140 our str     wid  fix   12
17141 ou  str     wid  fix   11
17142 ou  st      wid  fix   10
17143 ou  st      wi   fix   9
17144 ou  st      wi   fi    8
17145 Final file name: oustwifi.adb
17146 @end smallexample
17147
17148 @item
17149 The file names for all predefined units are always krunched to eight
17150 characters. The krunching of these predefined units uses the following
17151 special prefix replacements:
17152
17153 @table @file
17154 @item ada-
17155 replaced by @file{^a^A^-}
17156
17157 @item gnat-
17158 replaced by @file{^g^G^-}
17159
17160 @item interfaces-
17161 replaced by @file{^i^I^-}
17162
17163 @item system-
17164 replaced by @file{^s^S^-}
17165 @end table
17166
17167 These system files have a hyphen in the second character position. That
17168 is why normal user files replace such a character with a
17169 ^tilde^dollar sign^, to
17170 avoid confusion with system file names.
17171
17172 As an example of this special rule, consider
17173 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
17174
17175 @smallexample
17176 ada-strings-wide_fixed 22
17177 a-  strings wide fixed 18
17178 a-  string  wide fixed 17
17179 a-  strin   wide fixed 16
17180 a-  stri    wide fixed 15
17181 a-  stri    wide fixe  14
17182 a-  str     wide fixe  13
17183 a-  str     wid  fixe  12
17184 a-  str     wid  fix   11
17185 a-  st      wid  fix   10
17186 a-  st      wi   fix   9
17187 a-  st      wi   fi    8
17188 Final file name: a-stwifi.adb
17189 @end smallexample
17190 @end itemize
17191
17192 Of course no file shortening algorithm can guarantee uniqueness over all
17193 possible unit names, and if file name krunching is used then it is your
17194 responsibility to ensure that no name clashes occur. The utility
17195 program @code{gnatkr} is supplied for conveniently determining the
17196 krunched name of a file.
17197
17198 @node Examples of gnatkr Usage
17199 @section Examples of @code{gnatkr} Usage
17200
17201 @smallexample
17202 @iftex
17203 @leftskip=0cm
17204 @end iftex
17205 @ifclear vms
17206 $ gnatkr very_long_unit_name.ads      --> velounna.ads
17207 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
17208 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
17209 $ gnatkr grandparent-parent-child     --> grparchi
17210 @end ifclear
17211 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
17212 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
17213 @end smallexample
17214
17215 @node Preprocessing Using gnatprep
17216 @chapter Preprocessing Using @code{gnatprep}
17217 @findex gnatprep
17218
17219 @noindent
17220 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
17221 preprocessing.
17222 Although designed for use with GNAT, @code{gnatprep} does not depend on any
17223 special GNAT features.
17224 For further discussion of conditional compilation in general, see
17225 @ref{Conditional Compilation}.
17226
17227 @menu
17228 * Using gnatprep::
17229 * Switches for gnatprep::
17230 * Form of Definitions File::
17231 * Form of Input Text for gnatprep::
17232 @end menu
17233
17234
17235 @node Using gnatprep
17236 @section Using @code{gnatprep}
17237
17238 @noindent
17239 To call @code{gnatprep} use
17240
17241 @smallexample
17242 $ gnatprep [switches] infile outfile [deffile]
17243 @end smallexample
17244
17245 @noindent
17246 where
17247 @table @code
17248 @item switches
17249 is an optional sequence of switches as described in the next section.
17250
17251 @item infile
17252 is the full name of the input file, which is an Ada source
17253 file containing preprocessor directives.
17254
17255 @item outfile
17256 is the full name of the output file, which is an Ada source
17257 in standard Ada form. When used with GNAT, this file name will
17258 normally have an ads or adb suffix.
17259
17260 @item deffile
17261 is the full name of a text file containing definitions of
17262 symbols to be referenced by the preprocessor. This argument is
17263 optional, and can be replaced by the use of the @option{-D} switch.
17264
17265 @end table
17266
17267 @node Switches for gnatprep
17268 @section Switches for @code{gnatprep}
17269
17270 @table @option
17271 @c !sort!
17272
17273 @item ^-b^/BLANK_LINES^
17274 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
17275 Causes both preprocessor lines and the lines deleted by
17276 preprocessing to be replaced by blank lines in the output source file,
17277 preserving line numbers in the output file.
17278
17279 @item ^-c^/COMMENTS^
17280 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
17281 Causes both preprocessor lines and the lines deleted
17282 by preprocessing to be retained in the output source as comments marked
17283 with the special string @code{"--! "}. This option will result in line numbers
17284 being preserved in the output file.
17285
17286 @item ^-C^/REPLACE_IN_COMMENTS^
17287 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
17288 Causes comments to be scanned. Normally comments are ignored by gnatprep.
17289 If this option is specified, then comments are scanned and any $symbol
17290 substitutions performed as in program text. This is particularly useful
17291 when structured comments are used (e.g. when writing programs in the
17292 SPARK dialect of Ada). Note that this switch is not available when
17293 doing integrated preprocessing (it would be useless in this context
17294 since comments are ignored by the compiler in any case).
17295
17296 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
17297 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
17298 Defines a new symbol, associated with value. If no value is given on the
17299 command line, then symbol is considered to be @code{True}. This switch
17300 can be used in place of a definition file.
17301
17302 @ifset vms
17303 @item /REMOVE
17304 @cindex @option{/REMOVE} (@command{gnatprep})
17305 This is the default setting which causes lines deleted by preprocessing
17306 to be entirely removed from the output file.
17307 @end ifset
17308
17309 @item ^-r^/REFERENCE^
17310 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
17311 Causes a @code{Source_Reference} pragma to be generated that
17312 references the original input file, so that error messages will use
17313 the file name of this original file. The use of this switch implies
17314 that preprocessor lines are not to be removed from the file, so its
17315 use will force @option{^-b^/BLANK_LINES^} mode if
17316 @option{^-c^/COMMENTS^}
17317 has not been specified explicitly.
17318
17319 Note that if the file to be preprocessed contains multiple units, then
17320 it will be necessary to @code{gnatchop} the output file from
17321 @code{gnatprep}. If a @code{Source_Reference} pragma is present
17322 in the preprocessed file, it will be respected by
17323 @code{gnatchop ^-r^/REFERENCE^}
17324 so that the final chopped files will correctly refer to the original
17325 input source file for @code{gnatprep}.
17326
17327 @item ^-s^/SYMBOLS^
17328 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
17329 Causes a sorted list of symbol names and values to be
17330 listed on the standard output file.
17331
17332 @item ^-u^/UNDEFINED^
17333 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
17334 Causes undefined symbols to be treated as having the value FALSE in the context
17335 of a preprocessor test. In the absence of this option, an undefined symbol in
17336 a @code{#if} or @code{#elsif} test will be treated as an error.
17337
17338 @end table
17339
17340 @ifclear vms
17341 @noindent
17342 Note: if neither @option{-b} nor @option{-c} is present,
17343 then preprocessor lines and
17344 deleted lines are completely removed from the output, unless -r is
17345 specified, in which case -b is assumed.
17346 @end ifclear
17347
17348 @node Form of Definitions File
17349 @section Form of Definitions File
17350
17351 @noindent
17352 The definitions file contains lines of the form
17353
17354 @smallexample
17355 symbol := value
17356 @end smallexample
17357
17358 @noindent
17359 where symbol is an identifier, following normal Ada (case-insensitive)
17360 rules for its syntax, and value is one of the following:
17361
17362 @itemize @bullet
17363 @item
17364 Empty, corresponding to a null substitution
17365 @item
17366 A string literal using normal Ada syntax
17367 @item
17368 Any sequence of characters from the set
17369 (letters, digits, period, underline).
17370 @end itemize
17371
17372 @noindent
17373 Comment lines may also appear in the definitions file, starting with
17374 the usual @code{--},
17375 and comments may be added to the definitions lines.
17376
17377 @node Form of Input Text for gnatprep
17378 @section Form of Input Text for @code{gnatprep}
17379
17380 @noindent
17381 The input text may contain preprocessor conditional inclusion lines,
17382 as well as general symbol substitution sequences.
17383
17384 The preprocessor conditional inclusion commands have the form
17385
17386 @smallexample
17387 @group
17388 @cartouche
17389 #if @i{expression} [then]
17390    lines
17391 #elsif @i{expression} [then]
17392    lines
17393 #elsif @i{expression} [then]
17394    lines
17395 ...
17396 #else
17397    lines
17398 #end if;
17399 @end cartouche
17400 @end group
17401 @end smallexample
17402
17403 @noindent
17404 In this example, @i{expression} is defined by the following grammar:
17405 @smallexample
17406 @i{expression} ::=  <symbol>
17407 @i{expression} ::=  <symbol> = "<value>"
17408 @i{expression} ::=  <symbol> = <symbol>
17409 @i{expression} ::=  <symbol> 'Defined
17410 @i{expression} ::=  not @i{expression}
17411 @i{expression} ::=  @i{expression} and @i{expression}
17412 @i{expression} ::=  @i{expression} or @i{expression}
17413 @i{expression} ::=  @i{expression} and then @i{expression}
17414 @i{expression} ::=  @i{expression} or else @i{expression}
17415 @i{expression} ::=  ( @i{expression} )
17416 @end smallexample
17417
17418 @noindent
17419 For the first test (@i{expression} ::= <symbol>) the symbol must have
17420 either the value true or false, that is to say the right-hand of the
17421 symbol definition must be one of the (case-insensitive) literals
17422 @code{True} or @code{False}. If the value is true, then the
17423 corresponding lines are included, and if the value is false, they are
17424 excluded.
17425
17426 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
17427 the symbol has been defined in the definition file or by a @option{-D}
17428 switch on the command line. Otherwise, the test is false.
17429
17430 The equality tests are case insensitive, as are all the preprocessor lines.
17431
17432 If the symbol referenced is not defined in the symbol definitions file,
17433 then the effect depends on whether or not switch @option{-u}
17434 is specified. If so, then the symbol is treated as if it had the value
17435 false and the test fails. If this switch is not specified, then
17436 it is an error to reference an undefined symbol. It is also an error to
17437 reference a symbol that is defined with a value other than @code{True}
17438 or @code{False}.
17439
17440 The use of the @code{not} operator inverts the sense of this logical test.
17441 The @code{not} operator cannot be combined with the @code{or} or @code{and}
17442 operators, without parentheses. For example, "if not X or Y then" is not
17443 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
17444
17445 The @code{then} keyword is optional as shown
17446
17447 The @code{#} must be the first non-blank character on a line, but
17448 otherwise the format is free form. Spaces or tabs may appear between
17449 the @code{#} and the keyword. The keywords and the symbols are case
17450 insensitive as in normal Ada code. Comments may be used on a
17451 preprocessor line, but other than that, no other tokens may appear on a
17452 preprocessor line. Any number of @code{elsif} clauses can be present,
17453 including none at all. The @code{else} is optional, as in Ada.
17454
17455 The @code{#} marking the start of a preprocessor line must be the first
17456 non-blank character on the line, i.e. it must be preceded only by
17457 spaces or horizontal tabs.
17458
17459 Symbol substitution outside of preprocessor lines is obtained by using
17460 the sequence
17461
17462 @smallexample
17463 $symbol
17464 @end smallexample
17465
17466 @noindent
17467 anywhere within a source line, except in a comment or within a
17468 string literal. The identifier
17469 following the @code{$} must match one of the symbols defined in the symbol
17470 definition file, and the result is to substitute the value of the
17471 symbol in place of @code{$symbol} in the output file.
17472
17473 Note that although the substitution of strings within a string literal
17474 is not possible, it is possible to have a symbol whose defined value is
17475 a string literal. So instead of setting XYZ to @code{hello} and writing:
17476
17477 @smallexample
17478 Header : String := "$XYZ";
17479 @end smallexample
17480
17481 @noindent
17482 you should set XYZ to @code{"hello"} and write:
17483
17484 @smallexample
17485 Header : String := $XYZ;
17486 @end smallexample
17487
17488 @noindent
17489 and then the substitution will occur as desired.
17490
17491 @ifset vms
17492 @node The GNAT Run-Time Library Builder gnatlbr
17493 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
17494 @findex gnatlbr
17495 @cindex Library builder
17496
17497 @noindent
17498 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
17499 supplied configuration pragmas.
17500
17501 @menu
17502 * Running gnatlbr::
17503 * Switches for gnatlbr::
17504 * Examples of gnatlbr Usage::
17505 @end menu
17506
17507 @node Running gnatlbr
17508 @section Running @code{gnatlbr}
17509
17510 @noindent
17511 The @code{gnatlbr} command has the form
17512
17513 @smallexample
17514 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
17515 @end smallexample
17516
17517 @node Switches for gnatlbr
17518 @section Switches for @code{gnatlbr}
17519
17520 @noindent
17521 @code{gnatlbr} recognizes the following switches:
17522
17523 @table @option
17524 @c !sort!
17525 @item /CREATE=directory
17526 @cindex @code{/CREATE} (@code{gnatlbr})
17527      Create the new run-time library in the specified directory.
17528
17529 @item /SET=directory
17530 @cindex @code{/SET} (@code{gnatlbr})
17531      Make the library in the specified directory the current run-time
17532      library.
17533
17534 @item /DELETE=directory
17535 @cindex @code{/DELETE} (@code{gnatlbr})
17536      Delete the run-time library in the specified directory.
17537
17538 @item /CONFIG=file
17539 @cindex @code{/CONFIG} (@code{gnatlbr})
17540      With /CREATE:
17541      Use the configuration pragmas in the specified file when building
17542      the library.
17543
17544      With /SET:
17545      Use the configuration pragmas in the specified file when compiling.
17546
17547 @end table
17548
17549 @node Examples of gnatlbr Usage
17550 @section Example of @code{gnatlbr} Usage
17551
17552 @smallexample
17553 Contents of VAXFLOAT.ADC:
17554 pragma Float_Representation (VAX_Float);
17555
17556 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
17557
17558 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
17559
17560 @end smallexample
17561 @end ifset
17562
17563 @node The GNAT Library Browser gnatls
17564 @chapter The GNAT Library Browser @code{gnatls}
17565 @findex gnatls
17566 @cindex Library browser
17567
17568 @noindent
17569 @code{gnatls} is a tool that outputs information about compiled
17570 units. It gives the relationship between objects, unit names and source
17571 files. It can also be used to check the source dependencies of a unit
17572 as well as various characteristics.
17573
17574 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
17575 driver (see @ref{The GNAT Driver and Project Files}).
17576
17577 @menu
17578 * Running gnatls::
17579 * Switches for gnatls::
17580 * Examples of gnatls Usage::
17581 @end menu
17582
17583 @node Running gnatls
17584 @section Running @code{gnatls}
17585
17586 @noindent
17587 The @code{gnatls} command has the form
17588
17589 @smallexample
17590 $ gnatls switches @var{object_or_ali_file}
17591 @end smallexample
17592
17593 @noindent
17594 The main argument is the list of object or @file{ali} files
17595 (@pxref{The Ada Library Information Files})
17596 for which information is requested.
17597
17598 In normal mode, without additional option, @code{gnatls} produces a
17599 four-column listing. Each line represents information for a specific
17600 object. The first column gives the full path of the object, the second
17601 column gives the name of the principal unit in this object, the third
17602 column gives the status of the source and the fourth column gives the
17603 full path of the source representing this unit.
17604 Here is a simple example of use:
17605
17606 @smallexample
17607 $ gnatls *.o
17608 ^./^[]^demo1.o            demo1            DIF demo1.adb
17609 ^./^[]^demo2.o            demo2             OK demo2.adb
17610 ^./^[]^hello.o            h1                OK hello.adb
17611 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
17612 ^./^[]^instr.o            instr             OK instr.adb
17613 ^./^[]^tef.o              tef              DIF tef.adb
17614 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
17615 ^./^[]^tgef.o             tgef             DIF tgef.adb
17616 @end smallexample
17617
17618 @noindent
17619 The first line can be interpreted as follows: the main unit which is
17620 contained in
17621 object file @file{demo1.o} is demo1, whose main source is in
17622 @file{demo1.adb}. Furthermore, the version of the source used for the
17623 compilation of demo1 has been modified (DIF). Each source file has a status
17624 qualifier which can be:
17625
17626 @table @code
17627 @item OK (unchanged)
17628 The version of the source file used for the compilation of the
17629 specified unit corresponds exactly to the actual source file.
17630
17631 @item MOK (slightly modified)
17632 The version of the source file used for the compilation of the
17633 specified unit differs from the actual source file but not enough to
17634 require recompilation. If you use gnatmake with the qualifier
17635 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
17636 MOK will not be recompiled.
17637
17638 @item DIF (modified)
17639 No version of the source found on the path corresponds to the source
17640 used to build this object.
17641
17642 @item ??? (file not found)
17643 No source file was found for this unit.
17644
17645 @item HID (hidden,  unchanged version not first on PATH)
17646 The version of the source that corresponds exactly to the source used
17647 for compilation has been found on the path but it is hidden by another
17648 version of the same source that has been modified.
17649
17650 @end table
17651
17652 @node Switches for gnatls
17653 @section Switches for @code{gnatls}
17654
17655 @noindent
17656 @code{gnatls} recognizes the following switches:
17657
17658 @table @option
17659 @c !sort!
17660 @cindex @option{--version} @command{gnatls}
17661 Display Copyright and version, then exit disregarding all other options.
17662
17663 @item --help
17664 @cindex @option{--help} @command{gnatls}
17665 If @option{--version} was not used, display usage, then exit disregarding
17666 all other options.
17667
17668 @item ^-a^/ALL_UNITS^
17669 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
17670 Consider all units, including those of the predefined Ada library.
17671 Especially useful with @option{^-d^/DEPENDENCIES^}.
17672
17673 @item ^-d^/DEPENDENCIES^
17674 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
17675 List sources from which specified units depend on.
17676
17677 @item ^-h^/OUTPUT=OPTIONS^
17678 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
17679 Output the list of options.
17680
17681 @item ^-o^/OUTPUT=OBJECTS^
17682 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
17683 Only output information about object files.
17684
17685 @item ^-s^/OUTPUT=SOURCES^
17686 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
17687 Only output information about source files.
17688
17689 @item ^-u^/OUTPUT=UNITS^
17690 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
17691 Only output information about compilation units.
17692
17693 @item ^-files^/FILES^=@var{file}
17694 @cindex @option{^-files^/FILES^} (@code{gnatls})
17695 Take as arguments the files listed in text file @var{file}.
17696 Text file @var{file} may contain empty lines that are ignored.
17697 Each non empty line should contain the name of an existing file.
17698 Several such switches may be specified simultaneously.
17699
17700 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17701 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
17702 @itemx ^-I^/SEARCH=^@var{dir}
17703 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
17704 @itemx -nostdinc
17705 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
17706 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
17707 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
17708 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
17709 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
17710 flags (@pxref{Switches for gnatmake}).
17711
17712 @item --RTS=@var{rts-path}
17713 @cindex @option{--RTS} (@code{gnatls})
17714 Specifies the default location of the runtime library. Same meaning as the
17715 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
17716
17717 @item ^-v^/OUTPUT=VERBOSE^
17718 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
17719 Verbose mode. Output the complete source, object and project paths. Do not use
17720 the default column layout but instead use long format giving as much as
17721 information possible on each requested units, including special
17722 characteristics such as:
17723
17724 @table @code
17725 @item  Preelaborable
17726 The unit is preelaborable in the Ada sense.
17727
17728 @item No_Elab_Code
17729 No elaboration code has been produced by the compiler for this unit.
17730
17731 @item Pure
17732 The unit is pure in the Ada sense.
17733
17734 @item Elaborate_Body
17735 The unit contains a pragma Elaborate_Body.
17736
17737 @item Remote_Types
17738 The unit contains a pragma Remote_Types.
17739
17740 @item Shared_Passive
17741 The unit contains a pragma Shared_Passive.
17742
17743 @item Predefined
17744 This unit is part of the predefined environment and cannot be modified
17745 by the user.
17746
17747 @item Remote_Call_Interface
17748 The unit contains a pragma Remote_Call_Interface.
17749
17750 @end table
17751
17752 @end table
17753
17754 @node Examples of gnatls Usage
17755 @section Example of @code{gnatls} Usage
17756 @ifclear vms
17757
17758 @noindent
17759 Example of using the verbose switch. Note how the source and
17760 object paths are affected by the -I switch.
17761
17762 @smallexample
17763 $ gnatls -v -I.. demo1.o
17764
17765 GNATLS 5.03w (20041123-34)
17766 Copyright 1997-2004 Free Software Foundation, Inc.
17767
17768 Source Search Path:
17769    <Current_Directory>
17770    ../
17771    /home/comar/local/adainclude/
17772
17773 Object Search Path:
17774    <Current_Directory>
17775    ../
17776    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17777
17778 Project Search Path:
17779    <Current_Directory>
17780    /home/comar/local/lib/gnat/
17781
17782 ./demo1.o
17783    Unit =>
17784      Name   => demo1
17785      Kind   => subprogram body
17786      Flags  => No_Elab_Code
17787      Source => demo1.adb    modified
17788 @end smallexample
17789
17790 @noindent
17791 The following is an example of use of the dependency list.
17792 Note the use of the -s switch
17793 which gives a straight list of source files. This can be useful for
17794 building specialized scripts.
17795
17796 @smallexample
17797 $ gnatls -d demo2.o
17798 ./demo2.o   demo2        OK demo2.adb
17799                          OK gen_list.ads
17800                          OK gen_list.adb
17801                          OK instr.ads
17802                          OK instr-child.ads
17803
17804 $ gnatls -d -s -a demo1.o
17805 demo1.adb
17806 /home/comar/local/adainclude/ada.ads
17807 /home/comar/local/adainclude/a-finali.ads
17808 /home/comar/local/adainclude/a-filico.ads
17809 /home/comar/local/adainclude/a-stream.ads
17810 /home/comar/local/adainclude/a-tags.ads
17811 gen_list.ads
17812 gen_list.adb
17813 /home/comar/local/adainclude/gnat.ads
17814 /home/comar/local/adainclude/g-io.ads
17815 instr.ads
17816 /home/comar/local/adainclude/system.ads
17817 /home/comar/local/adainclude/s-exctab.ads
17818 /home/comar/local/adainclude/s-finimp.ads
17819 /home/comar/local/adainclude/s-finroo.ads
17820 /home/comar/local/adainclude/s-secsta.ads
17821 /home/comar/local/adainclude/s-stalib.ads
17822 /home/comar/local/adainclude/s-stoele.ads
17823 /home/comar/local/adainclude/s-stratt.ads
17824 /home/comar/local/adainclude/s-tasoli.ads
17825 /home/comar/local/adainclude/s-unstyp.ads
17826 /home/comar/local/adainclude/unchconv.ads
17827 @end smallexample
17828 @end ifclear
17829
17830 @ifset vms
17831 @smallexample
17832 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17833
17834 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17835 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17836 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17837 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17838 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17839 demo1.adb
17840 gen_list.ads
17841 gen_list.adb
17842 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17843 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17844 instr.ads
17845 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17846 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17847 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17848 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17849 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17850 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17851 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17852 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17853 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17854 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17855 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17856 @end smallexample
17857 @end ifset
17858
17859 @node Cleaning Up Using gnatclean
17860 @chapter Cleaning Up Using @code{gnatclean}
17861 @findex gnatclean
17862 @cindex Cleaning tool
17863
17864 @noindent
17865 @code{gnatclean} is a tool that allows the deletion of files produced by the
17866 compiler, binder and linker, including ALI files, object files, tree files,
17867 expanded source files, library files, interface copy source files, binder
17868 generated files and executable files.
17869
17870 @menu
17871 * Running gnatclean::
17872 * Switches for gnatclean::
17873 @c * Examples of gnatclean Usage::
17874 @end menu
17875
17876 @node Running gnatclean
17877 @section Running @code{gnatclean}
17878
17879 @noindent
17880 The @code{gnatclean} command has the form:
17881
17882 @smallexample
17883 $ gnatclean switches @var{names}
17884 @end smallexample
17885
17886 @noindent
17887 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17888 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17889 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17890
17891 @noindent
17892 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17893 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17894 the linker. In informative-only mode, specified by switch
17895 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17896 normal mode is listed, but no file is actually deleted.
17897
17898 @node Switches for gnatclean
17899 @section Switches for @code{gnatclean}
17900
17901 @noindent
17902 @code{gnatclean} recognizes the following switches:
17903
17904 @table @option
17905 @c !sort!
17906 @cindex @option{--version} @command{gnatclean}
17907 Display Copyright and version, then exit disregarding all other options.
17908
17909 @item --help
17910 @cindex @option{--help} @command{gnatclean}
17911 If @option{--version} was not used, display usage, then exit disregarding
17912 all other options.
17913
17914 @item ^-c^/COMPILER_FILES_ONLY^
17915 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17916 Only attempt to delete the files produced by the compiler, not those produced
17917 by the binder or the linker. The files that are not to be deleted are library
17918 files, interface copy files, binder generated files and executable files.
17919
17920 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17921 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17922 Indicate that ALI and object files should normally be found in directory
17923 @var{dir}.
17924
17925 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17926 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17927 When using project files, if some errors or warnings are detected during
17928 parsing and verbose mode is not in effect (no use of switch
17929 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17930 file, rather than its simple file name.
17931
17932 @item ^-h^/HELP^
17933 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17934 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17935
17936 @item ^-n^/NODELETE^
17937 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17938 Informative-only mode. Do not delete any files. Output the list of the files
17939 that would have been deleted if this switch was not specified.
17940
17941 @item ^-P^/PROJECT_FILE=^@var{project}
17942 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17943 Use project file @var{project}. Only one such switch can be used.
17944 When cleaning a project file, the files produced by the compilation of the
17945 immediate sources or inherited sources of the project files are to be
17946 deleted. This is not depending on the presence or not of executable names
17947 on the command line.
17948
17949 @item ^-q^/QUIET^
17950 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17951 Quiet output. If there are no errors, do not output anything, except in
17952 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17953 (switch ^-n^/NODELETE^).
17954
17955 @item ^-r^/RECURSIVE^
17956 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17957 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17958 clean all imported and extended project files, recursively. If this switch
17959 is not specified, only the files related to the main project file are to be
17960 deleted. This switch has no effect if no project file is specified.
17961
17962 @item ^-v^/VERBOSE^
17963 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17964 Verbose mode.
17965
17966 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17967 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17968 Indicates the verbosity of the parsing of GNAT project files.
17969 @xref{Switches Related to Project Files}.
17970
17971 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17972 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17973 Indicates that external variable @var{name} has the value @var{value}.
17974 The Project Manager will use this value for occurrences of
17975 @code{external(name)} when parsing the project file.
17976 @xref{Switches Related to Project Files}.
17977
17978 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17979 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17980 When searching for ALI and object files, look in directory
17981 @var{dir}.
17982
17983 @item ^-I^/SEARCH=^@var{dir}
17984 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17985 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17986
17987 @item ^-I-^/NOCURRENT_DIRECTORY^
17988 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17989 @cindex Source files, suppressing search
17990 Do not look for ALI or object files in the directory
17991 where @code{gnatclean} was invoked.
17992
17993 @end table
17994
17995 @c @node Examples of gnatclean Usage
17996 @c @section Examples of @code{gnatclean} Usage
17997
17998 @ifclear vms
17999 @node GNAT and Libraries
18000 @chapter GNAT and Libraries
18001 @cindex Library, building, installing, using
18002
18003 @noindent
18004 This chapter describes how to build and use libraries with GNAT, and also shows
18005 how to recompile the GNAT run-time library. You should be familiar with the
18006 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18007 chapter.
18008
18009 @menu
18010 * Introduction to Libraries in GNAT::
18011 * General Ada Libraries::
18012 * Stand-alone Ada Libraries::
18013 * Rebuilding the GNAT Run-Time Library::
18014 @end menu
18015
18016 @node Introduction to Libraries in GNAT
18017 @section Introduction to Libraries in GNAT
18018
18019 @noindent
18020 A library is, conceptually, a collection of objects which does not have its
18021 own main thread of execution, but rather provides certain services to the
18022 applications that use it. A library can be either statically linked with the
18023 application, in which case its code is directly included in the application,
18024 or, on platforms that support it, be dynamically linked, in which case
18025 its code is shared by all applications making use of this library.
18026
18027 GNAT supports both types of libraries.
18028 In the static case, the compiled code can be provided in different ways. The
18029 simplest approach is to provide directly the set of objects resulting from
18030 compilation of the library source files. Alternatively, you can group the
18031 objects into an archive using whatever commands are provided by the operating
18032 system. For the latter case, the objects are grouped into a shared library.
18033
18034 In the GNAT environment, a library has three types of components:
18035 @itemize @bullet
18036 @item
18037 Source files.
18038 @item
18039 @file{ALI} files.
18040 @xref{The Ada Library Information Files}.
18041 @item
18042 Object files, an archive or a shared library.
18043 @end itemize
18044
18045 @noindent
18046 A GNAT library may expose all its source files, which is useful for
18047 documentation purposes. Alternatively, it may expose only the units needed by
18048 an external user to make use of the library. That is to say, the specs
18049 reflecting the library services along with all the units needed to compile
18050 those specs, which can include generic bodies or any body implementing an
18051 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18052 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18053
18054 All compilation units comprising an application, including those in a library,
18055 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18056 computes the elaboration order from the @file{ALI} files and this is why they
18057 constitute a mandatory part of GNAT libraries. Except in the case of
18058 @emph{stand-alone libraries}, where a specific library elaboration routine is
18059 produced independently of the application(s) using the library.
18060
18061 @node General Ada Libraries
18062 @section General Ada Libraries
18063
18064 @menu
18065 * Building a library::
18066 * Installing a library::
18067 * Using a library::
18068 @end menu
18069
18070 @node Building a library
18071 @subsection Building a library
18072
18073 @noindent
18074 The easiest way to build a library is to use the Project Manager,
18075 which supports a special type of project called a @emph{Library Project}
18076 (@pxref{Library Projects}).
18077
18078 A project is considered a library project, when two project-level attributes
18079 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
18080 control different aspects of library configuration, additional optional
18081 project-level attributes can be specified:
18082 @table @code
18083 @item Library_Kind
18084 This attribute controls whether the library is to be static or dynamic
18085
18086 @item Library_Version
18087 This attribute specifies the library version; this value is used
18088 during dynamic linking of shared libraries to determine if the currently
18089 installed versions of the binaries are compatible.
18090
18091 @item Library_Options
18092 @item Library_GCC
18093 These attributes specify additional low-level options to be used during
18094 library generation, and redefine the actual application used to generate
18095 library.
18096 @end table
18097
18098 @noindent
18099 The GNAT Project Manager takes full care of the library maintenance task,
18100 including recompilation of the source files for which objects do not exist
18101 or are not up to date, assembly of the library archive, and installation of
18102 the library (i.e., copying associated source, object and @file{ALI} files
18103 to the specified location).
18104
18105 Here is a simple library project file:
18106 @smallexample @c ada
18107 project My_Lib is
18108    for Source_Dirs use ("src1", "src2");
18109    for Object_Dir use "obj";
18110    for Library_Name use "mylib";
18111    for Library_Dir use "lib";
18112    for Library_Kind use "dynamic";
18113 end My_lib;
18114 @end smallexample
18115
18116 @noindent
18117 and the compilation command to build and install the library:
18118
18119 @smallexample @c ada
18120   $ gnatmake -Pmy_lib
18121 @end smallexample
18122
18123 @noindent
18124 It is not entirely trivial to perform manually all the steps required to
18125 produce a library. We recommend that you use the GNAT Project Manager
18126 for this task. In special cases where this is not desired, the necessary
18127 steps are discussed below.
18128
18129 There are various possibilities for compiling the units that make up the
18130 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
18131 with a conventional script. For simple libraries, it is also possible to create
18132 a dummy main program which depends upon all the packages that comprise the
18133 interface of the library. This dummy main program can then be given to
18134 @command{gnatmake}, which will ensure that all necessary objects are built.
18135
18136 After this task is accomplished, you should follow the standard procedure
18137 of the underlying operating system to produce the static or shared library.
18138
18139 Here is an example of such a dummy program:
18140 @smallexample @c ada
18141 @group
18142 with My_Lib.Service1;
18143 with My_Lib.Service2;
18144 with My_Lib.Service3;
18145 procedure My_Lib_Dummy is
18146 begin
18147    null;
18148 end;
18149 @end group
18150 @end smallexample
18151
18152 @noindent
18153 Here are the generic commands that will build an archive or a shared library.
18154
18155 @smallexample
18156 # compiling the library
18157 $ gnatmake -c my_lib_dummy.adb
18158
18159 # we don't need the dummy object itself
18160 $ rm my_lib_dummy.o my_lib_dummy.ali
18161
18162 # create an archive with the remaining objects
18163 $ ar rc libmy_lib.a *.o
18164 # some systems may require "ranlib" to be run as well
18165
18166 # or create a shared library
18167 $ gcc -shared -o libmy_lib.so *.o
18168 # some systems may require the code to have been compiled with -fPIC
18169
18170 # remove the object files that are now in the library
18171 $ rm *.o
18172
18173 # Make the ALI files read-only so that gnatmake will not try to
18174 # regenerate the objects that are in the library
18175 $ chmod -w *.ali
18176 @end smallexample
18177
18178 @noindent
18179 Please note that the library must have a name of the form @file{libxxx.a} or
18180 @file{libxxx.so} (or @file{libxxx.dll} on Windows) in order to be accessed by
18181 the directive @option{-lxxx} at link time.
18182
18183 @node Installing a library
18184 @subsection Installing a library
18185 @cindex @code{ADA_PROJECT_PATH}
18186
18187 @noindent
18188 If you use project files, library installation is part of the library build
18189 process. Thus no further action is needed in order to make use of the
18190 libraries that are built as part of the general application build. A usable
18191 version of the library is installed in the directory specified by the
18192 @code{Library_Dir} attribute of the library project file.
18193
18194 You may want to install a library in a context different from where the library
18195 is built. This situation arises with third party suppliers, who may want
18196 to distribute a library in binary form where the user is not expected to be
18197 able to recompile the library. The simplest option in this case is to provide
18198 a project file slightly different from the one used to build the library, by
18199 using the @code{externally_built} attribute. For instance, the project
18200 file used to build the library in the previous section can be changed into the
18201 following one when the library is installed:
18202
18203 @smallexample @c projectfile
18204 project My_Lib is
18205    for Source_Dirs use ("src1", "src2");
18206    for Library_Name use "mylib";
18207    for Library_Dir use "lib";
18208    for Library_Kind use "dynamic";
18209    for Externally_Built use "true";
18210 end My_lib;
18211 @end smallexample
18212
18213 @noindent
18214 This project file assumes that the directories @file{src1},
18215 @file{src2}, and @file{lib} exist in
18216 the directory containing the project file. The @code{externally_built}
18217 attribute makes it clear to the GNAT builder that it should not attempt to
18218 recompile any of the units from this library. It allows the library provider to
18219 restrict the source set to the minimum necessary for clients to make use of the
18220 library as described in the first section of this chapter. It is the
18221 responsibility of the library provider to install the necessary sources, ALI
18222 files and libraries in the directories mentioned in the project file. For
18223 convenience, the user's library project file should be installed in a location
18224 that will be searched automatically by the GNAT
18225 builder. These are the directories referenced in the @code{ADA_PROJECT_PATH}
18226 environment variable (@pxref{Importing Projects}), and also the default GNAT
18227 library location that can be queried with @command{gnatls -v} and is usually of
18228 the form $gnat_install_root/lib/gnat.
18229
18230 When project files are not an option, it is also possible, but not recommended,
18231 to install the library so that the sources needed to use the library are on the
18232 Ada source path and the ALI files & libraries be on the Ada Object path (see
18233 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
18234 administrator can place general-purpose libraries in the default compiler
18235 paths, by specifying the libraries' location in the configuration files
18236 @file{ada_source_path} and @file{ada_object_path}. These configuration files
18237 must be located in the GNAT installation tree at the same place as the gcc spec
18238 file. The location of the gcc spec file can be determined as follows:
18239 @smallexample
18240 $ gcc -v
18241 @end smallexample
18242
18243 @noindent
18244 The configuration files mentioned above have a simple format: each line
18245 must contain one unique directory name.
18246 Those names are added to the corresponding path
18247 in their order of appearance in the file. The names can be either absolute
18248 or relative; in the latter case, they are relative to where theses files
18249 are located.
18250
18251 The files @file{ada_source_path} and @file{ada_object_path} might not be
18252 present in a
18253 GNAT installation, in which case, GNAT will look for its run-time library in
18254 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
18255 objects and @file{ALI} files). When the files exist, the compiler does not
18256 look in @file{adainclude} and @file{adalib}, and thus the
18257 @file{ada_source_path} file
18258 must contain the location for the GNAT run-time sources (which can simply
18259 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
18260 contain the location for the GNAT run-time objects (which can simply
18261 be @file{adalib}).
18262
18263 You can also specify a new default path to the run-time library at compilation
18264 time with the switch @option{--RTS=rts-path}. You can thus choose / change
18265 the run-time library you want your program to be compiled with. This switch is
18266 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
18267 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
18268
18269 It is possible to install a library before or after the standard GNAT
18270 library, by reordering the lines in the configuration files. In general, a
18271 library must be installed before the GNAT library if it redefines
18272 any part of it.
18273
18274 @node Using a library
18275 @subsection Using a library
18276
18277 @noindent Once again, the project facility greatly simplifies the use of
18278 libraries. In this context, using a library is just a matter of adding a
18279 @code{with} clause in the user project. For instance, to make use of the
18280 library @code{My_Lib} shown in examples in earlier sections, you can
18281 write:
18282
18283 @smallexample @c projectfile
18284 with "my_lib";
18285 project My_Proj is
18286   ...
18287 end My_Proj;
18288 @end smallexample
18289
18290 Even if you have a third-party, non-Ada library, you can still use GNAT's
18291 Project Manager facility to provide a wrapper for it. For example, the
18292 following project, when @code{with}ed by your main project, will link with the
18293 third-party library @file{liba.a}:
18294
18295 @smallexample @c projectfile
18296 @group
18297 project Liba is
18298    for Externally_Built use "true";
18299    for Source_Files use ();
18300    for Library_Dir use "lib";
18301    for Library_Name use "a";
18302    for Library_Kind use "static";
18303 end Liba;
18304 @end group
18305 @end smallexample
18306 This is an alternative to the use of @code{pragma Linker_Options}. It is
18307 especially interesting in the context of systems with several interdependent
18308 static libraries where finding a proper linker order is not easy and best be
18309 left to the tools having visibility over project dependence information.
18310
18311 @noindent
18312 In order to use an Ada library manually, you need to make sure that this
18313 library is on both your source and object path
18314 (see @ref{Search Paths and the Run-Time Library (RTL)}
18315 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
18316 in an archive or a shared library, you need to specify the desired
18317 library at link time.
18318
18319 For example, you can use the library @file{mylib} installed in
18320 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
18321
18322 @smallexample
18323 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
18324   -largs -lmy_lib
18325 @end smallexample
18326
18327 @noindent
18328 This can be expressed more simply:
18329 @smallexample
18330 $ gnatmake my_appl
18331 @end smallexample
18332 @noindent
18333 when the following conditions are met:
18334 @itemize @bullet
18335 @item
18336 @file{/dir/my_lib_src} has been added by the user to the environment
18337 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
18338 @file{ada_source_path}
18339 @item
18340 @file{/dir/my_lib_obj} has been added by the user to the environment
18341 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
18342 @file{ada_object_path}
18343 @item
18344 a pragma @code{Linker_Options} has been added to one of the sources.
18345 For example:
18346
18347 @smallexample @c ada
18348 pragma Linker_Options ("-lmy_lib");
18349 @end smallexample
18350 @end itemize
18351
18352 @node Stand-alone Ada Libraries
18353 @section Stand-alone Ada Libraries
18354 @cindex Stand-alone library, building, using
18355
18356 @menu
18357 * Introduction to Stand-alone Libraries::
18358 * Building a Stand-alone Library::
18359 * Creating a Stand-alone Library to be used in a non-Ada context::
18360 * Restrictions in Stand-alone Libraries::
18361 @end menu
18362
18363 @node Introduction to Stand-alone Libraries
18364 @subsection Introduction to Stand-alone Libraries
18365
18366 @noindent
18367 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
18368 necessary code to
18369 elaborate the Ada units that are included in the library. In contrast with
18370 an ordinary library, which consists of all sources, objects and @file{ALI}
18371 files of the
18372 library, a SAL may specify a restricted subset of compilation units
18373 to serve as a library interface. In this case, the fully
18374 self-sufficient set of files will normally consist of an objects
18375 archive, the sources of interface units' specs, and the @file{ALI}
18376 files of interface units.
18377 If an interface spec contains a generic unit or an inlined subprogram,
18378 the body's
18379 source must also be provided; if the units that must be provided in the source
18380 form depend on other units, the source and @file{ALI} files of those must
18381 also be provided.
18382
18383 The main purpose of a SAL is to minimize the recompilation overhead of client
18384 applications when a new version of the library is installed. Specifically,
18385 if the interface sources have not changed, client applications do not need to
18386 be recompiled. If, furthermore, a SAL is provided in the shared form and its
18387 version, controlled by @code{Library_Version} attribute, is not changed,
18388 then the clients do not need to be relinked.
18389
18390 SALs also allow the library providers to minimize the amount of library source
18391 text exposed to the clients.  Such ``information hiding'' might be useful or
18392 necessary for various reasons.
18393
18394 Stand-alone libraries are also well suited to be used in an executable whose
18395 main routine is not written in Ada.
18396
18397 @node Building a Stand-alone Library
18398 @subsection Building a Stand-alone Library
18399
18400 @noindent
18401 GNAT's Project facility provides a simple way of building and installing
18402 stand-alone libraries; see @ref{Stand-alone Library Projects}.
18403 To be a Stand-alone Library Project, in addition to the two attributes
18404 that make a project a Library Project (@code{Library_Name} and
18405 @code{Library_Dir}; see @ref{Library Projects}), the attribute
18406 @code{Library_Interface} must be defined.  For example:
18407
18408 @smallexample @c projectfile
18409 @group
18410    for Library_Dir use "lib_dir";
18411    for Library_Name use "dummy";
18412    for Library_Interface use ("int1", "int1.child");
18413 @end group
18414 @end smallexample
18415
18416 @noindent
18417 Attribute @code{Library_Interface} has a non-empty string list value,
18418 each string in the list designating a unit contained in an immediate source
18419 of the project file.
18420
18421 When a Stand-alone Library is built, first the binder is invoked to build
18422 a package whose name depends on the library name
18423 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
18424 This binder-generated package includes initialization and
18425 finalization procedures whose
18426 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
18427 in the example
18428 above). The object corresponding to this package is included in the library.
18429
18430 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
18431 calling of these procedures if a static SAL is built, or if a shared SAL
18432 is built
18433 with the project-level attribute @code{Library_Auto_Init} set to
18434 @code{"false"}.
18435
18436 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
18437 (those that are listed in attribute @code{Library_Interface}) are copied to
18438 the Library Directory. As a consequence, only the Interface Units may be
18439 imported from Ada units outside of the library. If other units are imported,
18440 the binding phase will fail.
18441
18442 The attribute @code{Library_Src_Dir} may be specified for a
18443 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
18444 single string value. Its value must be the path (absolute or relative to the
18445 project directory) of an existing directory. This directory cannot be the
18446 object directory or one of the source directories, but it can be the same as
18447 the library directory. The sources of the Interface
18448 Units of the library that are needed by an Ada client of the library will be
18449 copied to the designated directory, called the Interface Copy directory.
18450 These sources include the specs of the Interface Units, but they may also
18451 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
18452 are used, or when there is a generic unit in the spec. Before the sources
18453 are copied to the Interface Copy directory, an attempt is made to delete all
18454 files in the Interface Copy directory.
18455
18456 Building stand-alone libraries by hand is somewhat tedious, but for those
18457 occasions when it is necessary here are the steps that you need to perform:
18458 @itemize @bullet
18459 @item
18460 Compile all library sources.
18461
18462 @item
18463 Invoke the binder with the switch @option{-n} (No Ada main program),
18464 with all the @file{ALI} files of the interfaces, and
18465 with the switch @option{-L} to give specific names to the @code{init}
18466 and @code{final} procedures.  For example:
18467 @smallexample
18468   gnatbind -n int1.ali int2.ali -Lsal1
18469 @end smallexample
18470
18471 @item
18472 Compile the binder generated file:
18473 @smallexample
18474   gcc -c b~int2.adb
18475 @end smallexample
18476
18477 @item
18478 Link the dynamic library with all the necessary object files,
18479 indicating to the linker the names of the @code{init} (and possibly
18480 @code{final}) procedures for automatic initialization (and finalization).
18481 The built library should be placed in a directory different from
18482 the object directory.
18483
18484 @item
18485 Copy the @code{ALI} files of the interface to the library directory,
18486 add in this copy an indication that it is an interface to a SAL
18487 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
18488 with letter ``P'') and make the modified copy of the @file{ALI} file
18489 read-only.
18490 @end itemize
18491
18492 @noindent
18493 Using SALs is not different from using other libraries
18494 (see @ref{Using a library}).
18495
18496 @node Creating a Stand-alone Library to be used in a non-Ada context
18497 @subsection Creating a Stand-alone Library to be used in a non-Ada context
18498
18499 @noindent
18500 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
18501 a non-Ada context.
18502
18503 The only extra step required is to ensure that library interface subprograms
18504 are compatible with the main program, by means of @code{pragma Export}
18505 or @code{pragma Convention}.
18506
18507 Here is an example of simple library interface for use with C main program:
18508
18509 @smallexample @c ada
18510 package Interface is
18511
18512    procedure Do_Something;
18513    pragma Export (C, Do_Something, "do_something");
18514
18515    procedure Do_Something_Else;
18516    pragma Export (C, Do_Something_Else, "do_something_else");
18517
18518 end Interface;
18519 @end smallexample
18520
18521 @noindent
18522 On the foreign language side, you must provide a ``foreign'' view of the
18523 library interface; remember that it should contain elaboration routines in
18524 addition to interface subprograms.
18525
18526 The example below shows the content of @code{mylib_interface.h} (note
18527 that there is no rule for the naming of this file, any name can be used)
18528 @smallexample
18529 /* the library elaboration procedure */
18530 extern void mylibinit (void);
18531
18532 /* the library finalization procedure */
18533 extern void mylibfinal (void);
18534
18535 /* the interface exported by the library */
18536 extern void do_something (void);
18537 extern void do_something_else (void);
18538 @end smallexample
18539
18540 @noindent
18541 Libraries built as explained above can be used from any program, provided
18542 that the elaboration procedures (named @code{mylibinit} in the previous
18543 example) are called before the library services are used. Any number of
18544 libraries can be used simultaneously, as long as the elaboration
18545 procedure of each library is called.
18546
18547 Below is an example of a C program that uses the @code{mylib} library.
18548
18549 @smallexample
18550 #include "mylib_interface.h"
18551
18552 int
18553 main (void)
18554 @{
18555    /* First, elaborate the library before using it */
18556    mylibinit ();
18557
18558    /* Main program, using the library exported entities */
18559    do_something ();
18560    do_something_else ();
18561
18562    /* Library finalization at the end of the program */
18563    mylibfinal ();
18564    return 0;
18565 @}
18566 @end smallexample
18567
18568 @noindent
18569 Note that invoking any library finalization procedure generated by
18570 @code{gnatbind} shuts down the Ada run-time environment.
18571 Consequently, the
18572 finalization of all Ada libraries must be performed at the end of the program.
18573 No call to these libraries or to the Ada run-time library should be made
18574 after the finalization phase.
18575
18576 @node Restrictions in Stand-alone Libraries
18577 @subsection Restrictions in Stand-alone Libraries
18578
18579 @noindent
18580 The pragmas listed below should be used with caution inside libraries,
18581 as they can create incompatibilities with other Ada libraries:
18582 @itemize @bullet
18583 @item pragma @code{Locking_Policy}
18584 @item pragma @code{Queuing_Policy}
18585 @item pragma @code{Task_Dispatching_Policy}
18586 @item pragma @code{Unreserve_All_Interrupts}
18587 @end itemize
18588
18589 @noindent
18590 When using a library that contains such pragmas, the user must make sure
18591 that all libraries use the same pragmas with the same values. Otherwise,
18592 @code{Program_Error} will
18593 be raised during the elaboration of the conflicting
18594 libraries. The usage of these pragmas and its consequences for the user
18595 should therefore be well documented.
18596
18597 Similarly, the traceback in the exception occurrence mechanism should be
18598 enabled or disabled in a consistent manner across all libraries.
18599 Otherwise, Program_Error will be raised during the elaboration of the
18600 conflicting libraries.
18601
18602 If the @code{Version} or @code{Body_Version}
18603 attributes are used inside a library, then you need to
18604 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
18605 libraries, so that version identifiers can be properly computed.
18606 In practice these attributes are rarely used, so this is unlikely
18607 to be a consideration.
18608
18609 @node  Rebuilding the GNAT Run-Time Library
18610 @section Rebuilding the GNAT Run-Time Library
18611 @cindex GNAT Run-Time Library, rebuilding
18612 @cindex Building the GNAT Run-Time Library
18613 @cindex Rebuilding the GNAT Run-Time Library
18614 @cindex Run-Time Library, rebuilding
18615
18616 @noindent
18617 It may be useful to recompile the GNAT library in various contexts, the
18618 most important one being the use of partition-wide configuration pragmas
18619 such as @code{Normalize_Scalars}. A special Makefile called
18620 @code{Makefile.adalib} is provided to that effect and can be found in
18621 the directory containing the GNAT library. The location of this
18622 directory depends on the way the GNAT environment has been installed and can
18623 be determined by means of the command:
18624
18625 @smallexample
18626 $ gnatls -v
18627 @end smallexample
18628
18629 @noindent
18630 The last entry in the object search path usually contains the
18631 gnat library. This Makefile contains its own documentation and in
18632 particular the set of instructions needed to rebuild a new library and
18633 to use it.
18634
18635 @node Using the GNU make Utility
18636 @chapter Using the GNU @code{make} Utility
18637 @findex make
18638
18639 @noindent
18640 This chapter offers some examples of makefiles that solve specific
18641 problems. It does not explain how to write a makefile (see the GNU make
18642 documentation), nor does it try to replace the @command{gnatmake} utility
18643 (@pxref{The GNAT Make Program gnatmake}).
18644
18645 All the examples in this section are specific to the GNU version of
18646 make. Although @code{make} is a standard utility, and the basic language
18647 is the same, these examples use some advanced features found only in
18648 @code{GNU make}.
18649
18650 @menu
18651 * Using gnatmake in a Makefile::
18652 * Automatically Creating a List of Directories::
18653 * Generating the Command Line Switches::
18654 * Overcoming Command Line Length Limits::
18655 @end menu
18656
18657 @node Using gnatmake in a Makefile
18658 @section Using gnatmake in a Makefile
18659 @findex makefile
18660 @cindex GNU make
18661
18662 @noindent
18663 Complex project organizations can be handled in a very powerful way by
18664 using GNU make combined with gnatmake. For instance, here is a Makefile
18665 which allows you to build each subsystem of a big project into a separate
18666 shared library. Such a makefile allows you to significantly reduce the link
18667 time of very big applications while maintaining full coherence at
18668 each step of the build process.
18669
18670 The list of dependencies are handled automatically by
18671 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
18672 the appropriate directories.
18673
18674 Note that you should also read the example on how to automatically
18675 create the list of directories
18676 (@pxref{Automatically Creating a List of Directories})
18677 which might help you in case your project has a lot of subdirectories.
18678
18679 @smallexample
18680 @iftex
18681 @leftskip=0cm
18682 @font@heightrm=cmr8
18683 @heightrm
18684 @end iftex
18685 ## This Makefile is intended to be used with the following directory
18686 ## configuration:
18687 ##  - The sources are split into a series of csc (computer software components)
18688 ##    Each of these csc is put in its own directory.
18689 ##    Their name are referenced by the directory names.
18690 ##    They will be compiled into shared library (although this would also work
18691 ##    with static libraries
18692 ##  - The main program (and possibly other packages that do not belong to any
18693 ##    csc is put in the top level directory (where the Makefile is).
18694 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
18695 ##                    \_ second_csc (sources) __ lib (will contain the library)
18696 ##                    \_ ...
18697 ## Although this Makefile is build for shared library, it is easy to modify
18698 ## to build partial link objects instead (modify the lines with -shared and
18699 ## gnatlink below)
18700 ##
18701 ## With this makefile, you can change any file in the system or add any new
18702 ## file, and everything will be recompiled correctly (only the relevant shared
18703 ## objects will be recompiled, and the main program will be re-linked).
18704
18705 # The list of computer software component for your project. This might be
18706 # generated automatically.
18707 CSC_LIST=aa bb cc
18708
18709 # Name of the main program (no extension)
18710 MAIN=main
18711
18712 # If we need to build objects with -fPIC, uncomment the following line
18713 #NEED_FPIC=-fPIC
18714
18715 # The following variable should give the directory containing libgnat.so
18716 # You can get this directory through 'gnatls -v'. This is usually the last
18717 # directory in the Object_Path.
18718 GLIB=...
18719
18720 # The directories for the libraries
18721 # (This macro expands the list of CSC to the list of shared libraries, you
18722 # could simply use the expanded form :
18723 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
18724 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
18725
18726 $@{MAIN@}: objects $@{LIB_DIR@}
18727     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
18728     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
18729
18730 objects::
18731     # recompile the sources
18732     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
18733
18734 # Note: In a future version of GNAT, the following commands will be simplified
18735 # by a new tool, gnatmlib
18736 $@{LIB_DIR@}:
18737     mkdir -p $@{dir $@@ @}
18738     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
18739     cd $@{dir $@@ @}; cp -f ../*.ali .
18740
18741 # The dependencies for the modules
18742 # Note that we have to force the expansion of *.o, since in some cases
18743 # make won't be able to do it itself.
18744 aa/lib/libaa.so: $@{wildcard aa/*.o@}
18745 bb/lib/libbb.so: $@{wildcard bb/*.o@}
18746 cc/lib/libcc.so: $@{wildcard cc/*.o@}
18747
18748 # Make sure all of the shared libraries are in the path before starting the
18749 # program
18750 run::
18751     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
18752
18753 clean::
18754     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
18755     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
18756     $@{RM@} $@{CSC_LIST:%=%/*.o@}
18757     $@{RM@} *.o *.ali $@{MAIN@}
18758 @end smallexample
18759
18760 @node Automatically Creating a List of Directories
18761 @section Automatically Creating a List of Directories
18762
18763 @noindent
18764 In most makefiles, you will have to specify a list of directories, and
18765 store it in a variable. For small projects, it is often easier to
18766 specify each of them by hand, since you then have full control over what
18767 is the proper order for these directories, which ones should be
18768 included...
18769
18770 However, in larger projects, which might involve hundreds of
18771 subdirectories, it might be more convenient to generate this list
18772 automatically.
18773
18774 The example below presents two methods. The first one, although less
18775 general, gives you more control over the list. It involves wildcard
18776 characters, that are automatically expanded by @code{make}. Its
18777 shortcoming is that you need to explicitly specify some of the
18778 organization of your project, such as for instance the directory tree
18779 depth, whether some directories are found in a separate tree,...
18780
18781 The second method is the most general one. It requires an external
18782 program, called @code{find}, which is standard on all Unix systems. All
18783 the directories found under a given root directory will be added to the
18784 list.
18785
18786 @smallexample
18787 @iftex
18788 @leftskip=0cm
18789 @font@heightrm=cmr8
18790 @heightrm
18791 @end iftex
18792 # The examples below are based on the following directory hierarchy:
18793 # All the directories can contain any number of files
18794 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
18795 #                       ->  ab
18796 #                       ->  ac
18797 #                ->  b  ->  ba  ->  baa
18798 #                       ->  bb
18799 #                       ->  bc
18800 # This Makefile creates a variable called DIRS, that can be reused any time
18801 # you need this list (see the other examples in this section)
18802
18803 # The root of your project's directory hierarchy
18804 ROOT_DIRECTORY=.
18805
18806 ####
18807 # First method: specify explicitly the list of directories
18808 # This allows you to specify any subset of all the directories you need.
18809 ####
18810
18811 DIRS := a/aa/ a/ab/ b/ba/
18812
18813 ####
18814 # Second method: use wildcards
18815 # Note that the argument(s) to wildcard below should end with a '/'.
18816 # Since wildcards also return file names, we have to filter them out
18817 # to avoid duplicate directory names.
18818 # We thus use make's @code{dir} and @code{sort} functions.
18819 # It sets DIRs to the following value (note that the directories aaa and baa
18820 # are not given, unless you change the arguments to wildcard).
18821 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18822 ####
18823
18824 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18825                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18826
18827 ####
18828 # Third method: use an external program
18829 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18830 # This is the most complete command: it sets DIRs to the following value:
18831 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18832 ####
18833
18834 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18835
18836 @end smallexample
18837
18838 @node Generating the Command Line Switches
18839 @section Generating the Command Line Switches
18840
18841 @noindent
18842 Once you have created the list of directories as explained in the
18843 previous section (@pxref{Automatically Creating a List of Directories}),
18844 you can easily generate the command line arguments to pass to gnatmake.
18845
18846 For the sake of completeness, this example assumes that the source path
18847 is not the same as the object path, and that you have two separate lists
18848 of directories.
18849
18850 @smallexample
18851 # see "Automatically creating a list of directories" to create
18852 # these variables
18853 SOURCE_DIRS=
18854 OBJECT_DIRS=
18855
18856 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18857 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18858
18859 all:
18860         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18861 @end smallexample
18862
18863 @node Overcoming Command Line Length Limits
18864 @section Overcoming Command Line Length Limits
18865
18866 @noindent
18867 One problem that might be encountered on big projects is that many
18868 operating systems limit the length of the command line. It is thus hard to give
18869 gnatmake the list of source and object directories.
18870
18871 This example shows how you can set up environment variables, which will
18872 make @command{gnatmake} behave exactly as if the directories had been
18873 specified on the command line, but have a much higher length limit (or
18874 even none on most systems).
18875
18876 It assumes that you have created a list of directories in your Makefile,
18877 using one of the methods presented in
18878 @ref{Automatically Creating a List of Directories}.
18879 For the sake of completeness, we assume that the object
18880 path (where the ALI files are found) is different from the sources patch.
18881
18882 Note a small trick in the Makefile below: for efficiency reasons, we
18883 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18884 expanded immediately by @code{make}. This way we overcome the standard
18885 make behavior which is to expand the variables only when they are
18886 actually used.
18887
18888 On Windows, if you are using the standard Windows command shell, you must
18889 replace colons with semicolons in the assignments to these variables.
18890
18891 @smallexample
18892 @iftex
18893 @leftskip=0cm
18894 @font@heightrm=cmr8
18895 @heightrm
18896 @end iftex
18897 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
18898 # This is the same thing as putting the -I arguments on the command line.
18899 # (the equivalent of using -aI on the command line would be to define
18900 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
18901 # You can of course have different values for these variables.
18902 #
18903 # Note also that we need to keep the previous values of these variables, since
18904 # they might have been set before running 'make' to specify where the GNAT
18905 # library is installed.
18906
18907 # see "Automatically creating a list of directories" to create these
18908 # variables
18909 SOURCE_DIRS=
18910 OBJECT_DIRS=
18911
18912 empty:=
18913 space:=$@{empty@} $@{empty@}
18914 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18915 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18916 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18917 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
18918 export ADA_INCLUDE_PATH
18919 export ADA_OBJECT_PATH
18920
18921 all:
18922         gnatmake main_unit
18923 @end smallexample
18924 @end ifclear
18925
18926 @node Memory Management Issues
18927 @chapter Memory Management Issues
18928
18929 @noindent
18930 This chapter describes some useful memory pools provided in the GNAT library
18931 and in particular the GNAT Debug Pool facility, which can be used to detect
18932 incorrect uses of access values (including ``dangling references'').
18933 @ifclear vms
18934 It also describes the @command{gnatmem} tool, which can be used to track down
18935 ``memory leaks''.
18936 @end ifclear
18937
18938 @menu
18939 * Some Useful Memory Pools::
18940 * The GNAT Debug Pool Facility::
18941 @ifclear vms
18942 * The gnatmem Tool::
18943 @end ifclear
18944 @end menu
18945
18946 @node Some Useful Memory Pools
18947 @section Some Useful Memory Pools
18948 @findex Memory Pool
18949 @cindex storage, pool
18950
18951 @noindent
18952 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18953 storage pool. Allocations use the standard system call @code{malloc} while
18954 deallocations use the standard system call @code{free}. No reclamation is
18955 performed when the pool goes out of scope. For performance reasons, the
18956 standard default Ada allocators/deallocators do not use any explicit storage
18957 pools but if they did, they could use this storage pool without any change in
18958 behavior. That is why this storage pool is used  when the user
18959 manages to make the default implicit allocator explicit as in this example:
18960 @smallexample @c ada
18961    type T1 is access Something;
18962     -- no Storage pool is defined for T2
18963    type T2 is access Something_Else;
18964    for T2'Storage_Pool use T1'Storage_Pool;
18965    -- the above is equivalent to
18966    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18967 @end smallexample
18968
18969 @noindent
18970 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18971 pool. The allocation strategy is similar to @code{Pool_Local}'s
18972 except that the all
18973 storage allocated with this pool is reclaimed when the pool object goes out of
18974 scope. This pool provides a explicit mechanism similar to the implicit one
18975 provided by several Ada 83 compilers for allocations performed through a local
18976 access type and whose purpose was to reclaim memory when exiting the
18977 scope of a given local access. As an example, the following program does not
18978 leak memory even though it does not perform explicit deallocation:
18979
18980 @smallexample @c ada
18981 with System.Pool_Local;
18982 procedure Pooloc1 is
18983    procedure Internal is
18984       type A is access Integer;
18985       X : System.Pool_Local.Unbounded_Reclaim_Pool;
18986       for A'Storage_Pool use X;
18987       v : A;
18988    begin
18989       for I in  1 .. 50 loop
18990          v := new Integer;
18991       end loop;
18992    end Internal;
18993 begin
18994    for I in  1 .. 100 loop
18995       Internal;
18996    end loop;
18997 end Pooloc1;
18998 @end smallexample
18999
19000 @noindent
19001 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19002 @code{Storage_Size} is specified for an access type.
19003 The whole storage for the pool is
19004 allocated at once, usually on the stack at the point where the access type is
19005 elaborated. It is automatically reclaimed when exiting the scope where the
19006 access type is defined. This package is not intended to be used directly by the
19007 user and it is implicitly used for each such declaration:
19008
19009 @smallexample @c ada
19010    type T1 is access Something;
19011    for T1'Storage_Size use 10_000;
19012 @end smallexample
19013
19014 @node The GNAT Debug Pool Facility
19015 @section The GNAT Debug Pool Facility
19016 @findex Debug Pool
19017 @cindex storage, pool, memory corruption
19018
19019 @noindent
19020 The use of unchecked deallocation and unchecked conversion can easily
19021 lead to incorrect memory references. The problems generated by such
19022 references are usually difficult to tackle because the symptoms can be
19023 very remote from the origin of the problem. In such cases, it is
19024 very helpful to detect the problem as early as possible. This is the
19025 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19026
19027 In order to use the GNAT specific debugging pool, the user must
19028 associate a debug pool object with each of the access types that may be
19029 related to suspected memory problems. See Ada Reference Manual 13.11.
19030 @smallexample @c ada
19031 type Ptr is access Some_Type;
19032 Pool : GNAT.Debug_Pools.Debug_Pool;
19033 for Ptr'Storage_Pool use Pool;
19034 @end smallexample
19035
19036 @noindent
19037 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19038 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19039 allow the user to redefine allocation and deallocation strategies. They
19040 also provide a checkpoint for each dereference, through the use of
19041 the primitive operation @code{Dereference} which is implicitly called at
19042 each dereference of an access value.
19043
19044 Once an access type has been associated with a debug pool, operations on
19045 values of the type may raise four distinct exceptions,
19046 which correspond to four potential kinds of memory corruption:
19047 @itemize @bullet
19048 @item
19049 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19050 @item
19051 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19052 @item
19053 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19054 @item
19055 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19056 @end itemize
19057
19058 @noindent
19059 For types associated with a Debug_Pool, dynamic allocation is performed using
19060 the standard GNAT allocation routine. References to all allocated chunks of
19061 memory are kept in an internal dictionary. Several deallocation strategies are
19062 provided, whereupon the user can choose to release the memory to the system,
19063 keep it allocated for further invalid access checks, or fill it with an easily
19064 recognizable pattern for debug sessions. The memory pattern is the old IBM
19065 hexadecimal convention: @code{16#DEADBEEF#}.
19066
19067 See the documentation in the file g-debpoo.ads for more information on the
19068 various strategies.
19069
19070 Upon each dereference, a check is made that the access value denotes a
19071 properly allocated memory location. Here is a complete example of use of
19072 @code{Debug_Pools}, that includes typical instances of  memory corruption:
19073 @smallexample @c ada
19074 @iftex
19075 @leftskip=0cm
19076 @end iftex
19077 with Gnat.Io; use Gnat.Io;
19078 with Unchecked_Deallocation;
19079 with Unchecked_Conversion;
19080 with GNAT.Debug_Pools;
19081 with System.Storage_Elements;
19082 with Ada.Exceptions; use Ada.Exceptions;
19083 procedure Debug_Pool_Test is
19084
19085    type T is access Integer;
19086    type U is access all T;
19087
19088    P : GNAT.Debug_Pools.Debug_Pool;
19089    for T'Storage_Pool use P;
19090
19091    procedure Free is new Unchecked_Deallocation (Integer, T);
19092    function UC is new Unchecked_Conversion (U, T);
19093    A, B : aliased T;
19094
19095    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
19096
19097 begin
19098    Info (P);
19099    A := new Integer;
19100    B := new Integer;
19101    B := A;
19102    Info (P);
19103    Free (A);
19104    begin
19105       Put_Line (Integer'Image(B.all));
19106    exception
19107       when E : others => Put_Line ("raised: " & Exception_Name (E));
19108    end;
19109    begin
19110       Free (B);
19111    exception
19112       when E : others => Put_Line ("raised: " & Exception_Name (E));
19113    end;
19114    B := UC(A'Access);
19115    begin
19116       Put_Line (Integer'Image(B.all));
19117    exception
19118       when E : others => Put_Line ("raised: " & Exception_Name (E));
19119    end;
19120    begin
19121       Free (B);
19122    exception
19123       when E : others => Put_Line ("raised: " & Exception_Name (E));
19124    end;
19125    Info (P);
19126 end Debug_Pool_Test;
19127 @end smallexample
19128
19129 @noindent
19130 The debug pool mechanism provides the following precise diagnostics on the
19131 execution of this erroneous program:
19132 @smallexample
19133 Debug Pool info:
19134   Total allocated bytes :  0
19135   Total deallocated bytes :  0
19136   Current Water Mark:  0
19137   High Water Mark:  0
19138
19139 Debug Pool info:
19140   Total allocated bytes :  8
19141   Total deallocated bytes :  0
19142   Current Water Mark:  8
19143   High Water Mark:  8
19144
19145 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
19146 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
19147 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
19148 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
19149 Debug Pool info:
19150   Total allocated bytes :  8
19151   Total deallocated bytes :  4
19152   Current Water Mark:  4
19153   High Water Mark:  8
19154 @end smallexample
19155
19156 @ifclear vms
19157 @node The gnatmem Tool
19158 @section The @command{gnatmem} Tool
19159 @findex gnatmem
19160
19161 @noindent
19162 The @code{gnatmem} utility monitors dynamic allocation and
19163 deallocation activity in a program, and displays information about
19164 incorrect deallocations and possible sources of memory leaks.
19165 It provides three type of information:
19166 @itemize @bullet
19167 @item
19168 General information concerning memory management, such as the total
19169 number of allocations and deallocations, the amount of allocated
19170 memory and the high water mark, i.e. the largest amount of allocated
19171 memory in the course of program execution.
19172
19173 @item
19174 Backtraces for all incorrect deallocations, that is to say deallocations
19175 which do not correspond to a valid allocation.
19176
19177 @item
19178 Information on each allocation that is potentially the origin of a memory
19179 leak.
19180 @end itemize
19181
19182 @menu
19183 * Running gnatmem::
19184 * Switches for gnatmem::
19185 * Example of gnatmem Usage::
19186 @end menu
19187
19188 @node Running gnatmem
19189 @subsection Running @code{gnatmem}
19190
19191 @noindent
19192 @code{gnatmem} makes use of the output created by the special version of
19193 allocation and deallocation routines that record call information. This
19194 allows to obtain accurate dynamic memory usage history at a minimal cost to
19195 the execution speed. Note however, that @code{gnatmem} is not supported on
19196 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
19197 Solaris and Windows NT/2000/XP (x86).
19198
19199 @noindent
19200 The @code{gnatmem} command has the form
19201
19202 @smallexample
19203    $ gnatmem [switches] user_program
19204 @end smallexample
19205
19206 @noindent
19207 The program must have been linked with the instrumented version of the
19208 allocation and deallocation routines. This is done by linking with the
19209 @file{libgmem.a} library. For correct symbolic backtrace information,
19210 the user program should be compiled with debugging options
19211 (see @ref{Switches for gcc}). For example to build @file{my_program}:
19212
19213 @smallexample
19214 $ gnatmake -g my_program -largs -lgmem
19215 @end smallexample
19216
19217 @noindent
19218 As library @file{libgmem.a} contains an alternate body for package
19219 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
19220 when an executable is linked with library @file{libgmem.a}. It is then not
19221 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
19222
19223 @noindent
19224 When @file{my_program} is executed, the file @file{gmem.out} is produced.
19225 This file contains information about all allocations and deallocations
19226 performed by the program. It is produced by the instrumented allocations and
19227 deallocations routines and will be used by @code{gnatmem}.
19228
19229 In order to produce symbolic backtrace information for allocations and
19230 deallocations performed by the GNAT run-time library, you need to use a
19231 version of that library that has been compiled with the @option{-g} switch
19232 (see @ref{Rebuilding the GNAT Run-Time Library}).
19233
19234 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
19235 examine. If the location of @file{gmem.out} file was not explicitly supplied by
19236 @code{-i} switch, gnatmem will assume that this file can be found in the
19237 current directory. For example, after you have executed @file{my_program},
19238 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
19239
19240 @smallexample
19241 $ gnatmem my_program
19242 @end smallexample
19243
19244 @noindent
19245 This will produce the output with the following format:
19246
19247 *************** debut cc
19248 @smallexample
19249 $ gnatmem my_program
19250
19251 Global information
19252 ------------------
19253    Total number of allocations        :  45
19254    Total number of deallocations      :   6
19255    Final Water Mark (non freed mem)   :  11.29 Kilobytes
19256    High Water Mark                    :  11.40 Kilobytes
19257
19258 .
19259 .
19260 .
19261 Allocation Root # 2
19262 -------------------
19263  Number of non freed allocations    :  11
19264  Final Water Mark (non freed mem)   :   1.16 Kilobytes
19265  High Water Mark                    :   1.27 Kilobytes
19266  Backtrace                          :
19267    my_program.adb:23 my_program.alloc
19268 .
19269 .
19270 .
19271 @end smallexample
19272
19273 The first block of output gives general information. In this case, the
19274 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
19275 Unchecked_Deallocation routine occurred.
19276
19277 @noindent
19278 Subsequent paragraphs display  information on all allocation roots.
19279 An allocation root is a specific point in the execution of the program
19280 that generates some dynamic allocation, such as a ``@code{@b{new}}''
19281 construct. This root is represented by an execution backtrace (or subprogram
19282 call stack). By default the backtrace depth for allocations roots is 1, so
19283 that a root corresponds exactly to a source location. The backtrace can
19284 be made deeper, to make the root more specific.
19285
19286 @node Switches for gnatmem
19287 @subsection Switches for @code{gnatmem}
19288
19289 @noindent
19290 @code{gnatmem} recognizes the following switches:
19291
19292 @table @option
19293
19294 @item -q
19295 @cindex @option{-q} (@code{gnatmem})
19296 Quiet. Gives the minimum output needed to identify the origin of the
19297 memory leaks. Omits statistical information.
19298
19299 @item @var{N}
19300 @cindex @var{N} (@code{gnatmem})
19301 N is an integer literal (usually between 1 and 10) which controls the
19302 depth of the backtraces defining allocation root. The default value for
19303 N is 1. The deeper the backtrace, the more precise the localization of
19304 the root. Note that the total number of roots can depend on this
19305 parameter. This parameter must be specified @emph{before} the name of the
19306 executable to be analyzed, to avoid ambiguity.
19307
19308 @item -b n
19309 @cindex @option{-b} (@code{gnatmem})
19310 This switch has the same effect as just depth parameter.
19311
19312 @item -i @var{file}
19313 @cindex @option{-i} (@code{gnatmem})
19314 Do the @code{gnatmem} processing starting from @file{file}, rather than
19315 @file{gmem.out} in the current directory.
19316
19317 @item -m n
19318 @cindex @option{-m} (@code{gnatmem})
19319 This switch causes @code{gnatmem} to mask the allocation roots that have less
19320 than n leaks. The default value is 1. Specifying the value of 0 will allow to
19321 examine even the roots that didn't result in leaks.
19322
19323 @item -s order
19324 @cindex @option{-s} (@code{gnatmem})
19325 This switch causes @code{gnatmem} to sort the allocation roots according to the
19326 specified order of sort criteria, each identified by a single letter. The
19327 currently supported criteria are @code{n, h, w} standing respectively for
19328 number of unfreed allocations, high watermark, and final watermark
19329 corresponding to a specific root. The default order is @code{nwh}.
19330
19331 @end table
19332
19333 @node Example of gnatmem Usage
19334 @subsection Example of @code{gnatmem} Usage
19335
19336 @noindent
19337 The following example shows the use of @code{gnatmem}
19338 on a simple memory-leaking program.
19339 Suppose that we have the following Ada program:
19340
19341 @smallexample @c ada
19342 @group
19343 @cartouche
19344 with Unchecked_Deallocation;
19345 procedure Test_Gm is
19346
19347    type T is array (1..1000) of Integer;
19348    type Ptr is access T;
19349    procedure Free is new Unchecked_Deallocation (T, Ptr);
19350    A : Ptr;
19351
19352    procedure My_Alloc is
19353    begin
19354       A := new T;
19355    end My_Alloc;
19356
19357    procedure My_DeAlloc is
19358       B : Ptr := A;
19359    begin
19360       Free (B);
19361    end My_DeAlloc;
19362
19363 begin
19364    My_Alloc;
19365    for I in 1 .. 5 loop
19366       for J in I .. 5 loop
19367          My_Alloc;
19368       end loop;
19369       My_Dealloc;
19370    end loop;
19371 end;
19372 @end cartouche
19373 @end group
19374 @end smallexample
19375
19376 @noindent
19377 The program needs to be compiled with debugging option and linked with
19378 @code{gmem} library:
19379
19380 @smallexample
19381 $ gnatmake -g test_gm -largs -lgmem
19382 @end smallexample
19383
19384 @noindent
19385 Then we execute the program as usual:
19386
19387 @smallexample
19388 $ test_gm
19389 @end smallexample
19390
19391 @noindent
19392 Then @code{gnatmem} is invoked simply with
19393 @smallexample
19394 $ gnatmem test_gm
19395 @end smallexample
19396
19397 @noindent
19398 which produces the following output (result may vary on different platforms):
19399
19400 @smallexample
19401 Global information
19402 ------------------
19403    Total number of allocations        :  18
19404    Total number of deallocations      :   5
19405    Final Water Mark (non freed mem)   :  53.00 Kilobytes
19406    High Water Mark                    :  56.90 Kilobytes
19407
19408 Allocation Root # 1
19409 -------------------
19410  Number of non freed allocations    :  11
19411  Final Water Mark (non freed mem)   :  42.97 Kilobytes
19412  High Water Mark                    :  46.88 Kilobytes
19413  Backtrace                          :
19414    test_gm.adb:11 test_gm.my_alloc
19415
19416 Allocation Root # 2
19417 -------------------
19418  Number of non freed allocations    :   1
19419  Final Water Mark (non freed mem)   :  10.02 Kilobytes
19420  High Water Mark                    :  10.02 Kilobytes
19421  Backtrace                          :
19422    s-secsta.adb:81 system.secondary_stack.ss_init
19423
19424 Allocation Root # 3
19425 -------------------
19426  Number of non freed allocations    :   1
19427  Final Water Mark (non freed mem)   :  12 Bytes
19428  High Water Mark                    :  12 Bytes
19429  Backtrace                          :
19430    s-secsta.adb:181 system.secondary_stack.ss_init
19431 @end smallexample
19432
19433 @noindent
19434 Note that the GNAT run time contains itself a certain number of
19435 allocations that have no  corresponding deallocation,
19436 as shown here for root #2 and root
19437 #3. This is a normal behavior when the number of non freed allocations
19438 is one, it allocates dynamic data structures that the run time needs for
19439 the complete lifetime of the program. Note also that there is only one
19440 allocation root in the user program with a single line back trace:
19441 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
19442 program shows that 'My_Alloc' is called at 2 different points in the
19443 source (line 21 and line 24). If those two allocation roots need to be
19444 distinguished, the backtrace depth parameter can be used:
19445
19446 @smallexample
19447 $ gnatmem 3 test_gm
19448 @end smallexample
19449
19450 @noindent
19451 which will give the following output:
19452
19453 @smallexample
19454 Global information
19455 ------------------
19456    Total number of allocations        :  18
19457    Total number of deallocations      :   5
19458    Final Water Mark (non freed mem)   :  53.00 Kilobytes
19459    High Water Mark                    :  56.90 Kilobytes
19460
19461 Allocation Root # 1
19462 -------------------
19463  Number of non freed allocations    :  10
19464  Final Water Mark (non freed mem)   :  39.06 Kilobytes
19465  High Water Mark                    :  42.97 Kilobytes
19466  Backtrace                          :
19467    test_gm.adb:11 test_gm.my_alloc
19468    test_gm.adb:24 test_gm
19469    b_test_gm.c:52 main
19470
19471 Allocation Root # 2
19472 -------------------
19473  Number of non freed allocations    :   1
19474  Final Water Mark (non freed mem)   :  10.02 Kilobytes
19475  High Water Mark                    :  10.02 Kilobytes
19476  Backtrace                          :
19477    s-secsta.adb:81  system.secondary_stack.ss_init
19478    s-secsta.adb:283 <system__secondary_stack___elabb>
19479    b_test_gm.c:33   adainit
19480
19481 Allocation Root # 3
19482 -------------------
19483  Number of non freed allocations    :   1
19484  Final Water Mark (non freed mem)   :   3.91 Kilobytes
19485  High Water Mark                    :   3.91 Kilobytes
19486  Backtrace                          :
19487    test_gm.adb:11 test_gm.my_alloc
19488    test_gm.adb:21 test_gm
19489    b_test_gm.c:52 main
19490
19491 Allocation Root # 4
19492 -------------------
19493  Number of non freed allocations    :   1
19494  Final Water Mark (non freed mem)   :  12 Bytes
19495  High Water Mark                    :  12 Bytes
19496  Backtrace                          :
19497    s-secsta.adb:181 system.secondary_stack.ss_init
19498    s-secsta.adb:283 <system__secondary_stack___elabb>
19499    b_test_gm.c:33   adainit
19500 @end smallexample
19501
19502 @noindent
19503 The allocation root #1 of the first example has been split in 2 roots #1
19504 and #3 thanks to the more precise associated backtrace.
19505
19506 @end ifclear
19507
19508 @node Stack Related Facilities
19509 @chapter Stack Related Facilities
19510
19511 @noindent
19512 This chapter describes some useful tools associated with stack
19513 checking and analysis. In
19514 particular, it deals with dynamic and static stack usage measurements.
19515
19516 @menu
19517 * Stack Overflow Checking::
19518 * Static Stack Usage Analysis::
19519 * Dynamic Stack Usage Analysis::
19520 @end menu
19521
19522 @node Stack Overflow Checking
19523 @section Stack Overflow Checking
19524 @cindex Stack Overflow Checking
19525 @cindex -fstack-check
19526
19527 @noindent
19528 For most operating systems, @command{gcc} does not perform stack overflow
19529 checking by default. This means that if the main environment task or
19530 some other task exceeds the available stack space, then unpredictable
19531 behavior will occur. Most native systems offer some level of protection by
19532 adding a guard page at the end of each task stack. This mechanism is usually
19533 not enough for dealing properly with stack overflow situations because
19534 a large local variable could ``jump'' above the guard page.
19535 Furthermore, when the
19536 guard page is hit, there may not be any space left on the stack for executing
19537 the exception propagation code. Enabling stack checking avoids
19538 such situations.
19539
19540 To activate stack checking, compile all units with the gcc option
19541 @option{-fstack-check}. For example:
19542
19543 @smallexample
19544 gcc -c -fstack-check package1.adb
19545 @end smallexample
19546
19547 @noindent
19548 Units compiled with this option will generate extra instructions to check
19549 that any use of the stack (for procedure calls or for declaring local
19550 variables in declare blocks) does not exceed the available stack space.
19551 If the space is exceeded, then a @code{Storage_Error} exception is raised.
19552
19553 For declared tasks, the stack size is controlled by the size
19554 given in an applicable @code{Storage_Size} pragma or by the value specified
19555 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
19556 the default size as defined in the GNAT runtime otherwise.
19557
19558 For the environment task, the stack size depends on
19559 system defaults and is unknown to the compiler. Stack checking
19560 may still work correctly if a fixed
19561 size stack is allocated, but this cannot be guaranteed.
19562 @ifclear vms
19563 To ensure that a clean exception is signalled for stack
19564 overflow, set the environment variable
19565 @code{GNAT_STACK_LIMIT} to indicate the maximum
19566 stack area that can be used, as in:
19567 @cindex GNAT_STACK_LIMIT
19568
19569 @smallexample
19570 SET GNAT_STACK_LIMIT 1600
19571 @end smallexample
19572
19573 @noindent
19574 The limit is given in kilobytes, so the above declaration would
19575 set the stack limit of the environment task to 1.6 megabytes.
19576 Note that the only purpose of this usage is to limit the amount
19577 of stack used by the environment task. If it is necessary to
19578 increase the amount of stack for the environment task, then this
19579 is an operating systems issue, and must be addressed with the
19580 appropriate operating systems commands.
19581 @end ifclear
19582 @ifset vms
19583 To have a fixed size stack in the environment task, the stack must be put
19584 in the P0 address space and its size specified.  Use these switches to
19585 create a p0 image:
19586
19587 @smallexample
19588 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
19589 @end smallexample
19590
19591 @noindent
19592 The quotes are required to keep case.  The number after @samp{STACK=} is the
19593 size of the environmental task stack in pagelets (512 bytes).  In this example
19594 the stack size is about 2 megabytes.
19595
19596 @noindent
19597 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
19598 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
19599 more details about the @option{/p0image} qualifier and the @option{stack}
19600 option.
19601 @end ifset
19602
19603 @node Static Stack Usage Analysis
19604 @section Static Stack Usage Analysis
19605 @cindex Static Stack Usage Analysis
19606 @cindex -fstack-usage
19607
19608 @noindent
19609 A unit compiled with @option{-fstack-usage} will generate an extra file
19610 that specifies
19611 the maximum amount of stack used, on a per-function basis.
19612 The file has the same
19613 basename as the target object file with a @file{.su} extension.
19614 Each line of this file is made up of three fields:
19615
19616 @itemize
19617 @item
19618 The name of the function.
19619 @item
19620 A number of bytes.
19621 @item
19622 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
19623 @end itemize
19624
19625 The second field corresponds to the size of the known part of the function
19626 frame.
19627
19628 The qualifier @code{static} means that the function frame size
19629 is purely static.
19630 It usually means that all local variables have a static size.
19631 In this case, the second field is a reliable measure of the function stack
19632 utilization.
19633
19634 The qualifier @code{dynamic} means that the function frame size is not static.
19635 It happens mainly when some local variables have a dynamic size. When this
19636 qualifier appears alone, the second field is not a reliable measure
19637 of the function stack analysis. When it is qualified with  @code{bounded}, it
19638 means that the second field is a reliable maximum of the function stack
19639 utilization.
19640
19641 @node Dynamic Stack Usage Analysis
19642 @section Dynamic Stack Usage Analysis
19643
19644 @noindent
19645 It is possible to measure the maximum amount of stack used by a task, by
19646 adding a switch to @command{gnatbind}, as:
19647
19648 @smallexample
19649 $ gnatbind -u0 file
19650 @end smallexample
19651
19652 @noindent
19653 With this option, at each task termination, its stack usage is  output on
19654 @file{stderr}.
19655 It is not always convenient to output the stack usage when the program
19656 is still running. Hence, it is possible to delay this output until program
19657 termination. for a given number of tasks specified as the argument of the
19658 @code{-u} option. For instance:
19659
19660 @smallexample
19661 $ gnatbind -u100 file
19662 @end smallexample
19663
19664 @noindent
19665 will buffer the stack usage information of the first 100 tasks to terminate and
19666 output this info at program termination. Results are displayed in four
19667 columns:
19668
19669 @noindent
19670 Index | Task Name | Stack Size | Actual Use [min - max]
19671
19672 @noindent
19673 where:
19674
19675 @table @emph
19676 @item Index
19677 is a number associated with each task.
19678
19679 @item Task Name
19680 is the name of the task analyzed.
19681
19682 @item Stack Size
19683 is the maximum size for the stack.
19684
19685 @item Actual Use
19686 is the measure done by the stack analyzer. In order to prevent overflow,
19687 the stack is not entirely analyzed, and it's not possible to know exactly how
19688 much has actually been used. The real amount of stack used is between the min
19689 and max values.
19690
19691 @end table
19692
19693 @noindent
19694 The environment task stack, e.g. the stack that contains the main unit, is
19695 only processed when the environment variable GNAT_STACK_LIMIT is set.
19696
19697
19698 @c *********************************
19699 @c *            GNATCHECK          *
19700 @c *********************************
19701 @node Verifying Properties Using gnatcheck
19702 @chapter Verifying Properties Using @command{gnatcheck}
19703 @findex gnatcheck
19704 @cindex @command{gnatcheck}
19705
19706 @noindent
19707 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
19708 of Ada source files according to a given set of semantic rules.
19709 @cindex ASIS
19710
19711 In order to check compliance with a given rule, @command{gnatcheck} has to
19712 semantically analyze the Ada sources.
19713 Therefore, checks can only be performed on
19714 legal Ada units. Moreover, when a unit depends semantically upon units located
19715 outside the current directory, the source search path has to be provided when
19716 calling @command{gnatcheck}, either through a specified project file or
19717 through @command{gnatcheck} switches as described below.
19718
19719 A number of rules are predefined in @command{gnatcheck} and are described
19720 later in this chapter.
19721 You can also add new rules, by modifying the @command{gnatcheck} code and
19722 rebuilding the tool. In order to add a simple rule making some local checks,
19723 a small amount of straightforward ASIS-based programming is usually needed.
19724
19725 Project support for @command{gnatcheck} is provided by the GNAT
19726 driver (see @ref{The GNAT Driver and Project Files}).
19727
19728 Invoking @command{gnatcheck} on the command line has the form:
19729
19730 @smallexample
19731 $ gnatcheck [@i{switches}]  @{@i{filename}@}
19732       [^-files^/FILES^=@{@i{arg_list_filename}@}]
19733       [-cargs @i{gcc_switches}] [-rules @i{rule_options}]
19734 @end smallexample
19735
19736 @noindent
19737 where
19738 @itemize @bullet
19739 @item
19740 @i{switches} specify the general tool options
19741
19742 @item
19743 Each @i{filename} is the name (including the extension) of a source
19744 file to process. ``Wildcards'' are allowed, and
19745 the file name may contain path information.
19746
19747 @item
19748 Each @i{arg_list_filename} is the name (including the extension) of a text
19749 file containing the names of the source files to process, separated by spaces
19750 or line breaks.
19751
19752 @item
19753 @i{gcc_switches} is a list of switches for
19754 @command{gcc}. They will be passed on to all compiler invocations made by
19755 @command{gnatcheck} to generate the ASIS trees. Here you can provide
19756 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19757 and use the @option{-gnatec} switch to set the configuration file.
19758
19759 @item
19760 @i{rule_options} is a list of options for controlling a set of
19761 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
19762 @end itemize
19763
19764 @noindent
19765 Either a @i{filename} or an @i{arg_list_filename} must be supplied.
19766
19767 @menu
19768 * Format of the Report File::
19769 * General gnatcheck Switches::
19770 * gnatcheck Rule Options::
19771 * Adding the Results of Compiler Checks to gnatcheck Output::
19772 * Project-Wide Checks::
19773 * Predefined Rules::
19774 @end menu
19775
19776 @node Format of the Report File
19777 @section Format of the Report File
19778 @cindex Report file (for @code{gnatcheck})
19779
19780 @noindent
19781 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
19782 rule violations.
19783 It also creates, in the current
19784 directory, a text file named @file{^gnatcheck.out^GNATCHECK.OUT^} that
19785 contains the complete report of the last gnatcheck run. This report contains:
19786 @itemize @bullet
19787 @item a list of the Ada source files being checked,
19788 @item a list of enabled and disabled rules,
19789 @item a list of the diagnostic messages, ordered in three different ways
19790 and collected in three separate
19791 sections. Section 1 contains the raw list of diagnostic messages. It
19792 corresponds to the output going to @file{stdout}. Section 2 contains
19793 messages ordered by rules.
19794 Section 3 contains messages ordered by source files.
19795 @end itemize
19796
19797 @node General gnatcheck Switches
19798 @section General @command{gnatcheck} Switches
19799
19800 @noindent
19801 The following switches control the general @command{gnatcheck} behavior
19802
19803 @table @option
19804 @c !sort!
19805 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
19806 @item ^-a^/ALL^
19807 Process all units including those with read-only ALI files such as
19808 those from GNAT Run-Time library.
19809
19810 @ifclear vms
19811 @ignore
19812 @cindex @option{-d} (@command{gnatcheck})
19813 @item -d
19814 Debug mode
19815 @end ignore
19816
19817 @cindex @option{-dd} (@command{gnatcheck})
19818 @item -dd
19819 Progress indicator mode (for use in GPS)
19820 @end ifclear
19821
19822 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
19823 @item ^-h^/HELP^
19824 List the predefined and user-defined rules. For more details see
19825 @ref{Predefined Rules}.
19826
19827 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
19828 @item ^-l^/LOCS^
19829 Use full source locations references in the report file. For a construct from
19830 a generic instantiation a full source location is a chain from the location
19831 of this construct in the generic unit to the place where this unit is
19832 instantiated.
19833
19834 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
19835 @item ^-q^/QUIET^
19836 Quiet mode. All the diagnoses about rule violations are placed in the
19837 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
19838
19839 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
19840 @item ^-s^/SHORT^
19841 Short format of the report file (no version information, no list of applied
19842 rules, no list of checked sources is included)
19843
19844 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
19845 @item ^-s1^/COMPILER_STYLE^
19846 Include the compiler-style section in the report file
19847
19848 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
19849 @item ^-s2^/BY_RULES^
19850 Include the section containing diagnoses ordered by rules in the report file
19851
19852 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
19853 @item ^-s3^/BY_FILES_BY_RULES^
19854 Include the section containing diagnoses ordered by files and then by rules
19855 in the report file
19856
19857 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
19858 @item ^-v^/VERBOSE^
19859 Verbose mode; @command{gnatcheck} generates version information and then
19860 a trace of sources being processed.
19861
19862 @end table
19863
19864 @noindent
19865 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
19866 @option{^-s2^/BY_RULES^} or
19867 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
19868 then the  @command{gnatcheck} report file will only contain sections
19869 explicitly denoted by these options.
19870
19871 @node gnatcheck Rule Options
19872 @section @command{gnatcheck} Rule Options
19873
19874 @noindent
19875 The following options control the processing performed by
19876 @command{gnatcheck}.
19877
19878 @table @option
19879 @cindex @option{+ALL} (@command{gnatcheck})
19880 @item +ALL
19881 Turn all the rule checks ON.
19882
19883 @cindex @option{-ALL} (@command{gnatcheck})
19884 @item -ALL
19885 Turn all the rule checks OFF.
19886
19887 @cindex @option{+R} (@command{gnatcheck})
19888 @item +R@i{rule_id[:param]}
19889 Turn on the check for a specified rule with the specified parameter, if any.
19890 @i{rule_id} must be the identifier of one of the currently implemented rules
19891 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
19892 are not case-sensitive. The @i{param} item must
19893 be a string representing a valid parameter(s) for the specified rule.
19894 If it contains any space characters then this string must be enclosed in
19895 quotation marks.
19896
19897 @cindex @option{-R} (@command{gnatcheck})
19898 @item -R@i{rule_id[:param]}
19899 Turn off the check for a specified rule with the specified parameter, if any.
19900
19901 @cindex @option{-from} (@command{gnatcheck})
19902 @item -from=@i{rule_option_filename}
19903 Read the rule options from the text file @i{rule_option_filename}, referred as
19904 ``rule file'' below.
19905
19906 @end table
19907
19908 @noindent
19909 The default behavior is that all the rule checks are enabled, except for
19910 the checks performed by the compiler.
19911 @ignore
19912 and the checks associated with the
19913 global rules.
19914 @end ignore
19915
19916 A rule file is a text file containing a set of rule options.
19917 @cindex Rule file (for @code{gnatcheck})
19918 The file may contain empty lines and Ada-style comments (comment
19919 lines and end-of-line comments). The rule file has free format; that is,
19920 you do not have to start a new rule option on a new line.
19921
19922 A rule file may contain other @option{-from=@i{rule_option_filename}}
19923 options, each such option being replaced with the content of the
19924 corresponding rule file during the rule files processing. In case a
19925 cycle is detected (that is, @i{rule_file_1} reads rule options from
19926 @i{rule_file_2}, and  @i{rule_file_2} reads (directly or indirectly)
19927 rule options from @i{rule_file_1}), the processing
19928 of rule files is interrupted and a part of their content is ignored.
19929
19930
19931 @node Adding the Results of Compiler Checks to gnatcheck Output
19932 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
19933
19934 @noindent
19935 The @command{gnatcheck} tool can include in the generated diagnostic messages
19936 and in
19937 the report file the results of the checks performed by the compiler. Though
19938 disabled by default, this effect may be obtained by using @option{+R} with
19939 the following rule identifiers and parameters:
19940
19941 @table @option
19942 @item Restrictions
19943 To record restrictions violations (that are performed by the compiler if the
19944 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
19945 use the rule named
19946 @code{Restrictions} with the same parameters as pragma
19947 @code{Restrictions} or @code{Restriction_Warnings}.
19948
19949 @item Style_Checks
19950 To record compiler style checks, use the rule named
19951 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
19952 which enables all the style checks, or a string that has exactly the same
19953 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
19954 @code{Style_Checks} (for further information about this pragma, please
19955 refer to the @cite{@value{EDITION} Reference Manual}).
19956
19957 @item Warnings
19958 To record compiler warnings (@pxref{Warning Message Control}), use the rule
19959 named @code{Warnings} with a parameter that is a valid
19960 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
19961 (for further information about this pragma, please
19962 refer to the @cite{@value{EDITION} Reference Manual}).
19963
19964 @end table
19965
19966 @node Project-Wide Checks
19967 @section Project-Wide Checks
19968 @cindex Project-wide checks (for @command{gnatcheck})
19969
19970 @noindent
19971 In order to perform checks on all units of a given project, you can use
19972 the GNAT driver along with the @option{-P} option:
19973 @smallexample
19974    gnat check -Pproj -rules -from=my_rules
19975 @end smallexample
19976
19977 @noindent
19978 If the project @code{proj} depends upon other projects, you can perform
19979 checks on the project closure using the @option{-U} option:
19980 @smallexample
19981    gnat check -Pproj -U -rules -from=my_rules
19982 @end smallexample
19983
19984 @noindent
19985 Finally, if not all the units are relevant to a particular main
19986 program in the project closure, you can perform checks for the set
19987 of units needed to create a given main program (unit closure) using
19988 the @option{-U} option followed by the name of the main unit:
19989 @smallexample
19990    gnat check -Pproj -U main -rules -from=my_rules
19991 @end smallexample
19992
19993
19994 @node Predefined Rules
19995 @section Predefined Rules
19996 @cindex Predefined rules (for @command{gnatcheck})
19997
19998 @ignore
19999 @c (Jan 2007) Since the global rules are still under development and are not
20000 @c documented, there is no point in explaining the difference between
20001 @c global and local rules
20002 @noindent
20003 A rule in @command{gnatcheck} is either local or global.
20004 A @emph{local rule} is a rule that applies to a well-defined section
20005 of a program and that can be checked by analyzing only this section.
20006 A @emph{global rule} requires analysis of some global properties of the
20007 whole program (mostly related to the program call graph).
20008 As of @value{NOW}, the implementation of global rules should be
20009 considered to be at a preliminary stage. You can use the
20010 @option{+GLOBAL} option to enable all the global rules, and the
20011 @option{-GLOBAL} rule option to disable all the global rules.
20012
20013 All the global rules in the list below are
20014 so indicated by marking them ``GLOBAL''.
20015 This +GLOBAL and -GLOBAL options are not
20016 included in the list of gnatcheck options above, because at the moment they
20017 are considered as a temporary debug options.
20018
20019 @command{gnatcheck} performs rule checks for generic
20020 instances only for global rules.  This limitation may be relaxed in a later
20021 release.
20022 @end ignore
20023
20024 @noindent
20025 The following subsections document the rules implemented in
20026 @command{gnatcheck}.
20027 The subsection title is the same as the rule identifier, which may be
20028 used as a parameter of the @option{+R} or @option{-R} options.
20029
20030
20031 @menu
20032 * Abstract_Type_Declarations::
20033 * Anonymous_Arrays::
20034 * Anonymous_Subtypes::
20035 * Blocks::
20036 * Boolean_Relational_Operators::
20037 @ignore
20038 * Ceiling_Violations::
20039 @end ignore
20040 * Controlled_Type_Declarations::
20041 * Declarations_In_Blocks::
20042 * Default_Parameters::
20043 * Discriminated_Records::
20044 * Enumeration_Ranges_In_CASE_Statements::
20045 * Exceptions_As_Control_Flow::
20046 * EXIT_Statements_With_No_Loop_Name::
20047 * Expanded_Loop_Exit_Names::
20048 * Explicit_Full_Discrete_Ranges::
20049 * Float_Equality_Checks::
20050 * Forbidden_Pragmas::
20051 * Function_Style_Procedures::
20052 * Generics_In_Subprograms::
20053 * GOTO_Statements::
20054 * Implicit_IN_Mode_Parameters::
20055 * Implicit_SMALL_For_Fixed_Point_Types::
20056 * Improperly_Located_Instantiations::
20057 * Improper_Returns::
20058 * Library_Level_Subprograms::
20059 * Local_Packages::
20060 @ignore
20061 * Improperly_Called_Protected_Entries::
20062 @end ignore
20063 * Misnamed_Identifiers::
20064 * Multiple_Entries_In_Protected_Definitions::
20065 * Name_Clashes::
20066 * Non_Qualified_Aggregates::
20067 * Non_Short_Circuit_Operators::
20068 * Non_SPARK_Attributes::
20069 * Non_Tagged_Derived_Types::
20070 * Non_Visible_Exceptions::
20071 * Numeric_Literals::
20072 * OTHERS_In_Aggregates::
20073 * OTHERS_In_CASE_Statements::
20074 * OTHERS_In_Exception_Handlers::
20075 * Outer_Loop_Exits::
20076 * Overloaded_Operators::
20077 * Overly_Nested_Control_Structures::
20078 * Parameters_Out_Of_Order::
20079 * Positional_Actuals_For_Defaulted_Generic_Parameters::
20080 * Positional_Actuals_For_Defaulted_Parameters::
20081 * Positional_Components::
20082 * Positional_Generic_Parameters::
20083 * Positional_Parameters::
20084 * Predefined_Numeric_Types::
20085 * Raising_External_Exceptions::
20086 * Raising_Predefined_Exceptions::
20087 @ignore
20088 * Recursion::
20089 * Side_Effect_Functions::
20090 @end ignore
20091 * Slices::
20092 * Unassigned_OUT_Parameters::
20093 * Uncommented_BEGIN_In_Package_Bodies::
20094 * Unconstrained_Array_Returns::
20095 * Universal_Ranges::
20096 * Unnamed_Blocks_And_Loops::
20097 @ignore
20098 * Unused_Subprograms::
20099 @end ignore
20100 * USE_PACKAGE_Clauses::
20101 * Volatile_Objects_Without_Address_Clauses::
20102 @end menu
20103
20104
20105 @node Abstract_Type_Declarations
20106 @subsection @code{Abstract_Type_Declarations}
20107 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
20108
20109 @noindent
20110 Flag all declarations of abstract types. For an abstract private
20111 type, both the private and full type declarations are flagged.
20112
20113 This rule has no parameters.
20114
20115
20116 @node Anonymous_Arrays
20117 @subsection @code{Anonymous_Arrays}
20118 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
20119
20120 @noindent
20121 Flag all anonymous array type definitions (by Ada semantics these can only
20122 occur in object declarations).
20123
20124 This rule has no parameters.
20125
20126 @node Anonymous_Subtypes
20127 @subsection @code{Anonymous_Subtypes}
20128 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
20129
20130 @noindent
20131 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
20132 any instance of a subtype indication with a constraint, other than one
20133 that occurs immediately within a subtype declaration. Any use of a range
20134 other than as a constraint used immediately within a subtype declaration
20135 is considered as an anonymous subtype.
20136
20137 An effect of this rule is that @code{for} loops such as the following are
20138 flagged (since @code{1..N} is formally a ``range''):
20139
20140 @smallexample @c ada
20141 for I in 1 .. N loop
20142    ...
20143 end loop;
20144 @end smallexample
20145
20146 @noindent
20147 Declaring an explicit subtype solves the problem:
20148
20149 @smallexample @c ada
20150 subtype S is Integer range 1..N;
20151 ...
20152 for I in S loop
20153    ...
20154 end loop;
20155 @end smallexample
20156
20157 @noindent
20158 This rule has no parameters.
20159
20160 @node Blocks
20161 @subsection @code{Blocks}
20162 @cindex @code{Blocks} rule (for @command{gnatcheck})
20163
20164 @noindent
20165 Flag each block statement.
20166
20167 This rule has no parameters.
20168
20169 @node Boolean_Relational_Operators
20170 @subsection @code{Boolean_Relational_Operators}
20171 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
20172
20173 @noindent
20174 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
20175 ``>='', ``='' and ``/='') for the predefined Boolean type.
20176 (This rule is useful in enforcing the SPARK language restrictions.)
20177
20178 Calls to predefined relational operators of any type derived from
20179 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
20180 with these designators, and uses of operators that are renamings
20181 of the predefined relational operators for @code{Standard.Boolean},
20182 are likewise not detected.
20183
20184 This rule has no parameters.
20185
20186 @ignore
20187 @node Ceiling_Violations
20188 @subsection @code{Ceiling_Violations} (under construction, GLOBAL)
20189 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
20190
20191 @noindent
20192 Flag invocations of a protected operation by a task whose priority exceeds
20193 the protected object's ceiling.
20194
20195 As of @value{NOW}, this rule has the following limitations:
20196
20197 @itemize @bullet
20198
20199 @item
20200  We consider only pragmas Priority and Interrupt_Priority as means to define
20201   a task/protected operation priority. We do not consider the effect of using
20202   Ada.Dynamic_Priorities.Set_Priority procedure;
20203
20204 @item
20205  We consider only base task priorities, and no priority inheritance. That is,
20206   we do not make a difference between calls issued during task activation and
20207   execution of the sequence of statements from task body;
20208
20209 @item
20210  Any situation when the priority of protected operation caller is set by a
20211   dynamic expression (that is, the corresponding Priority or
20212   Interrupt_Priority pragma has a non-static expression as an argument) we
20213   treat as a priority inconsistency (and, therefore, detect this situation).
20214 @end itemize
20215
20216 @noindent
20217 At the moment the notion of the main subprogram is not implemented in
20218 gnatcheck, so any pragma Priority in a library level subprogram body (in case
20219 if this subprogram can be a main subprogram of a partition) changes the
20220 priority of an environment task. So if we have more then one such pragma in
20221 the set of processed sources, the pragma that is processed last, defines the
20222 priority of an environment task.
20223
20224 This rule has no parameters.
20225 @end ignore
20226
20227 @node Controlled_Type_Declarations
20228 @subsection @code{Controlled_Type_Declarations}
20229 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
20230
20231 @noindent
20232 Flag all declarations of controlled types. A declaration of a private type
20233 is flagged if its full declaration declares a controlled type. A declaration
20234 of a derived type is flagged if its ancestor type is controlled. Subtype
20235 declarations are not checked. A declaration of a type that itself is not a
20236 descendant of a type declared in @code{Ada.Finalization} but has a controlled
20237 component is not checked.
20238
20239 This rule has no parameters.
20240
20241
20242
20243 @node Declarations_In_Blocks
20244 @subsection @code{Declarations_In_Blocks}
20245 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
20246
20247 @noindent
20248 Flag all block statements containing local declarations. A @code{declare}
20249 block with an empty @i{declarative_part} or with a @i{declarative part}
20250 containing only pragmas and/or @code{use} clauses is not flagged.
20251
20252 This rule has no parameters.
20253
20254
20255 @node Default_Parameters
20256 @subsection @code{Default_Parameters}
20257 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
20258
20259 @noindent
20260 Flag all default expressions for subprogram parameters. Parameter
20261 declarations of formal and generic subprograms are also checked.
20262
20263 This rule has no parameters.
20264
20265
20266 @node Discriminated_Records
20267 @subsection @code{Discriminated_Records}
20268 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
20269
20270 @noindent
20271 Flag all declarations of record types with discriminants. Only the
20272 declarations of record and record extension types are checked. Incomplete,
20273 formal, private, derived and private extension type declarations are not
20274 checked. Task and protected type declarations also are not checked.
20275
20276 This rule has no parameters.
20277
20278
20279 @node Enumeration_Ranges_In_CASE_Statements
20280 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
20281 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
20282
20283 @noindent
20284 Flag each use of a range of enumeration literals as a choice in a
20285 @code{case} statement.
20286 All forms for specifying a range (explicit ranges
20287 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
20288 An enumeration range is
20289 flagged even if contains exactly one enumeration value or no values at all. A
20290 type derived fom an enumeration type is considered as an enumeration type.
20291
20292 This rule helps prevent maintenance problems arising from adding an
20293 enumeration value to a type and having it implicitly handled by an existing
20294 @code{case} statement with an enumeration range that includes the new literal.
20295
20296 This rule has no parameters.
20297
20298
20299 @node Exceptions_As_Control_Flow
20300 @subsection @code{Exceptions_As_Control_Flow}
20301 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
20302
20303 @noindent
20304 Flag each place where an exception is explictly raised and handled in the
20305 same subprogram body. A @code{raise} statement in an exception handler,
20306 package body, task body or entry body is not flagged.
20307
20308 The rule has no parameters.
20309
20310 @node EXIT_Statements_With_No_Loop_Name
20311 @subsection @code{EXIT_Statements_With_No_Loop_Name}
20312 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
20313
20314 @noindent
20315 Flag each @code{exit} statement that does not specify the name of the loop
20316 being exited.
20317
20318 The rule has no parameters.
20319
20320
20321 @node Expanded_Loop_Exit_Names
20322 @subsection @code{Expanded_Loop_Exit_Names}
20323 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
20324
20325 @noindent
20326 Flag all expanded loop names in @code{exit} statements.
20327
20328 This rule has no parameters.
20329
20330 @node Explicit_Full_Discrete_Ranges
20331 @subsection @code{Explicit_Full_Discrete_Ranges}
20332 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
20333
20334 @noindent
20335 Flag each discrete range that has the form @code{A'First .. A'Last}.
20336
20337 This rule has no parameters.
20338
20339 @node Float_Equality_Checks
20340 @subsection @code{Float_Equality_Checks}
20341 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
20342
20343 @noindent
20344 Flag all calls to the predefined equality operations for floating-point types.
20345 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
20346 User-defined equality operations are not flagged, nor are ``@code{=}''
20347 and ``@code{/=}'' operations for fixed-point types.
20348
20349 This rule has no parameters.
20350
20351
20352 @node Forbidden_Pragmas
20353 @subsection @code{Forbidden_Pragmas}
20354 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
20355
20356 @noindent
20357 Flag each use of the specified pragmas.  The pragmas to be detected
20358 are named in the rule's  parameters.
20359
20360 This rule has the following parameters:
20361
20362 @itemize @bullet
20363 @item For the @option{+R} option
20364
20365 @table @asis
20366 @item @emph{Pragma_Name}
20367 Adds the specified pragma to the set of pragmas to be
20368 checked and sets the checks for all the specified pragmas
20369 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
20370 does not correspond to any pragma name defined in the Ada
20371 standard or to the name of a GNAT-specific pragma defined
20372 in the GNAT Reference Manual, it is treated as the name of
20373 unknown pragma.
20374
20375 @item @code{GNAT}
20376 All the GNAT-specific pragmas are detected; this sets
20377 the checks for all the specified pragmas ON.
20378
20379 @item @code{ALL}
20380 All pragmas are detected; this sets the rule ON.
20381 @end table
20382
20383 @item For the @option{-R} option
20384 @table @asis
20385 @item @emph{Pragma_Name}
20386 Removes the specified pragma from the set of pragmas to be
20387 checked without affecting checks for
20388 other pragmas. @emph{Pragma_Name} is treated as a name
20389 of a pragma. If it does not correspond to any pragma
20390 defined in the Ada standard or to any name defined in the
20391 GNAT Reference Manual,
20392 this option is treated as turning OFF detection of all
20393 unknown pragmas.
20394
20395 @item GNAT
20396 Turn OFF detection of all GNAT-specific pragmas
20397
20398 @item ALL
20399 Clear the list of the pragmas to be detected and
20400 turn the rule OFF.
20401 @end table
20402 @end itemize
20403
20404 @noindent
20405 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
20406 the syntax of an Ada identifier and therefore can not be considered
20407 as a pragma name, a diagnostic message is generated and the corresponding
20408 parameter is ignored.
20409
20410 When more then one parameter is given in the same rule option, the parameters
20411 must be separated by a comma.
20412
20413 If more then one option for this rule is specified for the @command{gnatcheck}
20414 call, a new option overrides the previous one(s).
20415
20416 The @option{+R} option with no parameters turns the rule ON with the set of
20417 pragmas to be detected defined by the previous rule options.
20418 (By default this set is empty, so if the only option specified for the rule is
20419 @option{+RForbidden_Pragmas} (with
20420 no parameter), then the rule is enabled, but it does not detect anything).
20421 The @option{-R} option with no parameter turns the rule OFF, but it does not
20422 affect the set of pragmas to be detected.
20423
20424
20425
20426
20427 @node Function_Style_Procedures
20428 @subsection @code{Function_Style_Procedures}
20429 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
20430
20431 @noindent
20432 Flag each procedure that can be rewritten as a function. A procedure can be
20433 converted into a function if it has exactly one parameter of mode @code{out}
20434 and no parameters of mode @code{in out}. Procedure declarations,
20435 formal procedure declarations. and generic procedure declarations are always
20436 checked. Procedure
20437 bodies and body stubs are flagged only if they do not have corresponding
20438 separate declarations. Procedure renamings and procedure instantiations are
20439 not flagged.
20440
20441 If a procedure can be rewritten as a fucntion, but its @code{out} parameter is
20442 of a limited type, it is not flagged.
20443
20444 Protected procedures are not flagged. Null procedures also are not flagged.
20445
20446 This rule has no parameters.
20447
20448
20449 @node Generics_In_Subprograms
20450 @subsection @code{Generics_In_Subprograms}
20451 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
20452
20453 @noindent
20454 Flag each declaration of a generic unit in a supbrogram. Generic
20455 declarations in the bodies of generic subprograms are also flagged.
20456 A generic unit nested in another generic unit is not flagged.
20457 If a generic unit is
20458 declared in a local package that is declared in a subprogram body, the
20459 generic unit is flagged.
20460
20461 This rule has no parameters.
20462
20463
20464 @node GOTO_Statements
20465 @subsection @code{GOTO_Statements}
20466 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
20467
20468 @noindent
20469 Flag each occurrence of a @code{goto} statement.
20470
20471 This rule has no parameters.
20472
20473
20474 @node Implicit_IN_Mode_Parameters
20475 @subsection @code{Implicit_IN_Mode_Parameters}
20476 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
20477
20478 @noindent
20479 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
20480 Note that @code{access} parameters, although they technically behave
20481 like @code{in} parameters, are not flagged.
20482
20483 This rule has no parameters.
20484
20485
20486 @node Implicit_SMALL_For_Fixed_Point_Types
20487 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
20488 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
20489
20490 @noindent
20491 Flag each fixed point type declaration that lacks an explicit
20492 representation  clause to define its @code{'Small} value.
20493 Since @code{'Small} can be  defined only for ordinary fixed point types,
20494 decimal fixed point type declarations are not checked.
20495
20496 This rule has no parameters.
20497
20498
20499 @node Improperly_Located_Instantiations
20500 @subsection @code{Improperly_Located_Instantiations}
20501 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
20502
20503 @noindent
20504 Flag all generic instantiations in library-level package specifications
20505 (including library generic packages) and in all subprogram bodies.
20506
20507 Instantiations in task and entry bodies are not flagged. Instantiations in the
20508 bodies of protected subprograms are flagged.
20509
20510 This rule has no parameters.
20511
20512
20513
20514 @node Improper_Returns
20515 @subsection @code{Improper_Returns}
20516 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
20517
20518 @noindent
20519 Flag each explicit @code{return} statement in procedures, and
20520 multiple @code{return} statements in functions.
20521 Diagnostic messages are generated for all @code{return} statements
20522 in a procedure (thus each procedure must be written so that it
20523 returns implicitly at the end of its statement part),
20524 and for all @code{return} statements in a function after the first one.
20525 This rule supports the stylistic convention that each subprogram
20526 should have no more than one point of normal return.
20527
20528 This rule has no parameters.
20529
20530
20531 @node Library_Level_Subprograms
20532 @subsection @code{Library_Level_Subprograms}
20533 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
20534
20535 @noindent
20536 Flag all library-level subprograms (including generic subprogram instantiations).
20537
20538 This rule has no parameters.
20539
20540
20541 @node Local_Packages
20542 @subsection @code{Local_Packages}
20543 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
20544
20545 @noindent
20546 Flag all local packages declared in package and generic package
20547 specifications.
20548 Local packages in bodies are not flagged.
20549
20550 This rule has no parameters.
20551
20552 @ignore
20553 @node Improperly_Called_Protected_Entries
20554 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
20555 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
20556
20557 @noindent
20558 Flag each protected entry that can be called from more than one task.
20559
20560 This rule has no parameters.
20561 @end ignore
20562
20563
20564 @node Misnamed_Identifiers
20565 @subsection @code{Misnamed_Identifiers}
20566 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
20567
20568 @noindent
20569 Flag the declaration of each identifier that does not have a suffix
20570 corresponding to the kind of entity being declared.
20571 The following declarations are checked:
20572
20573 @itemize @bullet
20574 @item
20575  type declarations
20576
20577 @item
20578  constant declarations (but not number declarations)
20579
20580 @item
20581  package renaming declarations (but not generic package renaming
20582     declarations)
20583 @end itemize
20584
20585 @noindent
20586 This rule may have parameters. When used without parameters, the rule enforces
20587 the following checks:
20588
20589 @itemize @bullet
20590 @item
20591    type-defining names end with @code{_T}, unless the type is an access type,
20592     in which case the suffix must be @code{_A}
20593 @item
20594    constant names end with @code{_C}
20595 @item
20596    names defining package renamings end with @code{_R}
20597 @end itemize
20598
20599 @noindent
20600 For a private or incomplete type declaration the following checks are
20601 made for the defining name suffix:
20602
20603 @itemize @bullet
20604 @item
20605  For an incomplete type declaration: if the corresponding full type
20606   declaration is available, the defining identifier from the full type
20607   declaration is checked, but the defining identifier from the incomplete type
20608   declaration is not; otherwise the defining identifier from the incomplete
20609   type declaration is checked against the suffix specified for type
20610   declarations.
20611
20612 @item
20613  For a private type declaration (including private extensions),  the defining
20614   identifier from the private type declaration is checked against the type
20615   suffix (even if the corresponding full declaration is an access type
20616   declaration), and the defining identifier from the corresponding full type
20617   declaration is not checked.
20618 @end itemize
20619
20620 @noindent
20621 For a deferred constant, the defining name in the corresponding full constant
20622 declaration is not checked.
20623
20624 Defining names of formal types are not checked.
20625
20626 The rule may have the following parameters:
20627
20628 @itemize @bullet
20629 @item
20630 For the @option{+R} option:
20631 @table @code
20632 @item Default
20633 Sets the default listed above for all the names to be checked.
20634
20635 @item Type_Suffix=@emph{string}
20636 Specifies the suffix for a type name.
20637
20638 @item Access_Suffix=@emph{string}
20639 Specifies the suffix for an access type name. If
20640 this parameter is set, it overrides for access
20641 types the suffix set by the @code{Type_Suffix} parameter.
20642
20643 @item Constant_Suffix=@emph{string}
20644 Specifies the suffix for a constant name.
20645
20646 @item Renaming_Suffix=@emph{string}
20647 Specifies the suffix for a package renaming name.
20648 @end table
20649
20650 @item
20651 For the @option{-R} option:
20652 @table @code
20653 @item All_Suffixes
20654 Remove all the suffixes specified for the
20655 identifier suffix checks, whether by default or
20656 as specified by other rule parameters. All the
20657 checks for this rule are disabled as a result.
20658
20659 @item Type_Suffix
20660 Removes the suffix specified for types. This
20661 disables checks for types but does not disable
20662 any other checks for this rule (including the
20663 check for access type names if @code{Access_Suffix} is
20664 set).
20665
20666 @item Access_Suffix
20667 Removes the suffix specified for access types.
20668 This disables checks for access type names but
20669 does not disable any other checks for this rule.
20670 If @code{Type_Suffix} is set, access type names are
20671 checked as ordinary type names.
20672
20673 @item Constant_Suffix
20674 Removes the suffix specified for constants. This
20675 disables checks for constant names but does not
20676 disable any other checks for this rule.
20677
20678 @item Renaming_Suffix
20679 Removes the suffix specified for package
20680 renamings. This disables checks for package
20681 renamings but does not disable any other checks
20682 for this rule.
20683 @end table
20684 @end itemize
20685
20686 @noindent
20687 If more than one parameter is used, parameters must be separated by commas.
20688
20689 If more than one  option is specified for the @command{gnatcheck} invocation,
20690 a new option overrides the previous one(s).
20691
20692 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
20693 checks for all the
20694 name suffixes specified by previous options used for this rule.
20695
20696 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
20697 all the checks but keeps
20698 all the suffixes specified by previous options used for this rule.
20699
20700 The @emph{string} value must be a valid suffix for an Ada identifier (after
20701 trimming all the leading and trailing space characters, if any).
20702 Parameters are not case sensitive, except the @emph{string} part.
20703
20704 If any error is detected in a rule parameter, the parameter is ignored.
20705 In such a case the options that are set for the rule are not
20706 specified.
20707
20708
20709
20710 @node Multiple_Entries_In_Protected_Definitions
20711 @subsection @code{Multiple_Entries_In_Protected_Definitions}
20712 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
20713
20714 @noindent
20715 Flag each protected definition (i.e., each protected object/type declaration)
20716 that defines more than one entry.
20717 Diagnostic messages are generated for all the entry declarations
20718 except the first one. An entry family is counted as one entry. Entries from
20719 the private part of the protected definition are also checked.
20720
20721 This rule has no parameters.
20722
20723 @node Name_Clashes
20724 @subsection @code{Name_Clashes}
20725 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
20726
20727 @noindent
20728 Check that certain names are not used as defining identifiers. To activate
20729 this rule, you need to supply a reference to the dictionary file(s) as a rule
20730 parameter(s) (more then one dictionary file can be specified). If no
20731 dictionary file is set, this rule will not cause anything to be flagged.
20732 Only defining occurrences, not references, are checked.
20733 The check is not case-sensitive.
20734
20735 This rule is enabled by default, but without setting any corresponding
20736 dictionary file(s); thus the default effect is to do no checks.
20737
20738 A dictionary file is a plain text file. The maximum line length for this file
20739 is 1024 characters.  If the line is longer then this limit, extra characters
20740 are ignored.
20741
20742 Each line can be either an empty line, a comment line, or a line containing
20743 a list of identifiers separated by space or HT characters.
20744 A comment is an Ada-style comment (from @code{--} to end-of-line).
20745 Identifiers must follow the Ada syntax for identifiers.
20746 A line containing one or more identifiers may end with a comment.
20747
20748 @node Non_Qualified_Aggregates
20749 @subsection @code{Non_Qualified_Aggregates}
20750 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
20751
20752 @noindent
20753 Flag each non-qualified aggregate.
20754 A non-qualified aggregate is an
20755 aggregate that is not the expression of a qualified expression. A
20756 string literal is not considered an aggregate, but an array
20757 aggregate of a string type is considered as a normal aggregate.
20758 Aggregates of anonymous array types are not flagged.
20759
20760 This rule has no parameters.
20761
20762
20763 @node Non_Short_Circuit_Operators
20764 @subsection @code{Non_Short_Circuit_Operators}
20765 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
20766
20767 @noindent
20768 Flag all calls to predefined @code{and} and @code{or} operators for
20769 any boolean type. Calls to
20770 user-defined @code{and} and @code{or} and to operators defined by renaming
20771 declarations are not flagged. Calls to predefined @code{and} and @code{or}
20772 operators for modular types or boolean array types are not flagged.
20773
20774 This rule has no parameters.
20775
20776
20777
20778 @node Non_SPARK_Attributes
20779 @subsection @code{Non_SPARK_Attributes}
20780 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
20781
20782 @noindent
20783 The SPARK language defines the following subset of Ada 95 attribute
20784 designators as those that can be used in SPARK programs. The use of
20785 any other attribute is flagged.
20786
20787 @itemize @bullet
20788 @item @code{'Adjacent}
20789 @item @code{'Aft}
20790 @item @code{'Base}
20791 @item @code{'Ceiling}
20792 @item @code{'Component_Size}
20793 @item @code{'Compose}
20794 @item @code{'Copy_Sign}
20795 @item @code{'Delta}
20796 @item @code{'Denorm}
20797 @item @code{'Digits}
20798 @item @code{'Exponent}
20799 @item @code{'First}
20800 @item @code{'Floor}
20801 @item @code{'Fore}
20802 @item @code{'Fraction}
20803 @item @code{'Last}
20804 @item @code{'Leading_Part}
20805 @item @code{'Length}
20806 @item @code{'Machine}
20807 @item @code{'Machine_Emax}
20808 @item @code{'Machine_Emin}
20809 @item @code{'Machine_Mantissa}
20810 @item @code{'Machine_Overflows}
20811 @item @code{'Machine_Radix}
20812 @item @code{'Machine_Rounds}
20813 @item @code{'Max}
20814 @item @code{'Min}
20815 @item @code{'Model}
20816 @item @code{'Model_Emin}
20817 @item @code{'Model_Epsilon}
20818 @item @code{'Model_Mantissa}
20819 @item @code{'Model_Small}
20820 @item @code{'Modulus}
20821 @item @code{'Pos}
20822 @item @code{'Pred}
20823 @item @code{'Range}
20824 @item @code{'Remainder}
20825 @item @code{'Rounding}
20826 @item @code{'Safe_First}
20827 @item @code{'Safe_Last}
20828 @item @code{'Scaling}
20829 @item @code{'Signed_Zeros}
20830 @item @code{'Size}
20831 @item @code{'Small}
20832 @item @code{'Succ}
20833 @item @code{'Truncation}
20834 @item @code{'Unbiased_Rounding}
20835 @item @code{'Val}
20836 @item @code{'Valid}
20837 @end itemize
20838
20839 @noindent
20840 This rule has no parameters.
20841
20842
20843 @node Non_Tagged_Derived_Types
20844 @subsection @code{Non_Tagged_Derived_Types}
20845 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
20846
20847 @noindent
20848 Flag all derived type declarations that do not have a record extension part.
20849
20850 This rule has no parameters.
20851
20852
20853
20854 @node Non_Visible_Exceptions
20855 @subsection @code{Non_Visible_Exceptions}
20856 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
20857
20858 @noindent
20859 Flag constructs leading to the possibility of propagating an exception
20860 out of the scope in which the exception is declared.
20861 Two cases are detected:
20862
20863 @itemize @bullet
20864 @item
20865 An exception declaration in a subprogram body, task body or block
20866 statement is flagged if the body or statement does not contain a handler for
20867 that exception or a handler with an @code{others} choice.
20868
20869 @item
20870 A @code{raise} statement in an exception handler of a subprogram body,
20871 task body or block statement is flagged if it (re)raises a locally
20872 declared exception.  This may occur under the following circumstances:
20873 @itemize @minus
20874 @item
20875 it explicitly raises a locally declared exception, or
20876 @item
20877 it does not specify an exception name (i.e., it is simply @code{raise;})
20878 and the enclosing handler contains a locally declared exception in its
20879 exception choices.
20880 @end itemize
20881 @end itemize
20882
20883 @noindent
20884 Renamings of local exceptions are not flagged.
20885
20886 This rule has no parameters.
20887
20888
20889 @node Numeric_Literals
20890 @subsection @code{Numeric_Literals}
20891 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
20892
20893 @noindent
20894 Flag each use of a numeric literal in an index expression, and in any
20895 circumstance except for the following:
20896
20897 @itemize @bullet
20898 @item
20899 a literal occurring in the initialization expression for a constant
20900 declaration or a named number declaration, or
20901
20902 @item
20903 an integer literal that is less than or equal to a value
20904 specified by the @option{N} rule parameter.
20905 @end itemize
20906
20907 @noindent
20908 This rule may have the following parameters for the @option{+R} option:
20909
20910 @table @asis
20911 @item @emph{N}
20912 @emph{N} is an integer literal used as the maximal value that is not flagged
20913 (i.e., integer literals not exceeding this value are allowed)
20914
20915 @item @code{ALL}
20916 All integer literals are flagged
20917 @end table
20918
20919 @noindent
20920 If no parameters are set, the maximum unflagged value is 1.
20921
20922 The last specified check limit (or the fact that there is no limit at
20923 all) is used when multiple @option{+R} options appear.
20924
20925 The @option{-R} option for this rule has no parameters.
20926 It disables the rule but retains the last specified maximum unflagged value.
20927 If the @option{+R} option subsequently appears, this value is used as the
20928 threshold for the check.
20929
20930
20931 @node OTHERS_In_Aggregates
20932 @subsection @code{OTHERS_In_Aggregates}
20933 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
20934
20935 @noindent
20936 Flag each use of an @code{others} choice in extension aggregates.
20937 In record and array aggregates, an @code{others} choice is flagged unless
20938 it is used to refer to all components, or to all but one component.
20939
20940 If, in case of a named array aggregate, there are two associations, one
20941 with an @code{others} choice and another with a discrete range, the
20942 @code{others} choice is flagged even if the discrete range specifies
20943 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
20944
20945 This rule has no parameters.
20946
20947 @node OTHERS_In_CASE_Statements
20948 @subsection @code{OTHERS_In_CASE_Statements}
20949 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
20950
20951 @noindent
20952 Flag any use of an @code{others} choice in a @code{case} statement.
20953
20954 This rule has no parameters.
20955
20956 @node OTHERS_In_Exception_Handlers
20957 @subsection @code{OTHERS_In_Exception_Handlers}
20958 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
20959
20960 @noindent
20961 Flag any use of an @code{others} choice in an exception handler.
20962
20963 This rule has no parameters.
20964
20965
20966 @node Outer_Loop_Exits
20967 @subsection @code{Outer_Loop_Exits}
20968 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
20969
20970 @noindent
20971 Flag each @code{exit} statement containing a loop name that is not the name
20972 of the immediately enclosing @code{loop} statement.
20973
20974 This rule has no parameters.
20975
20976
20977 @node Overloaded_Operators
20978 @subsection @code{Overloaded_Operators}
20979 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
20980
20981 @noindent
20982 Flag each function declaration that overloads an operator symbol.
20983 A function body is checked only if the body does not have a
20984 separate spec. Formal functions are also checked. For a
20985 renaming declaration, only renaming-as-declaration is checked
20986
20987 This rule has no parameters.
20988
20989
20990 @node Overly_Nested_Control_Structures
20991 @subsection @code{Overly_Nested_Control_Structures}
20992 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
20993
20994 @noindent
20995 Flag each control structure whose nesting level exceeds the value provided
20996 in the rule parameter.
20997
20998 The control structures checked are the following:
20999
21000 @itemize @bullet
21001 @item    @code{if} statement
21002 @item    @code{case} statement
21003 @item    @code{loop} statement
21004 @item    Selective accept statement
21005 @item    Timed entry call statement
21006 @item    Conditional entry call
21007 @item    Asynchronous select statement
21008 @end itemize
21009
21010 @noindent
21011 The rule may have the following parameter for the @option{+R} option:
21012
21013 @table @emph
21014 @item N
21015 Positive integer specifying the maximal control structure nesting
21016 level that is not flagged
21017 @end table
21018
21019 @noindent
21020 If the parameter for the @option{+R} option is not a positive integer,
21021 the parameter is ignored and the rule is turned ON with the most recently
21022 specified maximal non-flagged nesting level.
21023
21024 If more then one  option is specified for the gnatcheck call, the later option and
21025 new parameter override the previous one(s).
21026
21027 A @option{+R} option with no parameter turns the rule ON using the maximal
21028 non-flagged nesting level specified by the most recent @option{+R} option with
21029 a parameter, or the value 4 if there is no such previous @option{+R} option.
21030
21031
21032
21033 @node Parameters_Out_Of_Order
21034 @subsection @code{Parameters_Out_Of_Order}
21035 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
21036
21037 @noindent
21038 Flag each subprogram and entry declaration whose formal parameters are not
21039 ordered according to the following scheme:
21040
21041 @itemize @bullet
21042
21043 @item @code{in} and @code{access} parameters first,
21044 then @code{in out} parameters,
21045 and then @code{out} parameters;
21046
21047 @item for @code{in} mode, parameters with default initialization expressions
21048 occur last
21049 @end itemize
21050
21051 @noindent
21052 Only the first violation of the described order is flagged.
21053
21054 The following constructs are checked:
21055
21056 @itemize @bullet
21057 @item   subprogram declarations (including null procedures);
21058 @item   generic subprogram declarations;
21059 @item   formal subprogram declarations;
21060 @item   entry declarations;
21061 @item   subprogram bodies and subprogram body stubs that do not
21062 have separate specifications
21063 @end itemize
21064
21065 @noindent
21066 Subprogram renamings are not checked.
21067
21068 This rule has no parameters.
21069
21070
21071 @node Positional_Actuals_For_Defaulted_Generic_Parameters
21072 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
21073 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
21074
21075 @noindent
21076 Flag each generic actual parameter corresponding to a generic formal
21077 parameter with a default initialization, if positional notation is used.
21078
21079 This rule has no parameters.
21080
21081 @node Positional_Actuals_For_Defaulted_Parameters
21082 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
21083 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
21084
21085 @noindent
21086 Flag each actual parameter to a subprogram or entry call where the
21087 corresponding formal parameter has a default expression, if positional
21088 notation is used.
21089
21090 This rule has no parameters.
21091
21092 @node Positional_Components
21093 @subsection @code{Positional_Components}
21094 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
21095
21096 @noindent
21097 Flag each array, record and extension aggregate that includes positional
21098 notation.
21099
21100 This rule has no parameters.
21101
21102
21103 @node Positional_Generic_Parameters
21104 @subsection @code{Positional_Generic_Parameters}
21105 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
21106
21107 @noindent
21108 Flag each instantiation using positional parameter notation.
21109
21110 This rule has no parameters.
21111
21112
21113 @node Positional_Parameters
21114 @subsection @code{Positional_Parameters}
21115 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
21116
21117 @noindent
21118 Flag each subprogram or entry call using positional parameter notation,
21119 except for the following:
21120
21121 @itemize @bullet
21122 @item
21123 Invocations of prefix or infix operators are not flagged
21124 @item
21125 If the called subprogram or entry has only one formal parameter,
21126 the call is not flagged;
21127 @item
21128 If a subprogram call uses the @emph{Object.Operation} notation, then
21129 @itemize @minus
21130 @item
21131 the first parameter (that is, @emph{Object}) is not flagged;
21132 @item
21133 if the called subprogram has only two parameters, the second parameter
21134 of the call is not flagged;
21135 @end itemize
21136 @end itemize
21137
21138 @noindent
21139 This rule has no parameters.
21140
21141
21142
21143
21144 @node Predefined_Numeric_Types
21145 @subsection @code{Predefined_Numeric_Types}
21146 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
21147
21148 @noindent
21149 Flag each explicit use of the name of any numeric type or subtype defined
21150 in package @code{Standard}.
21151
21152 The rationale for this rule is to detect when the
21153 program may depend on platform-specific characteristics of the implementation
21154 of the predefined numeric types. Note that this rule is over-pessimistic;
21155 for example, a program that uses @code{String} indexing
21156 likely needs a variable of type @code{Integer}.
21157 Another example is the flagging of predefined numeric types with explicit
21158 constraints:
21159
21160 @smallexample @c ada
21161     subtype My_Integer is Integer range Left .. Right;
21162     Vy_Var : My_Integer;
21163 @end smallexample
21164
21165 @noindent
21166 This rule detects only numeric types and subtypes defined in
21167 @code{Standard}. The use of numeric types and subtypes defined in other
21168 predefined packages (such as @code{System.Any_Priority} or
21169 @code{Ada.Text_IO.Count}) is not flagged
21170
21171 This rule has no parameters.
21172
21173
21174
21175 @node Raising_External_Exceptions
21176 @subsection @code{Raising_External_Exceptions}
21177 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
21178
21179 @noindent
21180 Flag any @code{raise} statement, in a program unit declared in a library
21181 package or in a generic library package, for an exception that is
21182 neither a predefined exception nor an exception that is also declared (or
21183 renamed) in the visible part of the package.
21184
21185 This rule has no parameters.
21186
21187
21188
21189 @node Raising_Predefined_Exceptions
21190 @subsection @code{Raising_Predefined_Exceptions}
21191 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
21192
21193 @noindent
21194 Flag each @code{raise} statement that raises a predefined exception
21195 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
21196 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
21197
21198 This rule has no parameters.
21199
21200
21201 @ignore
21202 @node Recursion
21203 @subsection @code{Recursion} (under construction, GLOBAL)
21204 @cindex @code{Recursion} rule (for @command{gnatcheck})
21205
21206 @noindent
21207 Flag recursive subprograms (cycles in the call graph). Declarations, and not
21208 calls, of recursive subprograms are detected.
21209
21210 This rule has no parameters.
21211 @end ignore
21212
21213 @ignore
21214 @node Side_Effect_Functions
21215 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
21216 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
21217
21218 @noindent
21219 Flag functions with side effects.
21220
21221 We define a side effect as changing any data object that is not local for the
21222 body of this function.
21223
21224 At the moment, we do NOT consider a side effect any input-output operations
21225 (changing a state or a content of any file).
21226
21227 We do not consider protected functions for this rule (???)
21228
21229 There are the following sources of side effect:
21230
21231 @enumerate
21232 @item Explicit (or direct) side-effect:
21233
21234 @itemize @bullet
21235 @item
21236 direct assignment to a non-local variable;
21237
21238 @item
21239 direct call to an entity that is known to change some data object that is
21240      not local for the body of this function (Note, that if F1 calls F2 and F2
21241      does have a side effect, this does not automatically mean that F1 also
21242      have a side effect, because it may be the case that F2 is declared in
21243      F1's body and it changes some data object that is global for F2, but
21244      local for F1);
21245 @end itemize
21246
21247 @item Indirect side-effect:
21248 @itemize @bullet
21249 @item
21250 Subprogram calls implicitly issued by:
21251 @itemize @bullet
21252 @item
21253 computing initialization expressions from type declarations as a part
21254          of object elaboration or allocator evaluation;
21255 @item
21256 computing implicit parameters of subprogram or entry calls or generic
21257          instantiations;
21258 @end itemize
21259
21260 @item
21261 activation of a task that change some non-local data object (directly or
21262      indirectly);
21263
21264 @item
21265 elaboration code of a package that is a result of a package instantiation;
21266
21267 @item
21268 controlled objects;
21269 @end itemize
21270
21271 @item Situations when we can suspect a side-effect, but the full static check
21272 is either impossible or too hard:
21273 @itemize @bullet
21274 @item
21275 assignment to access variables or to the objects pointed by access
21276      variables;
21277
21278 @item
21279 call to a subprogram pointed by access-to-subprogram value
21280
21281 @item
21282 dispatching calls;
21283 @end itemize
21284 @end enumerate
21285
21286 @noindent
21287 This rule has no parameters.
21288 @end ignore
21289
21290 @node Slices
21291 @subsection @code{Slices}
21292 @cindex @code{Slices} rule (for @command{gnatcheck})
21293
21294 @noindent
21295 Flag all uses of array slicing
21296
21297 This rule has no parameters.
21298
21299
21300 @node Unassigned_OUT_Parameters
21301 @subsection @code{Unassigned_OUT_Parameters}
21302 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
21303
21304 @noindent
21305 Flags procedures' @code{out} parameters that are not assigned, and
21306 identifies the contexts in which the assignments are missing.
21307
21308 An @code{out} parameter is flagged in the statements in the procedure
21309 body's handled sequence of statements (before the procedure body's
21310 @code{exception} part, if any) if this sequence of statements contains
21311 no assignments to the parameter.
21312
21313 An @code{out} parameter is flagged in an exception handler in the exception
21314 part of the procedure body's handled sequence of statements if the handler
21315 contains no assignment to the parameter.
21316
21317 Bodies of generic procedures are also considered.
21318
21319 The following are treated as assignments to an @code{out} parameter:
21320
21321 @itemize @bullet
21322 @item
21323 an assignment statement, with the parameter or some component as the target;
21324
21325 @item
21326 passing the parameter (or one of its components) as an @code{out} or
21327 @code{in out} parameter.
21328 @end itemize
21329
21330 @noindent
21331 This rule does not have any parameters.
21332
21333
21334
21335 @node Uncommented_BEGIN_In_Package_Bodies
21336 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
21337 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
21338
21339 @noindent
21340 Flags each package body with declarations and a statement part that does not
21341 include a trailing comment on the line containing the @code{begin} keyword;
21342 this trailing comment needs to specify the package name and nothing else.
21343 The @code{begin} is not flagged if the package body does not
21344 contain any declarations.
21345
21346 If the @code{begin} keyword is placed on the
21347 same line as the last declaration or the first statement, it is flagged
21348 independently of whether the line contains a trailing comment. The
21349 diagnostic message is attached to the line containing the first statement.
21350
21351 This rule has no parameters.
21352
21353
21354 @node Unconstrained_Array_Returns
21355 @subsection @code{Unconstrained_Array_Returns}
21356 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
21357
21358 @noindent
21359 Flag each function returning an unconstrained array. Function declarations,
21360 function bodies (and body stubs) having no separate specifications,
21361 and generic function instantiations are checked.
21362 Generic function declarations, function calls and function renamings are
21363 not checked.
21364
21365 This rule has no parameters.
21366
21367 @node Universal_Ranges
21368 @subsection @code{Universal_Ranges}
21369 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
21370
21371 @noindent
21372 Flag discrete ranges that are a part of an index constraint, constrained
21373 array definition, or @code{for}-loop parameter specification, and whose bounds
21374 are both of type @i{universal_integer}. Ranges that have at least one
21375 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
21376 or an expression of non-universal type) are not flagged.
21377
21378 This rule has no parameters.
21379
21380
21381 @node Unnamed_Blocks_And_Loops
21382 @subsection @code{Unnamed_Blocks_And_Loops}
21383 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
21384
21385 @noindent
21386 Flag each unnamed block statement and loop statement.
21387
21388 The rule has no parameters.
21389
21390
21391
21392 @ignore
21393 @node Unused_Subprograms
21394 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
21395 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
21396
21397 @noindent
21398 Flag all unused subprograms.
21399
21400 This rule has no parameters.
21401 @end ignore
21402
21403
21404
21405
21406 @node USE_PACKAGE_Clauses
21407 @subsection @code{USE_PACKAGE_Clauses}
21408 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
21409
21410 @noindent
21411 Flag all @code{use} clauses for packages; @code{use type} clauses are
21412 not flagged.
21413
21414 This rule has no parameters.
21415
21416
21417
21418 @node Volatile_Objects_Without_Address_Clauses
21419 @subsection @code{Volatile_Objects_Without_Address_Clauses}
21420 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
21421
21422 @noindent
21423 Flag each volatile object that does not have an address clause.
21424
21425 The following check is made: if the pragma @code{Volatile} is applied to a
21426 data object or to its type, then an address clause must
21427 be supplied for this object.
21428
21429 This rule does not check the components of data objects,
21430 array components that are volatile as a result of the pragma
21431 @code{Volatile_Components}, or objects that are volatile because
21432 they are atomic as a result of pragmas @code{Atomic} or
21433 @code{Atomic_Components}.
21434
21435 Only variable declarations, and not constant declarations, are checked.
21436
21437 This rule has no parameters.
21438
21439
21440 @c *********************************
21441 @node Creating Sample Bodies Using gnatstub
21442 @chapter Creating Sample Bodies Using @command{gnatstub}
21443 @findex gnatstub
21444
21445 @noindent
21446 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
21447 for library unit declarations.
21448
21449 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
21450 driver (see @ref{The GNAT Driver and Project Files}).
21451
21452 To create a body stub, @command{gnatstub} has to compile the library
21453 unit declaration. Therefore, bodies can be created only for legal
21454 library units. Moreover, if a library unit depends semantically upon
21455 units located outside the current directory, you have to provide
21456 the source search path when calling @command{gnatstub}, see the description
21457 of @command{gnatstub} switches below.
21458
21459 @menu
21460 * Running gnatstub::
21461 * Switches for gnatstub::
21462 @end menu
21463
21464 @node Running gnatstub
21465 @section Running @command{gnatstub}
21466
21467 @noindent
21468 @command{gnatstub} has the command-line interface of the form
21469
21470 @smallexample
21471 $ gnatstub [switches] filename [directory]
21472 @end smallexample
21473
21474 @noindent
21475 where
21476 @table @emph
21477 @item filename
21478 is the name of the source file that contains a library unit declaration
21479 for which a body must be created. The file name may contain the path
21480 information.
21481 The file name does not have to follow the GNAT file name conventions. If the
21482 name
21483 does not follow GNAT file naming conventions, the name of the body file must
21484 be provided
21485 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
21486 If the file name follows the GNAT file naming
21487 conventions and the name of the body file is not provided,
21488 @command{gnatstub}
21489 creates the name
21490 of the body file from the argument file name by replacing the @file{.ads}
21491 suffix
21492 with the @file{.adb} suffix.
21493
21494 @item directory
21495 indicates the directory in which the body stub is to be placed (the default
21496 is the
21497 current directory)
21498
21499 @item switches
21500 is an optional sequence of switches as described in the next section
21501 @end table
21502
21503 @node Switches for gnatstub
21504 @section Switches for @command{gnatstub}
21505
21506 @table @option
21507 @c !sort!
21508
21509 @item ^-f^/FULL^
21510 @cindex @option{^-f^/FULL^} (@command{gnatstub})
21511 If the destination directory already contains a file with the name of the
21512 body file
21513 for the argument spec file, replace it with the generated body stub.
21514
21515 @item ^-hs^/HEADER=SPEC^
21516 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
21517 Put the comment header (i.e., all the comments preceding the
21518 compilation unit) from the source of the library unit declaration
21519 into the body stub.
21520
21521 @item ^-hg^/HEADER=GENERAL^
21522 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
21523 Put a sample comment header into the body stub.
21524
21525 @ifclear vms
21526 @item -IDIR
21527 @cindex @option{-IDIR} (@command{gnatstub})
21528 @itemx -I-
21529 @cindex @option{-I-} (@command{gnatstub})
21530 @end ifclear
21531 @ifset vms
21532 @item /NOCURRENT_DIRECTORY
21533 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
21534 @end ifset
21535 ^These switches have ^This switch has^ the same meaning as in calls to
21536 @command{gcc}.
21537 ^They define ^It defines ^ the source search path in the call to
21538 @command{gcc} issued
21539 by @command{gnatstub} to compile an argument source file.
21540
21541 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
21542 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
21543 This switch has the same meaning as in calls to @command{gcc}.
21544 It defines the additional configuration file to be passed to the call to
21545 @command{gcc} issued
21546 by @command{gnatstub} to compile an argument source file.
21547
21548 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
21549 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
21550 (@var{n} is a non-negative integer). Set the maximum line length in the
21551 body stub to @var{n}; the default is 79. The maximum value that can be
21552 specified is 32767. Note that in the special case of configuration
21553 pragma files, the maximum is always 32767 regardless of whether or
21554 not this switch appears.
21555
21556 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
21557 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
21558 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
21559 the generated body sample to @var{n}.
21560 The default indentation is 3.
21561
21562 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
21563 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
21564 Order local bodies alphabetically. (By default local bodies are ordered
21565 in the same way as the corresponding local specs in the argument spec file.)
21566
21567 @item ^-i^/INDENTATION=^@var{n}
21568 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
21569 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
21570
21571 @item ^-k^/TREE_FILE=SAVE^
21572 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
21573 Do not remove the tree file (i.e., the snapshot of the compiler internal
21574 structures used by @command{gnatstub}) after creating the body stub.
21575
21576 @item ^-l^/LINE_LENGTH=^@var{n}
21577 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
21578 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
21579
21580 @item ^-o^/BODY=^@var{body-name}
21581 @cindex @option{^-o^/BODY^} (@command{gnatstub})
21582 Body file name.  This should be set if the argument file name does not
21583 follow
21584 the GNAT file naming
21585 conventions. If this switch is omitted the default name for the body will be
21586 obtained
21587 from the argument file name according to the GNAT file naming conventions.
21588
21589 @item ^-q^/QUIET^
21590 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
21591 Quiet mode: do not generate a confirmation when a body is
21592 successfully created, and do not generate a message when a body is not
21593 required for an
21594 argument unit.
21595
21596 @item ^-r^/TREE_FILE=REUSE^
21597 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
21598 Reuse the tree file (if it exists) instead of creating it.  Instead of
21599 creating the tree file for the library unit declaration, @command{gnatstub}
21600 tries to find it in the current directory and use it for creating
21601 a body. If the tree file is not found, no body is created. This option
21602 also implies @option{^-k^/SAVE^}, whether or not
21603 the latter is set explicitly.
21604
21605 @item ^-t^/TREE_FILE=OVERWRITE^
21606 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
21607 Overwrite the existing tree file.  If the current directory already
21608 contains the file which, according to the GNAT file naming rules should
21609 be considered as a tree file for the argument source file,
21610 @command{gnatstub}
21611 will refuse to create the tree file needed to create a sample body
21612 unless this option is set.
21613
21614 @item ^-v^/VERBOSE^
21615 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
21616 Verbose mode: generate version information.
21617
21618 @end table
21619
21620 @node Other Utility Programs
21621 @chapter Other Utility Programs
21622
21623 @noindent
21624 This chapter discusses some other utility programs available in the Ada
21625 environment.
21626
21627 @menu
21628 * Using Other Utility Programs with GNAT::
21629 * The External Symbol Naming Scheme of GNAT::
21630 * Converting Ada Files to html with gnathtml::
21631 * Installing gnathtml::
21632 @ifset vms
21633 * LSE::
21634 * Profiling::
21635 @end ifset
21636 @end menu
21637
21638 @node Using Other Utility Programs with GNAT
21639 @section Using Other Utility Programs with GNAT
21640
21641 @noindent
21642 The object files generated by GNAT are in standard system format and in
21643 particular the debugging information uses this format. This means
21644 programs generated by GNAT can be used with existing utilities that
21645 depend on these formats.
21646
21647 @ifclear vms
21648 In general, any utility program that works with C will also often work with
21649 Ada programs generated by GNAT. This includes software utilities such as
21650 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
21651 as Purify.
21652 @end ifclear
21653
21654 @node The External Symbol Naming Scheme of GNAT
21655 @section The External Symbol Naming Scheme of GNAT
21656
21657 @noindent
21658 In order to interpret the output from GNAT, when using tools that are
21659 originally intended for use with other languages, it is useful to
21660 understand the conventions used to generate link names from the Ada
21661 entity names.
21662
21663 All link names are in all lowercase letters. With the exception of library
21664 procedure names, the mechanism used is simply to use the full expanded
21665 Ada name with dots replaced by double underscores. For example, suppose
21666 we have the following package spec:
21667
21668 @smallexample @c ada
21669 @group
21670 @cartouche
21671 package QRS is
21672    MN : Integer;
21673 end QRS;
21674 @end cartouche
21675 @end group
21676 @end smallexample
21677
21678 @noindent
21679 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
21680 the corresponding link name is @code{qrs__mn}.
21681 @findex Export
21682 Of course if a @code{pragma Export} is used this may be overridden:
21683
21684 @smallexample @c ada
21685 @group
21686 @cartouche
21687 package Exports is
21688    Var1 : Integer;
21689    pragma Export (Var1, C, External_Name => "var1_name");
21690    Var2 : Integer;
21691    pragma Export (Var2, C, Link_Name => "var2_link_name");
21692 end Exports;
21693 @end cartouche
21694 @end group
21695 @end smallexample
21696
21697 @noindent
21698 In this case, the link name for @var{Var1} is whatever link name the
21699 C compiler would assign for the C function @var{var1_name}. This typically
21700 would be either @var{var1_name} or @var{_var1_name}, depending on operating
21701 system conventions, but other possibilities exist. The link name for
21702 @var{Var2} is @var{var2_link_name}, and this is not operating system
21703 dependent.
21704
21705 @findex _main
21706 One exception occurs for library level procedures. A potential ambiguity
21707 arises between the required name @code{_main} for the C main program,
21708 and the name we would otherwise assign to an Ada library level procedure
21709 called @code{Main} (which might well not be the main program).
21710
21711 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
21712 names. So if we have a library level procedure such as
21713
21714 @smallexample @c ada
21715 @group
21716 @cartouche
21717 procedure Hello (S : String);
21718 @end cartouche
21719 @end group
21720 @end smallexample
21721
21722 @noindent
21723 the external name of this procedure will be @var{_ada_hello}.
21724
21725
21726 @node Converting Ada Files to html with gnathtml
21727 @section Converting Ada Files to HTML with @code{gnathtml}
21728
21729 @noindent
21730 This @code{Perl} script allows Ada source files to be browsed using
21731 standard Web browsers. For installation procedure, see the section
21732 @xref{Installing gnathtml}.
21733
21734 Ada reserved keywords are highlighted in a bold font and Ada comments in
21735 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
21736 switch to suppress the generation of cross-referencing information, user
21737 defined variables and types will appear in a different color; you will
21738 be able to click on any identifier and go to its declaration.
21739
21740 The command line is as follow:
21741 @smallexample
21742 $ perl gnathtml.pl [^switches^options^] ada-files
21743 @end smallexample
21744
21745 @noindent
21746 You can pass it as many Ada files as you want. @code{gnathtml} will generate
21747 an html file for every ada file, and a global file called @file{index.htm}.
21748 This file is an index of every identifier defined in the files.
21749
21750 The available ^switches^options^ are the following ones :
21751
21752 @table @option
21753 @item -83
21754 @cindex @option{-83} (@code{gnathtml})
21755 Only the Ada 83 subset of keywords will be highlighted.
21756
21757 @item -cc @var{color}
21758 @cindex @option{-cc} (@code{gnathtml})
21759 This option allows you to change the color used for comments. The default
21760 value is green. The color argument can be any name accepted by html.
21761
21762 @item -d
21763 @cindex @option{-d} (@code{gnathtml})
21764 If the Ada files depend on some other files (for instance through
21765 @code{with} clauses, the latter files will also be converted to html.
21766 Only the files in the user project will be converted to html, not the files
21767 in the run-time library itself.
21768
21769 @item -D
21770 @cindex @option{-D} (@code{gnathtml})
21771 This command is the same as @option{-d} above, but @command{gnathtml} will
21772 also look for files in the run-time library, and generate html files for them.
21773
21774 @item -ext @var{extension}
21775 @cindex @option{-ext} (@code{gnathtml})
21776 This option allows you to change the extension of the generated HTML files.
21777 If you do not specify an extension, it will default to @file{htm}.
21778
21779 @item -f
21780 @cindex @option{-f} (@code{gnathtml})
21781 By default, gnathtml will generate html links only for global entities
21782 ('with'ed units, global variables and types,...). If you specify
21783 @option{-f} on the command line, then links will be generated for local
21784 entities too.
21785
21786 @item -l @var{number}
21787 @cindex @option{-l} (@code{gnathtml})
21788 If this ^switch^option^ is provided and @var{number} is not 0, then
21789 @code{gnathtml} will number the html files every @var{number} line.
21790
21791 @item -I @var{dir}
21792 @cindex @option{-I} (@code{gnathtml})
21793 Specify a directory to search for library files (@file{.ALI} files) and
21794 source files. You can provide several -I switches on the command line,
21795 and the directories will be parsed in the order of the command line.
21796
21797 @item -o @var{dir}
21798 @cindex @option{-o} (@code{gnathtml})
21799 Specify the output directory for html files. By default, gnathtml will
21800 saved the generated html files in a subdirectory named @file{html/}.
21801
21802 @item -p @var{file}
21803 @cindex @option{-p} (@code{gnathtml})
21804 If you are using Emacs and the most recent Emacs Ada mode, which provides
21805 a full Integrated Development Environment for compiling, checking,
21806 running and debugging applications, you may use @file{.gpr} files
21807 to give the directories where Emacs can find sources and object files.
21808
21809 Using this ^switch^option^, you can tell gnathtml to use these files.
21810 This allows you to get an html version of your application, even if it
21811 is spread over multiple directories.
21812
21813 @item -sc @var{color}
21814 @cindex @option{-sc} (@code{gnathtml})
21815 This ^switch^option^ allows you to change the color used for symbol
21816 definitions.
21817 The default value is red. The color argument can be any name accepted by html.
21818
21819 @item -t @var{file}
21820 @cindex @option{-t} (@code{gnathtml})
21821 This ^switch^option^ provides the name of a file. This file contains a list of
21822 file names to be converted, and the effect is exactly as though they had
21823 appeared explicitly on the command line. This
21824 is the recommended way to work around the command line length limit on some
21825 systems.
21826
21827 @end table
21828
21829 @node Installing gnathtml
21830 @section Installing @code{gnathtml}
21831
21832 @noindent
21833 @code{Perl} needs to be installed on your machine to run this script.
21834 @code{Perl} is freely available for almost every architecture and
21835 Operating System via the Internet.
21836
21837 On Unix systems, you  may want to modify  the  first line of  the script
21838 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
21839 is. The syntax of this line is :
21840 @smallexample
21841 #!full_path_name_to_perl
21842 @end smallexample
21843
21844 @noindent
21845 Alternatively, you may run the script using the following command line:
21846
21847 @smallexample
21848 $ perl gnathtml.pl [switches] files
21849 @end smallexample
21850
21851 @ifset vms
21852 @node LSE
21853 @section LSE
21854 @findex LSE
21855
21856 @noindent
21857 The GNAT distribution provides an Ada 95 template for the HP Language
21858 Sensitive Editor (LSE), a component of DECset. In order to
21859 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
21860
21861 @node Profiling
21862 @section Profiling
21863 @findex PCA
21864
21865 @noindent
21866 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
21867 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
21868 the collection phase with the /DEBUG qualifier.
21869
21870 @smallexample
21871 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
21872 $ DEFINE LIB$DEBUG PCA$COLLECTOR
21873 $ RUN/DEBUG <PROGRAM_NAME>
21874 @end smallexample
21875 @noindent
21876 @end ifset
21877
21878 @node Running and Debugging Ada Programs
21879 @chapter Running and Debugging Ada Programs
21880 @cindex Debugging
21881
21882 @noindent
21883 This chapter discusses how to debug Ada programs.
21884 @ifset vms
21885 It applies to GNAT on the Alpha OpenVMS platform;
21886 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
21887 since HP has implemented Ada support in the OpenVMS debugger on I64.
21888 @end ifset
21889
21890 An incorrect Ada program may be handled in three ways by the GNAT compiler:
21891
21892 @enumerate
21893 @item
21894 The illegality may be a violation of the static semantics of Ada. In
21895 that case GNAT diagnoses the constructs in the program that are illegal.
21896 It is then a straightforward matter for the user to modify those parts of
21897 the program.
21898
21899 @item
21900 The illegality may be a violation of the dynamic semantics of Ada. In
21901 that case the program compiles and executes, but may generate incorrect
21902 results, or may terminate abnormally with some exception.
21903
21904 @item
21905 When presented with a program that contains convoluted errors, GNAT
21906 itself may terminate abnormally without providing full diagnostics on
21907 the incorrect user program.
21908 @end enumerate
21909
21910 @menu
21911 * The GNAT Debugger GDB::
21912 * Running GDB::
21913 * Introduction to GDB Commands::
21914 * Using Ada Expressions::
21915 * Calling User-Defined Subprograms::
21916 * Using the Next Command in a Function::
21917 * Ada Exceptions::
21918 * Ada Tasks::
21919 * Debugging Generic Units::
21920 * GNAT Abnormal Termination or Failure to Terminate::
21921 * Naming Conventions for GNAT Source Files::
21922 * Getting Internal Debugging Information::
21923 * Stack Traceback::
21924 @end menu
21925
21926 @cindex Debugger
21927 @findex gdb
21928
21929 @node The GNAT Debugger GDB
21930 @section The GNAT Debugger GDB
21931
21932 @noindent
21933 @code{GDB} is a general purpose, platform-independent debugger that
21934 can be used to debug mixed-language programs compiled with @command{gcc},
21935 and in particular is capable of debugging Ada programs compiled with
21936 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
21937 complex Ada data structures.
21938
21939 The manual @cite{Debugging with GDB}
21940 @ifset vms
21941 , located in the GNU:[DOCS] directory,
21942 @end ifset
21943 contains full details on the usage of @code{GDB}, including a section on
21944 its usage on programs. This manual should be consulted for full
21945 details. The section that follows is a brief introduction to the
21946 philosophy and use of @code{GDB}.
21947
21948 When GNAT programs are compiled, the compiler optionally writes debugging
21949 information into the generated object file, including information on
21950 line numbers, and on declared types and variables. This information is
21951 separate from the generated code. It makes the object files considerably
21952 larger, but it does not add to the size of the actual executable that
21953 will be loaded into memory, and has no impact on run-time performance. The
21954 generation of debug information is triggered by the use of the
21955 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
21956 the compilations. It is important to emphasize that the use of these
21957 options does not change the generated code.
21958
21959 The debugging information is written in standard system formats that
21960 are used by many tools, including debuggers and profilers. The format
21961 of the information is typically designed to describe C types and
21962 semantics, but GNAT implements a translation scheme which allows full
21963 details about Ada types and variables to be encoded into these
21964 standard C formats. Details of this encoding scheme may be found in
21965 the file exp_dbug.ads in the GNAT source distribution. However, the
21966 details of this encoding are, in general, of no interest to a user,
21967 since @code{GDB} automatically performs the necessary decoding.
21968
21969 When a program is bound and linked, the debugging information is
21970 collected from the object files, and stored in the executable image of
21971 the program. Again, this process significantly increases the size of
21972 the generated executable file, but it does not increase the size of
21973 the executable program itself. Furthermore, if this program is run in
21974 the normal manner, it runs exactly as if the debug information were
21975 not present, and takes no more actual memory.
21976
21977 However, if the program is run under control of @code{GDB}, the
21978 debugger is activated.  The image of the program is loaded, at which
21979 point it is ready to run.  If a run command is given, then the program
21980 will run exactly as it would have if @code{GDB} were not present. This
21981 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
21982 entirely non-intrusive until a breakpoint is encountered.  If no
21983 breakpoint is ever hit, the program will run exactly as it would if no
21984 debugger were present. When a breakpoint is hit, @code{GDB} accesses
21985 the debugging information and can respond to user commands to inspect
21986 variables, and more generally to report on the state of execution.
21987
21988 @c **************
21989 @node Running GDB
21990 @section Running GDB
21991
21992 @noindent
21993 This section describes how to initiate the debugger.
21994 @c The above sentence is really just filler, but it was otherwise
21995 @c clumsy to get the first paragraph nonindented given the conditional
21996 @c nature of the description
21997
21998 @ifclear vms
21999 The debugger can be launched from a @code{GPS} menu or
22000 directly from the command line. The description below covers the latter use.
22001 All the commands shown can be used in the @code{GPS} debug console window,
22002 but there are usually more GUI-based ways to achieve the same effect.
22003 @end ifclear
22004
22005 The command to run @code{GDB} is
22006
22007 @smallexample
22008 $ ^gdb program^GDB PROGRAM^
22009 @end smallexample
22010
22011 @noindent
22012 where @code{^program^PROGRAM^} is the name of the executable file. This
22013 activates the debugger and results in a prompt for debugger commands.
22014 The simplest command is simply @code{run}, which causes the program to run
22015 exactly as if the debugger were not present. The following section
22016 describes some of the additional commands that can be given to @code{GDB}.
22017
22018 @c *******************************
22019 @node Introduction to GDB Commands
22020 @section Introduction to GDB Commands
22021
22022 @noindent
22023 @code{GDB} contains a large repertoire of commands. The manual
22024 @cite{Debugging with GDB}
22025 @ifset vms
22026 (located in the GNU:[DOCS] directory)
22027 @end ifset
22028 includes extensive documentation on the use
22029 of these commands, together with examples of their use. Furthermore,
22030 the command @var{help} invoked from within @code{GDB} activates a simple help
22031 facility which summarizes the available commands and their options.
22032 In this section we summarize a few of the most commonly
22033 used commands to give an idea of what @code{GDB} is about. You should create
22034 a simple program with debugging information and experiment with the use of
22035 these @code{GDB} commands on the program as you read through the
22036 following section.
22037
22038 @table @code
22039 @item set args @var{arguments}
22040 The @var{arguments} list above is a list of arguments to be passed to
22041 the program on a subsequent run command, just as though the arguments
22042 had been entered on a normal invocation of the program. The @code{set args}
22043 command is not needed if the program does not require arguments.
22044
22045 @item run
22046 The @code{run} command causes execution of the program to start from
22047 the beginning. If the program is already running, that is to say if
22048 you are currently positioned at a breakpoint, then a prompt will ask
22049 for confirmation that you want to abandon the current execution and
22050 restart.
22051
22052 @item breakpoint @var{location}
22053 The breakpoint command sets a breakpoint, that is to say a point at which
22054 execution will halt and @code{GDB} will await further
22055 commands. @var{location} is
22056 either a line number within a file, given in the format @code{file:linenumber},
22057 or it is the name of a subprogram. If you request that a breakpoint be set on
22058 a subprogram that is overloaded, a prompt will ask you to specify on which of
22059 those subprograms you want to breakpoint. You can also
22060 specify that all of them should be breakpointed. If the program is run
22061 and execution encounters the breakpoint, then the program
22062 stops and @code{GDB} signals that the breakpoint was encountered by
22063 printing the line of code before which the program is halted.
22064
22065 @item breakpoint exception @var{name}
22066 A special form of the breakpoint command which breakpoints whenever
22067 exception @var{name} is raised.
22068 If @var{name} is omitted,
22069 then a breakpoint will occur when any exception is raised.
22070
22071 @item print @var{expression}
22072 This will print the value of the given expression. Most simple
22073 Ada expression formats are properly handled by @code{GDB}, so the expression
22074 can contain function calls, variables, operators, and attribute references.
22075
22076 @item continue
22077 Continues execution following a breakpoint, until the next breakpoint or the
22078 termination of the program.
22079
22080 @item step
22081 Executes a single line after a breakpoint. If the next statement
22082 is a subprogram call, execution continues into (the first statement of)
22083 the called subprogram.
22084
22085 @item next
22086 Executes a single line. If this line is a subprogram call, executes and
22087 returns from the call.
22088
22089 @item list
22090 Lists a few lines around the current source location. In practice, it
22091 is usually more convenient to have a separate edit window open with the
22092 relevant source file displayed. Successive applications of this command
22093 print subsequent lines. The command can be given an argument which is a
22094 line number, in which case it displays a few lines around the specified one.
22095
22096 @item backtrace
22097 Displays a backtrace of the call chain. This command is typically
22098 used after a breakpoint has occurred, to examine the sequence of calls that
22099 leads to the current breakpoint. The display includes one line for each
22100 activation record (frame) corresponding to an active subprogram.
22101
22102 @item up
22103 At a breakpoint, @code{GDB} can display the values of variables local
22104 to the current frame. The command @code{up} can be used to
22105 examine the contents of other active frames, by moving the focus up
22106 the stack, that is to say from callee to caller, one frame at a time.
22107
22108 @item down
22109 Moves the focus of @code{GDB} down from the frame currently being
22110 examined to the frame of its callee (the reverse of the previous command),
22111
22112 @item frame @var{n}
22113 Inspect the frame with the given number. The value 0 denotes the frame
22114 of the current breakpoint, that is to say the top of the call stack.
22115
22116 @end table
22117
22118 @noindent
22119 The above list is a very short introduction to the commands that
22120 @code{GDB} provides. Important additional capabilities, including conditional
22121 breakpoints, the ability to execute command sequences on a breakpoint,
22122 the ability to debug at the machine instruction level and many other
22123 features are described in detail in @cite{Debugging with GDB}.
22124 Note that most commands can be abbreviated
22125 (for example, c for continue, bt for backtrace).
22126
22127 @node Using Ada Expressions
22128 @section Using Ada Expressions
22129 @cindex Ada expressions
22130
22131 @noindent
22132 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
22133 extensions. The philosophy behind the design of this subset is
22134
22135 @itemize @bullet
22136 @item
22137 That @code{GDB} should provide basic literals and access to operations for
22138 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
22139 leaving more sophisticated computations to subprograms written into the
22140 program (which therefore may be called from @code{GDB}).
22141
22142 @item
22143 That type safety and strict adherence to Ada language restrictions
22144 are not particularly important to the @code{GDB} user.
22145
22146 @item
22147 That brevity is important to the @code{GDB} user.
22148 @end itemize
22149
22150 @noindent
22151 Thus, for brevity, the debugger acts as if there were
22152 implicit @code{with} and @code{use} clauses in effect for all user-written
22153 packages, thus making it unnecessary to fully qualify most names with
22154 their packages, regardless of context. Where this causes ambiguity,
22155 @code{GDB} asks the user's intent.
22156
22157 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
22158
22159 @node Calling User-Defined Subprograms
22160 @section Calling User-Defined Subprograms
22161
22162 @noindent
22163 An important capability of @code{GDB} is the ability to call user-defined
22164 subprograms while debugging. This is achieved simply by entering
22165 a subprogram call statement in the form:
22166
22167 @smallexample
22168 call subprogram-name (parameters)
22169 @end smallexample
22170
22171 @noindent
22172 The keyword @code{call} can be omitted in the normal case where the
22173 @code{subprogram-name} does not coincide with any of the predefined
22174 @code{GDB} commands.
22175
22176 The effect is to invoke the given subprogram, passing it the
22177 list of parameters that is supplied. The parameters can be expressions and
22178 can include variables from the program being debugged. The
22179 subprogram must be defined
22180 at the library level within your program, and @code{GDB} will call the
22181 subprogram within the environment of your program execution (which
22182 means that the subprogram is free to access or even modify variables
22183 within your program).
22184
22185 The most important use of this facility is in allowing the inclusion of
22186 debugging routines that are tailored to particular data structures
22187 in your program. Such debugging routines can be written to provide a suitably
22188 high-level description of an abstract type, rather than a low-level dump
22189 of its physical layout. After all, the standard
22190 @code{GDB print} command only knows the physical layout of your
22191 types, not their abstract meaning. Debugging routines can provide information
22192 at the desired semantic level and are thus enormously useful.
22193
22194 For example, when debugging GNAT itself, it is crucial to have access to
22195 the contents of the tree nodes used to represent the program internally.
22196 But tree nodes are represented simply by an integer value (which in turn
22197 is an index into a table of nodes).
22198 Using the @code{print} command on a tree node would simply print this integer
22199 value, which is not very useful. But the PN routine (defined in file
22200 treepr.adb in the GNAT sources) takes a tree node as input, and displays
22201 a useful high level representation of the tree node, which includes the
22202 syntactic category of the node, its position in the source, the integers
22203 that denote descendant nodes and parent node, as well as varied
22204 semantic information. To study this example in more detail, you might want to
22205 look at the body of the PN procedure in the stated file.
22206
22207 @node Using the Next Command in a Function
22208 @section Using the Next Command in a Function
22209
22210 @noindent
22211 When you use the @code{next} command in a function, the current source
22212 location will advance to the next statement as usual. A special case
22213 arises in the case of a @code{return} statement.
22214
22215 Part of the code for a return statement is the ``epilog'' of the function.
22216 This is the code that returns to the caller. There is only one copy of
22217 this epilog code, and it is typically associated with the last return
22218 statement in the function if there is more than one return. In some
22219 implementations, this epilog is associated with the first statement
22220 of the function.
22221
22222 The result is that if you use the @code{next} command from a return
22223 statement that is not the last return statement of the function you
22224 may see a strange apparent jump to the last return statement or to
22225 the start of the function. You should simply ignore this odd jump.
22226 The value returned is always that from the first return statement
22227 that was stepped through.
22228
22229 @node Ada Exceptions
22230 @section Breaking on Ada Exceptions
22231 @cindex Exceptions
22232
22233 @noindent
22234 You can set breakpoints that trip when your program raises
22235 selected exceptions.
22236
22237 @table @code
22238 @item break exception
22239 Set a breakpoint that trips whenever (any task in the) program raises
22240 any exception.
22241
22242 @item break exception @var{name}
22243 Set a breakpoint that trips whenever (any task in the) program raises
22244 the exception @var{name}.
22245
22246 @item break exception unhandled
22247 Set a breakpoint that trips whenever (any task in the) program raises an
22248 exception for which there is no handler.
22249
22250 @item info exceptions
22251 @itemx info exceptions @var{regexp}
22252 The @code{info exceptions} command permits the user to examine all defined
22253 exceptions within Ada programs. With a regular expression, @var{regexp}, as
22254 argument, prints out only those exceptions whose name matches @var{regexp}.
22255 @end table
22256
22257 @node Ada Tasks
22258 @section Ada Tasks
22259 @cindex Tasks
22260
22261 @noindent
22262 @code{GDB} allows the following task-related commands:
22263
22264 @table @code
22265 @item info tasks
22266 This command shows a list of current Ada tasks, as in the following example:
22267
22268 @smallexample
22269 @iftex
22270 @leftskip=0cm
22271 @end iftex
22272 (gdb) info tasks
22273   ID       TID P-ID   Thread Pri State                 Name
22274    1   8088000   0   807e000  15 Child Activation Wait main_task
22275    2   80a4000   1   80ae000  15 Accept/Select Wait    b
22276    3   809a800   1   80a4800  15 Child Activation Wait a
22277 *  4   80ae800   3   80b8000  15 Running               c
22278 @end smallexample
22279
22280 @noindent
22281 In this listing, the asterisk before the first task indicates it to be the
22282 currently running task. The first column lists the task ID that is used
22283 to refer to tasks in the following commands.
22284
22285 @item break @var{linespec} task @var{taskid}
22286 @itemx break @var{linespec} task @var{taskid} if @dots{}
22287 @cindex Breakpoints and tasks
22288 These commands are like the @code{break @dots{} thread @dots{}}.
22289 @var{linespec} specifies source lines.
22290
22291 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
22292 to specify that you only want @code{GDB} to stop the program when a
22293 particular Ada task reaches this breakpoint. @var{taskid} is one of the
22294 numeric task identifiers assigned by @code{GDB}, shown in the first
22295 column of the @samp{info tasks} display.
22296
22297 If you do not specify @samp{task @var{taskid}} when you set a
22298 breakpoint, the breakpoint applies to @emph{all} tasks of your
22299 program.
22300
22301 You can use the @code{task} qualifier on conditional breakpoints as
22302 well; in this case, place @samp{task @var{taskid}} before the
22303 breakpoint condition (before the @code{if}).
22304
22305 @item task @var{taskno}
22306 @cindex Task switching
22307
22308 This command allows to switch to the task referred by @var{taskno}. In
22309 particular, This allows to browse the backtrace of the specified
22310 task. It is advised to switch back to the original task before
22311 continuing execution otherwise the scheduling of the program may be
22312 perturbed.
22313 @end table
22314
22315 @noindent
22316 For more detailed information on the tasking support,
22317 see @cite{Debugging with GDB}.
22318
22319 @node Debugging Generic Units
22320 @section Debugging Generic Units
22321 @cindex Debugging Generic Units
22322 @cindex Generics
22323
22324 @noindent
22325 GNAT always uses code expansion for generic instantiation. This means that
22326 each time an instantiation occurs, a complete copy of the original code is
22327 made, with appropriate substitutions of formals by actuals.
22328
22329 It is not possible to refer to the original generic entities in
22330 @code{GDB}, but it is always possible to debug a particular instance of
22331 a generic, by using the appropriate expanded names. For example, if we have
22332
22333 @smallexample @c ada
22334 @group
22335 @cartouche
22336 procedure g is
22337
22338    generic package k is
22339       procedure kp (v1 : in out integer);
22340    end k;
22341
22342    package body k is
22343       procedure kp (v1 : in out integer) is
22344       begin
22345          v1 := v1 + 1;
22346       end kp;
22347    end k;
22348
22349    package k1 is new k;
22350    package k2 is new k;
22351
22352    var : integer := 1;
22353
22354 begin
22355    k1.kp (var);
22356    k2.kp (var);
22357    k1.kp (var);
22358    k2.kp (var);
22359 end;
22360 @end cartouche
22361 @end group
22362 @end smallexample
22363
22364 @noindent
22365 Then to break on a call to procedure kp in the k2 instance, simply
22366 use the command:
22367
22368 @smallexample
22369 (gdb) break g.k2.kp
22370 @end smallexample
22371
22372 @noindent
22373 When the breakpoint occurs, you can step through the code of the
22374 instance in the normal manner and examine the values of local variables, as for
22375 other units.
22376
22377 @node GNAT Abnormal Termination or Failure to Terminate
22378 @section GNAT Abnormal Termination or Failure to Terminate
22379 @cindex GNAT Abnormal Termination or Failure to Terminate
22380
22381 @noindent
22382 When presented with programs that contain serious errors in syntax
22383 or semantics,
22384 GNAT may on rare occasions  experience problems in operation, such
22385 as aborting with a
22386 segmentation fault or illegal memory access, raising an internal
22387 exception, terminating abnormally, or failing to terminate at all.
22388 In such cases, you can activate
22389 various features of GNAT that can help you pinpoint the construct in your
22390 program that is the likely source of the problem.
22391
22392 The following strategies are presented in increasing order of
22393 difficulty, corresponding to your experience in using GNAT and your
22394 familiarity with compiler internals.
22395
22396 @enumerate
22397 @item
22398 Run @command{gcc} with the @option{-gnatf}. This first
22399 switch causes all errors on a given line to be reported. In its absence,
22400 only the first error on a line is displayed.
22401
22402 The @option{-gnatdO} switch causes errors to be displayed as soon as they
22403 are encountered, rather than after compilation is terminated. If GNAT
22404 terminates prematurely or goes into an infinite loop, the last error
22405 message displayed may help to pinpoint the culprit.
22406
22407 @item
22408 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
22409 mode, @command{gcc} produces ongoing information about the progress of the
22410 compilation and provides the name of each procedure as code is
22411 generated. This switch allows you to find which Ada procedure was being
22412 compiled when it encountered a code generation problem.
22413
22414 @item
22415 @cindex @option{-gnatdc} switch
22416 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
22417 switch that does for the front-end what @option{^-v^VERBOSE^} does
22418 for the back end. The system prints the name of each unit,
22419 either a compilation unit or nested unit, as it is being analyzed.
22420 @item
22421 Finally, you can start
22422 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
22423 front-end of GNAT, and can be run independently (normally it is just
22424 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
22425 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
22426 @code{where} command is the first line of attack; the variable
22427 @code{lineno} (seen by @code{print lineno}), used by the second phase of
22428 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
22429 which the execution stopped, and @code{input_file name} indicates the name of
22430 the source file.
22431 @end enumerate
22432
22433 @node Naming Conventions for GNAT Source Files
22434 @section Naming Conventions for GNAT Source Files
22435
22436 @noindent
22437 In order to examine the workings of the GNAT system, the following
22438 brief description of its organization may be helpful:
22439
22440 @itemize @bullet
22441 @item
22442 Files with prefix @file{^sc^SC^} contain the lexical scanner.
22443
22444 @item
22445 All files prefixed with @file{^par^PAR^} are components of the parser. The
22446 numbers correspond to chapters of the Ada Reference Manual. For example,
22447 parsing of select statements can be found in @file{par-ch9.adb}.
22448
22449 @item
22450 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
22451 numbers correspond to chapters of the Ada standard. For example, all
22452 issues involving context clauses can be found in @file{sem_ch10.adb}. In
22453 addition, some features of the language require sufficient special processing
22454 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
22455 dynamic dispatching, etc.
22456
22457 @item
22458 All files prefixed with @file{^exp^EXP^} perform normalization and
22459 expansion of the intermediate representation (abstract syntax tree, or AST).
22460 these files use the same numbering scheme as the parser and semantics files.
22461 For example, the construction of record initialization procedures is done in
22462 @file{exp_ch3.adb}.
22463
22464 @item
22465 The files prefixed with @file{^bind^BIND^} implement the binder, which
22466 verifies the consistency of the compilation, determines an order of
22467 elaboration, and generates the bind file.
22468
22469 @item
22470 The files @file{atree.ads} and @file{atree.adb} detail the low-level
22471 data structures used by the front-end.
22472
22473 @item
22474 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
22475 the abstract syntax tree as produced by the parser.
22476
22477 @item
22478 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
22479 all entities, computed during semantic analysis.
22480
22481 @item
22482 Library management issues are dealt with in files with prefix
22483 @file{^lib^LIB^}.
22484
22485 @item
22486 @findex Ada
22487 @cindex Annex A
22488 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
22489 defined in Annex A.
22490
22491 @item
22492 @findex Interfaces
22493 @cindex Annex B
22494 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
22495 defined in Annex B.
22496
22497 @item
22498 @findex System
22499 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
22500 both language-defined children and GNAT run-time routines.
22501
22502 @item
22503 @findex GNAT
22504 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
22505 general-purpose packages, fully documented in their specifications. All
22506 the other @file{.c} files are modifications of common @command{gcc} files.
22507 @end itemize
22508
22509 @node Getting Internal Debugging Information
22510 @section Getting Internal Debugging Information
22511
22512 @noindent
22513 Most compilers have internal debugging switches and modes. GNAT
22514 does also, except GNAT internal debugging switches and modes are not
22515 secret. A summary and full description of all the compiler and binder
22516 debug flags are in the file @file{debug.adb}. You must obtain the
22517 sources of the compiler to see the full detailed effects of these flags.
22518
22519 The switches that print the source of the program (reconstructed from
22520 the internal tree) are of general interest for user programs, as are the
22521 options to print
22522 the full internal tree, and the entity table (the symbol table
22523 information). The reconstructed source provides a readable version of the
22524 program after the front-end has completed analysis and  expansion,
22525 and is useful when studying the performance of specific constructs.
22526 For example, constraint checks are indicated, complex aggregates
22527 are replaced with loops and assignments, and tasking primitives
22528 are replaced with run-time calls.
22529
22530 @node Stack Traceback
22531 @section Stack Traceback
22532 @cindex traceback
22533 @cindex stack traceback
22534 @cindex stack unwinding
22535
22536 @noindent
22537 Traceback is a mechanism to display the sequence of subprogram calls that
22538 leads to a specified execution point in a program. Often (but not always)
22539 the execution point is an instruction at which an exception has been raised.
22540 This mechanism is also known as @i{stack unwinding} because it obtains
22541 its information by scanning the run-time stack and recovering the activation
22542 records of all active subprograms. Stack unwinding is one of the most
22543 important tools for program debugging.
22544
22545 The first entry stored in traceback corresponds to the deepest calling level,
22546 that is to say the subprogram currently executing the instruction
22547 from which we want to obtain the traceback.
22548
22549 Note that there is no runtime performance penalty when stack traceback
22550 is enabled, and no exception is raised during program execution.
22551
22552 @menu
22553 * Non-Symbolic Traceback::
22554 * Symbolic Traceback::
22555 @end menu
22556
22557 @node Non-Symbolic Traceback
22558 @subsection Non-Symbolic Traceback
22559 @cindex traceback, non-symbolic
22560
22561 @noindent
22562 Note: this feature is not supported on all platforms. See
22563 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
22564 platforms.
22565
22566 @menu
22567 * Tracebacks From an Unhandled Exception::
22568 * Tracebacks From Exception Occurrences (non-symbolic)::
22569 * Tracebacks From Anywhere in a Program (non-symbolic)::
22570 @end menu
22571
22572 @node Tracebacks From an Unhandled Exception
22573 @subsubsection Tracebacks From an Unhandled Exception
22574
22575 @noindent
22576 A runtime non-symbolic traceback is a list of addresses of call instructions.
22577 To enable this feature you must use the @option{-E}
22578 @code{gnatbind}'s option. With this option a stack traceback is stored as part
22579 of exception information. You can retrieve this information using the
22580 @code{addr2line} tool.
22581
22582 Here is a simple example:
22583
22584 @smallexample @c ada
22585 @cartouche
22586 procedure STB is
22587
22588    procedure P1 is
22589    begin
22590       raise Constraint_Error;
22591    end P1;
22592
22593    procedure P2 is
22594    begin
22595       P1;
22596    end P2;
22597
22598 begin
22599    P2;
22600 end STB;
22601 @end cartouche
22602 @end smallexample
22603
22604 @smallexample
22605 $ gnatmake stb -bargs -E
22606 $ stb
22607
22608 Execution terminated by unhandled exception
22609 Exception name: CONSTRAINT_ERROR
22610 Message: stb.adb:5
22611 Call stack traceback locations:
22612 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
22613 @end smallexample
22614
22615 @noindent
22616 As we see the traceback lists a sequence of addresses for the unhandled
22617 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
22618 guess that this exception come from procedure P1. To translate these
22619 addresses into the source lines where the calls appear, the
22620 @code{addr2line} tool, described below, is invaluable. The use of this tool
22621 requires the program to be compiled with debug information.
22622
22623 @smallexample
22624 $ gnatmake -g stb -bargs -E
22625 $ stb
22626
22627 Execution terminated by unhandled exception
22628 Exception name: CONSTRAINT_ERROR
22629 Message: stb.adb:5
22630 Call stack traceback locations:
22631 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
22632
22633 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
22634    0x4011f1 0x77e892a4
22635
22636 00401373 at d:/stb/stb.adb:5
22637 0040138B at d:/stb/stb.adb:10
22638 0040139C at d:/stb/stb.adb:14
22639 00401335 at d:/stb/b~stb.adb:104
22640 004011C4 at /build/.../crt1.c:200
22641 004011F1 at /build/.../crt1.c:222
22642 77E892A4 in ?? at ??:0
22643 @end smallexample
22644
22645 @noindent
22646 The @code{addr2line} tool has several other useful options:
22647
22648 @table @code
22649 @item --functions
22650 to get the function name corresponding to any location
22651
22652 @item --demangle=gnat
22653 to use the gnat decoding mode for the function names. Note that
22654 for binutils version 2.9.x the option is simply @option{--demangle}.
22655 @end table
22656
22657 @smallexample
22658 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
22659    0x40139c 0x401335 0x4011c4 0x4011f1
22660
22661 00401373 in stb.p1 at d:/stb/stb.adb:5
22662 0040138B in stb.p2 at d:/stb/stb.adb:10
22663 0040139C in stb at d:/stb/stb.adb:14
22664 00401335 in main at d:/stb/b~stb.adb:104
22665 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
22666 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
22667 @end smallexample
22668
22669 @noindent
22670 From this traceback we can see that the exception was raised in
22671 @file{stb.adb} at line 5, which was reached from a procedure call in
22672 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
22673 which contains the call to the main program.
22674 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
22675 and the output will vary from platform to platform.
22676
22677 It is also possible to use @code{GDB} with these traceback addresses to debug
22678 the program. For example, we can break at a given code location, as reported
22679 in the stack traceback:
22680
22681 @smallexample
22682 $ gdb -nw stb
22683 @ifclear vms
22684 @noindent
22685 Furthermore, this feature is not implemented inside Windows DLL. Only
22686 the non-symbolic traceback is reported in this case.
22687 @end ifclear
22688
22689 (gdb) break *0x401373
22690 Breakpoint 1 at 0x401373: file stb.adb, line 5.
22691 @end smallexample
22692
22693 @noindent
22694 It is important to note that the stack traceback addresses
22695 do not change when debug information is included. This is particularly useful
22696 because it makes it possible to release software without debug information (to
22697 minimize object size), get a field report that includes a stack traceback
22698 whenever an internal bug occurs, and then be able to retrieve the sequence
22699 of calls with the same program compiled with debug information.
22700
22701 @node Tracebacks From Exception Occurrences (non-symbolic)
22702 @subsubsection Tracebacks From Exception Occurrences
22703
22704 @noindent
22705 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
22706 The stack traceback is attached to the exception information string, and can
22707 be retrieved in an exception handler within the Ada program, by means of the
22708 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
22709
22710 @smallexample @c ada
22711 with Ada.Text_IO;
22712 with Ada.Exceptions;
22713
22714 procedure STB is
22715
22716    use Ada;
22717    use Ada.Exceptions;
22718
22719    procedure P1 is
22720       K : Positive := 1;
22721    begin
22722       K := K - 1;
22723    exception
22724       when E : others =>
22725          Text_IO.Put_Line (Exception_Information (E));
22726    end P1;
22727
22728    procedure P2 is
22729    begin
22730       P1;
22731    end P2;
22732
22733 begin
22734    P2;
22735 end STB;
22736 @end smallexample
22737
22738 @noindent
22739 This program will output:
22740
22741 @smallexample
22742 $ stb
22743
22744 Exception name: CONSTRAINT_ERROR
22745 Message: stb.adb:12
22746 Call stack traceback locations:
22747 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
22748 @end smallexample
22749
22750 @node Tracebacks From Anywhere in a Program (non-symbolic)
22751 @subsubsection Tracebacks From Anywhere in a Program
22752
22753 @noindent
22754 It is also possible to retrieve a stack traceback from anywhere in a
22755 program. For this you need to
22756 use the @code{GNAT.Traceback} API. This package includes a procedure called
22757 @code{Call_Chain} that computes a complete stack traceback, as well as useful
22758 display procedures described below. It is not necessary to use the
22759 @option{-E gnatbind} option in this case, because the stack traceback mechanism
22760 is invoked explicitly.
22761
22762 @noindent
22763 In the following example we compute a traceback at a specific location in
22764 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
22765 convert addresses to strings:
22766
22767 @smallexample @c ada
22768 with Ada.Text_IO;
22769 with GNAT.Traceback;
22770 with GNAT.Debug_Utilities;
22771
22772 procedure STB is
22773
22774    use Ada;
22775    use GNAT;
22776    use GNAT.Traceback;
22777
22778    procedure P1 is
22779       TB  : Tracebacks_Array (1 .. 10);
22780       --  We are asking for a maximum of 10 stack frames.
22781       Len : Natural;
22782       --  Len will receive the actual number of stack frames returned.
22783    begin
22784       Call_Chain (TB, Len);
22785
22786       Text_IO.Put ("In STB.P1 : ");
22787
22788       for K in 1 .. Len loop
22789          Text_IO.Put (Debug_Utilities.Image (TB (K)));
22790          Text_IO.Put (' ');
22791       end loop;
22792
22793       Text_IO.New_Line;
22794    end P1;
22795
22796    procedure P2 is
22797    begin
22798       P1;
22799    end P2;
22800
22801 begin
22802    P2;
22803 end STB;
22804 @end smallexample
22805
22806 @smallexample
22807 $ gnatmake -g stb
22808 $ stb
22809
22810 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
22811 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
22812 @end smallexample
22813
22814 @noindent
22815 You can then get further information by invoking the @code{addr2line}
22816 tool as described earlier (note that the hexadecimal addresses
22817 need to be specified in C format, with a leading ``0x'').
22818
22819 @node Symbolic Traceback
22820 @subsection Symbolic Traceback
22821 @cindex traceback, symbolic
22822
22823 @noindent
22824 A symbolic traceback is a stack traceback in which procedure names are
22825 associated with each code location.
22826
22827 @noindent
22828 Note that this feature is not supported on all platforms. See
22829 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
22830 list of currently supported platforms.
22831
22832 @noindent
22833 Note that the symbolic traceback requires that the program be compiled
22834 with debug information. If it is not compiled with debug information
22835 only the non-symbolic information will be valid.
22836
22837 @menu
22838 * Tracebacks From Exception Occurrences (symbolic)::
22839 * Tracebacks From Anywhere in a Program (symbolic)::
22840 @end menu
22841
22842 @node Tracebacks From Exception Occurrences (symbolic)
22843 @subsubsection Tracebacks From Exception Occurrences
22844
22845 @smallexample @c ada
22846 with Ada.Text_IO;
22847 with GNAT.Traceback.Symbolic;
22848
22849 procedure STB is
22850
22851    procedure P1 is
22852    begin
22853       raise Constraint_Error;
22854    end P1;
22855
22856    procedure P2 is
22857    begin
22858       P1;
22859    end P2;
22860
22861    procedure P3 is
22862    begin
22863       P2;
22864    end P3;
22865
22866 begin
22867    P3;
22868 exception
22869    when E : others =>
22870       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
22871 end STB;
22872 @end smallexample
22873
22874 @smallexample
22875 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
22876 $ stb
22877
22878 0040149F in stb.p1 at stb.adb:8
22879 004014B7 in stb.p2 at stb.adb:13
22880 004014CF in stb.p3 at stb.adb:18
22881 004015DD in ada.stb at stb.adb:22
22882 00401461 in main at b~stb.adb:168
22883 004011C4 in __mingw_CRTStartup at crt1.c:200
22884 004011F1 in mainCRTStartup at crt1.c:222
22885 77E892A4 in ?? at ??:0
22886 @end smallexample
22887
22888 @noindent
22889 In the above example the ``.\'' syntax in the @command{gnatmake} command
22890 is currently required by @command{addr2line} for files that are in
22891 the current working directory.
22892 Moreover, the exact sequence of linker options may vary from platform
22893 to platform.
22894 The above @option{-largs} section is for Windows platforms. By contrast,
22895 under Unix there is no need for the @option{-largs} section.
22896 Differences across platforms are due to details of linker implementation.
22897
22898 @node Tracebacks From Anywhere in a Program (symbolic)
22899 @subsubsection Tracebacks From Anywhere in a Program
22900
22901 @noindent
22902 It is possible to get a symbolic stack traceback
22903 from anywhere in a program, just as for non-symbolic tracebacks.
22904 The first step is to obtain a non-symbolic
22905 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
22906 information. Here is an example:
22907
22908 @smallexample @c ada
22909 with Ada.Text_IO;
22910 with GNAT.Traceback;
22911 with GNAT.Traceback.Symbolic;
22912
22913 procedure STB is
22914
22915    use Ada;
22916    use GNAT.Traceback;
22917    use GNAT.Traceback.Symbolic;
22918
22919    procedure P1 is
22920       TB  : Tracebacks_Array (1 .. 10);
22921       --  We are asking for a maximum of 10 stack frames.
22922       Len : Natural;
22923       --  Len will receive the actual number of stack frames returned.
22924    begin
22925       Call_Chain (TB, Len);
22926       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
22927    end P1;
22928
22929    procedure P2 is
22930    begin
22931       P1;
22932    end P2;
22933
22934 begin
22935    P2;
22936 end STB;
22937 @end smallexample
22938
22939 @c ******************************
22940 @ifset vms
22941 @node Compatibility with HP Ada
22942 @chapter Compatibility with HP Ada
22943 @cindex Compatibility
22944
22945 @noindent
22946 @cindex DEC Ada
22947 @cindex HP Ada
22948 @cindex Compatibility between GNAT and HP Ada
22949 This chapter compares HP Ada (formerly known as ``DEC Ada'')
22950 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
22951 GNAT is highly compatible
22952 with HP Ada, and it should generally be straightforward to port code
22953 from the HP Ada environment to GNAT. However, there are a few language
22954 and implementation differences of which the user must be aware. These
22955 differences are discussed in this chapter. In
22956 addition, the operating environment and command structure for the
22957 compiler are different, and these differences are also discussed.
22958
22959 For further details on these and other compatibility issues,
22960 see Appendix E of the HP publication
22961 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
22962
22963 Except where otherwise indicated, the description of GNAT for OpenVMS
22964 applies to both the Alpha and I64 platforms.
22965
22966 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
22967 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22968
22969 The discussion in this chapter addresses specifically the implementation
22970 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
22971 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
22972 GNAT always follows the Alpha implementation.
22973
22974 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
22975 attributes are recognized, although only a subset of them can sensibly
22976 be implemented.  The description of pragmas in the
22977 @cite{GNAT Reference Manual} indicates whether or not they are applicable
22978 to non-VMS systems.
22979
22980 @menu
22981 * Ada Language Compatibility::
22982 * Differences in the Definition of Package System::
22983 * Language-Related Features::
22984 * The Package STANDARD::
22985 * The Package SYSTEM::
22986 * Tasking and Task-Related Features::
22987 * Pragmas and Pragma-Related Features::
22988 * Library of Predefined Units::
22989 * Bindings::
22990 * Main Program Definition::
22991 * Implementation-Defined Attributes::
22992 * Compiler and Run-Time Interfacing::
22993 * Program Compilation and Library Management::
22994 * Input-Output::
22995 * Implementation Limits::
22996 * Tools and Utilities::
22997 @end menu
22998
22999 @node Ada Language Compatibility
23000 @section Ada Language Compatibility
23001
23002 @noindent
23003 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
23004 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
23005 with Ada 83, and therefore Ada 83 programs will compile
23006 and run under GNAT with
23007 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
23008 provides details on specific incompatibilities.
23009
23010 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
23011 as well as the pragma @code{ADA_83}, to force the compiler to
23012 operate in Ada 83 mode. This mode does not guarantee complete
23013 conformance to Ada 83, but in practice is sufficient to
23014 eliminate most sources of incompatibilities.
23015 In particular, it eliminates the recognition of the
23016 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
23017 in Ada 83 programs is legal, and handles the cases of packages
23018 with optional bodies, and generics that instantiate unconstrained
23019 types without the use of @code{(<>)}.
23020
23021 @node Differences in the Definition of Package System
23022 @section Differences in the Definition of Package @code{System}
23023
23024 @noindent
23025 An Ada compiler is allowed to add
23026 implementation-dependent declarations to package @code{System}.
23027 In normal mode,
23028 GNAT does not take advantage of this permission, and the version of
23029 @code{System} provided by GNAT exactly matches that defined in the Ada
23030 Reference Manual.
23031
23032 However, HP Ada adds an extensive set of declarations to package
23033 @code{System},
23034 as fully documented in the HP Ada manuals. To minimize changes required
23035 for programs that make use of these extensions, GNAT provides the pragma
23036 @code{Extend_System} for extending the definition of package System. By using:
23037 @cindex pragma @code{Extend_System}
23038 @cindex @code{Extend_System} pragma
23039
23040 @smallexample @c ada
23041 @group
23042 @cartouche
23043 pragma Extend_System (Aux_DEC);
23044 @end cartouche
23045 @end group
23046 @end smallexample
23047
23048 @noindent
23049 the set of definitions in @code{System} is extended to include those in
23050 package @code{System.Aux_DEC}.
23051 @cindex @code{System.Aux_DEC} package
23052 @cindex @code{Aux_DEC} package (child of @code{System})
23053 These definitions are incorporated directly into package @code{System},
23054 as though they had been declared there. For a
23055 list of the declarations added, see the specification of this package,
23056 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
23057 @cindex @file{s-auxdec.ads} file
23058 The pragma @code{Extend_System} is a configuration pragma, which means that
23059 it can be placed in the file @file{gnat.adc}, so that it will automatically
23060 apply to all subsequent compilations. See @ref{Configuration Pragmas},
23061 for further details.
23062
23063 An alternative approach that avoids the use of the non-standard
23064 @code{Extend_System} pragma is to add a context clause to the unit that
23065 references these facilities:
23066
23067 @smallexample @c ada
23068 @cartouche
23069 with System.Aux_DEC;
23070 use  System.Aux_DEC;
23071 @end cartouche
23072 @end smallexample
23073
23074 @noindent
23075 The effect is not quite semantically identical to incorporating
23076 the declarations directly into package @code{System},
23077 but most programs will not notice a difference
23078 unless they use prefix notation (e.g. @code{System.Integer_8})
23079 to reference the entities directly in package @code{System}.
23080 For units containing such references,
23081 the prefixes must either be removed, or the pragma @code{Extend_System}
23082 must be used.
23083
23084 @node Language-Related Features
23085 @section Language-Related Features
23086
23087 @noindent
23088 The following sections highlight differences in types,
23089 representations of types, operations, alignment, and
23090 related topics.
23091
23092 @menu
23093 * Integer Types and Representations::
23094 * Floating-Point Types and Representations::
23095 * Pragmas Float_Representation and Long_Float::
23096 * Fixed-Point Types and Representations::
23097 * Record and Array Component Alignment::
23098 * Address Clauses::
23099 * Other Representation Clauses::
23100 @end menu
23101
23102 @node Integer Types and Representations
23103 @subsection Integer Types and Representations
23104
23105 @noindent
23106 The set of predefined integer types is identical in HP Ada and GNAT.
23107 Furthermore the representation of these integer types is also identical,
23108 including the capability of size clauses forcing biased representation.
23109
23110 In addition,
23111 HP Ada for OpenVMS Alpha systems has defined the
23112 following additional integer types in package @code{System}:
23113
23114 @itemize @bullet
23115
23116 @item
23117 @code{INTEGER_8}
23118
23119 @item
23120 @code{INTEGER_16}
23121
23122 @item
23123 @code{INTEGER_32}
23124
23125 @item
23126 @code{INTEGER_64}
23127
23128 @item
23129 @code{LARGEST_INTEGER}
23130 @end itemize
23131
23132 @noindent
23133 In GNAT, the first four of these types may be obtained from the
23134 standard Ada package @code{Interfaces}.
23135 Alternatively, by use of the pragma @code{Extend_System}, identical
23136 declarations can be referenced directly in package @code{System}.
23137 On both GNAT and HP Ada, the maximum integer size is 64 bits.
23138
23139 @node Floating-Point Types and Representations
23140 @subsection Floating-Point Types and Representations
23141 @cindex Floating-Point types
23142
23143 @noindent
23144 The set of predefined floating-point types is identical in HP Ada and GNAT.
23145 Furthermore the representation of these floating-point
23146 types is also identical. One important difference is that the default
23147 representation for HP Ada is @code{VAX_Float}, but the default representation
23148 for GNAT is IEEE.
23149
23150 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
23151 pragma @code{Float_Representation} as described in the HP Ada
23152 documentation.
23153 For example, the declarations:
23154
23155 @smallexample @c ada
23156 @cartouche
23157 type F_Float is digits 6;
23158 pragma Float_Representation (VAX_Float, F_Float);
23159 @end cartouche
23160 @end smallexample
23161
23162 @noindent
23163 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
23164 format.
23165 This set of declarations actually appears in @code{System.Aux_DEC},
23166 which contains
23167 the full set of additional floating-point declarations provided in
23168 the HP Ada version of package @code{System}.
23169 This and similar declarations may be accessed in a user program
23170 by using pragma @code{Extend_System}. The use of this
23171 pragma, and the related pragma @code{Long_Float} is described in further
23172 detail in the following section.
23173
23174 @node Pragmas Float_Representation and Long_Float
23175 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
23176
23177 @noindent
23178 HP Ada provides the pragma @code{Float_Representation}, which
23179 acts as a program library switch to allow control over
23180 the internal representation chosen for the predefined
23181 floating-point types declared in the package @code{Standard}.
23182 The format of this pragma is as follows:
23183
23184 @smallexample @c ada
23185 @cartouche
23186 pragma Float_Representation(VAX_Float | IEEE_Float);
23187 @end cartouche
23188 @end smallexample
23189
23190 @noindent
23191 This pragma controls the representation of floating-point
23192 types as follows:
23193
23194 @itemize @bullet
23195 @item
23196 @code{VAX_Float} specifies that floating-point
23197 types are represented by default with the VAX system hardware types
23198 @code{F-floating}, @code{D-floating}, @code{G-floating}.
23199 Note that the @code{H-floating}
23200 type was available only on VAX systems, and is not available
23201 in either HP Ada or GNAT.
23202
23203 @item
23204 @code{IEEE_Float} specifies that floating-point
23205 types are represented by default with the IEEE single and
23206 double floating-point types.
23207 @end itemize
23208
23209 @noindent
23210 GNAT provides an identical implementation of the pragma
23211 @code{Float_Representation}, except that it functions as a
23212 configuration pragma. Note that the
23213 notion of configuration pragma corresponds closely to the
23214 HP Ada notion of a program library switch.
23215
23216 When no pragma is used in GNAT, the default is @code{IEEE_Float},
23217 which is different
23218 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
23219 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
23220 advisable to change the format of numbers passed to standard library
23221 routines, and if necessary explicit type conversions may be needed.
23222
23223 The use of @code{IEEE_Float} is recommended in GNAT since it is more
23224 efficient, and (given that it conforms to an international standard)
23225 potentially more portable.
23226 The situation in which @code{VAX_Float} may be useful is in interfacing
23227 to existing code and data that expect the use of @code{VAX_Float}.
23228 In such a situation use the predefined @code{VAX_Float}
23229 types in package @code{System}, as extended by
23230 @code{Extend_System}. For example, use @code{System.F_Float}
23231 to specify the 32-bit @code{F-Float} format.
23232
23233 @noindent
23234 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
23235 to allow control over the internal representation chosen
23236 for the predefined type @code{Long_Float} and for floating-point
23237 type declarations with digits specified in the range 7 .. 15.
23238 The format of this pragma is as follows:
23239
23240 @smallexample @c ada
23241 @cartouche
23242 pragma Long_Float (D_FLOAT | G_FLOAT);
23243 @end cartouche
23244 @end smallexample
23245
23246 @node Fixed-Point Types and Representations
23247 @subsection Fixed-Point Types and Representations
23248
23249 @noindent
23250 On HP Ada for OpenVMS Alpha systems, rounding is
23251 away from zero for both positive and negative numbers.
23252 Therefore, @code{+0.5} rounds to @code{1},
23253 and @code{-0.5} rounds to @code{-1}.
23254
23255 On GNAT the results of operations
23256 on fixed-point types are in accordance with the Ada
23257 rules. In particular, results of operations on decimal
23258 fixed-point types are truncated.
23259
23260 @node Record and Array Component Alignment
23261 @subsection Record and Array Component Alignment
23262
23263 @noindent
23264 On HP Ada for OpenVMS Alpha, all non composite components
23265 are aligned on natural boundaries. For example, 1-byte
23266 components are aligned on byte boundaries, 2-byte
23267 components on 2-byte boundaries, 4-byte components on 4-byte
23268 byte boundaries, and so on. The OpenVMS Alpha hardware
23269 runs more efficiently with naturally aligned data.
23270
23271 On GNAT, alignment rules are compatible
23272 with HP Ada for OpenVMS Alpha.
23273
23274 @node Address Clauses
23275 @subsection Address Clauses
23276
23277 @noindent
23278 In HP Ada and GNAT, address clauses are supported for
23279 objects and imported subprograms.
23280 The predefined type @code{System.Address} is a private type
23281 in both compilers on Alpha OpenVMS, with the same representation
23282 (it is simply a machine pointer). Addition, subtraction, and comparison
23283 operations are available in the standard Ada package
23284 @code{System.Storage_Elements}, or in package @code{System}
23285 if it is extended to include @code{System.Aux_DEC} using a
23286 pragma @code{Extend_System} as previously described.
23287
23288 Note that code that @code{with}'s both this extended package @code{System}
23289 and the package @code{System.Storage_Elements} should not @code{use}
23290 both packages, or ambiguities will result. In general it is better
23291 not to mix these two sets of facilities. The Ada package was
23292 designed specifically to provide the kind of features that HP Ada
23293 adds directly to package @code{System}.
23294
23295 The type @code{System.Address} is a 64-bit integer type in GNAT for
23296 I64 OpenVMS.  For more information,
23297 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
23298
23299 GNAT is compatible with HP Ada in its handling of address
23300 clauses, except for some limitations in
23301 the form of address clauses for composite objects with
23302 initialization. Such address clauses are easily replaced
23303 by the use of an explicitly-defined constant as described
23304 in the Ada Reference Manual (13.1(22)). For example, the sequence
23305 of declarations:
23306
23307 @smallexample @c ada
23308 @cartouche
23309 X, Y : Integer := Init_Func;
23310 Q : String (X .. Y) := "abc";
23311 ...
23312 for Q'Address use Compute_Address;
23313 @end cartouche
23314 @end smallexample
23315
23316 @noindent
23317 will be rejected by GNAT, since the address cannot be computed at the time
23318 that @code{Q} is declared. To achieve the intended effect, write instead:
23319
23320 @smallexample @c ada
23321 @group
23322 @cartouche
23323 X, Y : Integer := Init_Func;
23324 Q_Address : constant Address := Compute_Address;
23325 Q : String (X .. Y) := "abc";
23326 ...
23327 for Q'Address use Q_Address;
23328 @end cartouche
23329 @end group
23330 @end smallexample
23331
23332 @noindent
23333 which will be accepted by GNAT (and other Ada compilers), and is also
23334 compatible with Ada 83. A fuller description of the restrictions
23335 on address specifications is found in the @cite{GNAT Reference Manual}.
23336
23337 @node Other Representation Clauses
23338 @subsection Other Representation Clauses
23339
23340 @noindent
23341 GNAT implements in a compatible manner all the representation
23342 clauses supported by HP Ada. In addition, GNAT
23343 implements the representation clause forms that were introduced in Ada 95,
23344 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
23345
23346 @node The Package STANDARD
23347 @section The Package @code{STANDARD}
23348
23349 @noindent
23350 The package @code{STANDARD}, as implemented by HP Ada, is fully
23351 described in the @cite{Ada Reference Manual} and in the
23352 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
23353 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
23354
23355 In addition, HP Ada supports the Latin-1 character set in
23356 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
23357 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
23358 the type @code{WIDE_CHARACTER}.
23359
23360 The floating-point types supported by GNAT are those
23361 supported by HP Ada, but the defaults are different, and are controlled by
23362 pragmas. See @ref{Floating-Point Types and Representations}, for details.
23363
23364 @node The Package SYSTEM
23365 @section The Package @code{SYSTEM}
23366
23367 @noindent
23368 HP Ada provides a specific version of the package
23369 @code{SYSTEM} for each platform on which the language is implemented.
23370 For the complete specification of the package @code{SYSTEM}, see
23371 Appendix F of the @cite{HP Ada Language Reference Manual}.
23372
23373 On HP Ada, the package @code{SYSTEM} includes the following conversion
23374 functions:
23375 @itemize @bullet
23376 @item @code{TO_ADDRESS(INTEGER)}
23377
23378 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
23379
23380 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
23381
23382 @item @code{TO_INTEGER(ADDRESS)}
23383
23384 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
23385
23386 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
23387               functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
23388 @end itemize
23389
23390 @noindent
23391 By default, GNAT supplies a version of @code{SYSTEM} that matches
23392 the definition given in the @cite{Ada Reference Manual}.
23393 This
23394 is a subset of the HP system definitions, which is as
23395 close as possible to the original definitions. The only difference
23396 is that the definition of @code{SYSTEM_NAME} is different:
23397
23398 @smallexample @c ada
23399 @cartouche
23400 type Name is (SYSTEM_NAME_GNAT);
23401 System_Name : constant Name := SYSTEM_NAME_GNAT;
23402 @end cartouche
23403 @end smallexample
23404
23405 @noindent
23406 Also, GNAT adds the Ada declarations for
23407 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
23408
23409 However, the use of the following pragma causes GNAT
23410 to extend the definition of package @code{SYSTEM} so that it
23411 encompasses the full set of HP-specific extensions,
23412 including the functions listed above:
23413
23414 @smallexample @c ada
23415 @cartouche
23416 pragma Extend_System (Aux_DEC);
23417 @end cartouche
23418 @end smallexample
23419
23420 @noindent
23421 The pragma @code{Extend_System} is a configuration pragma that
23422 is most conveniently placed in the @file{gnat.adc} file. See the
23423 @cite{GNAT Reference Manual} for further details.
23424
23425 HP Ada does not allow the recompilation of the package
23426 @code{SYSTEM}. Instead HP Ada provides several pragmas
23427 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
23428 to modify values in the package @code{SYSTEM}.
23429 On OpenVMS Alpha systems, the pragma
23430 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
23431 its single argument.
23432
23433 GNAT does permit the recompilation of package @code{SYSTEM} using
23434 the special switch @option{-gnatg}, and this switch can be used if
23435 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
23436 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
23437 or @code{MEMORY_SIZE} by any other means.
23438
23439 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
23440 enumeration literal @code{SYSTEM_NAME_GNAT}.
23441
23442 The definitions provided by the use of
23443
23444 @smallexample @c ada
23445 pragma Extend_System (AUX_Dec);
23446 @end smallexample
23447
23448 @noindent
23449 are virtually identical to those provided by the HP Ada 83 package
23450 @code{SYSTEM}. One important difference is that the name of the
23451 @code{TO_ADDRESS}
23452 function for type @code{UNSIGNED_LONGWORD} is changed to
23453 @code{TO_ADDRESS_LONG}.
23454 See the @cite{GNAT Reference Manual} for a discussion of why this change was
23455 necessary.
23456
23457 @noindent
23458 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
23459 is in fact
23460 an extension to Ada 83 not strictly compatible with the reference manual.
23461 GNAT, in order to be exactly compatible with the standard,
23462 does not provide this capability. In HP Ada 83, the
23463 point of this definition is to deal with a call like:
23464
23465 @smallexample @c ada
23466 TO_ADDRESS (16#12777#);
23467 @end smallexample
23468
23469 @noindent
23470 Normally, according to Ada 83 semantics, one would expect this to be
23471 ambiguous, since it matches both the @code{INTEGER} and
23472 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
23473 However, in HP Ada 83, there is no ambiguity, since the
23474 definition using @i{universal_integer} takes precedence.
23475
23476 In GNAT, since the version with @i{universal_integer} cannot be supplied,
23477 it is
23478 not possible to be 100% compatible. Since there are many programs using
23479 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
23480 GNAT was
23481 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
23482 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
23483
23484 @smallexample @c ada
23485 function To_Address (X : Integer) return Address;
23486 pragma Pure_Function (To_Address);
23487
23488 function To_Address_Long (X : Unsigned_Longword) return Address;
23489 pragma Pure_Function (To_Address_Long);
23490 @end smallexample
23491
23492 @noindent
23493 This means that programs using @code{TO_ADDRESS} for
23494 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
23495
23496 @node Tasking and Task-Related Features
23497 @section Tasking and Task-Related Features
23498
23499 @noindent
23500 This section compares the treatment of tasking in GNAT
23501 and in HP Ada for OpenVMS Alpha.
23502 The GNAT description applies to both Alpha and I64 OpenVMS.
23503 For detailed information on tasking in
23504 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
23505 relevant run-time reference manual.
23506
23507 @menu
23508 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
23509 * Assigning Task IDs::
23510 * Task IDs and Delays::
23511 * Task-Related Pragmas::
23512 * Scheduling and Task Priority::
23513 * The Task Stack::
23514 * External Interrupts::
23515 @end menu
23516
23517 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
23518 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
23519
23520 @noindent
23521 On OpenVMS Alpha systems, each Ada task (except a passive
23522 task) is implemented as a single stream of execution
23523 that is created and managed by the kernel. On these
23524 systems, HP Ada tasking support is based on DECthreads,
23525 an implementation of the POSIX standard for threads.
23526
23527 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
23528 code that calls DECthreads routines can be used together.
23529 The interaction between Ada tasks and DECthreads routines
23530 can have some benefits. For example when on OpenVMS Alpha,
23531 HP Ada can call C code that is already threaded.
23532
23533 GNAT uses the facilities of DECthreads,
23534 and Ada tasks are mapped to threads.
23535
23536 @node Assigning Task IDs
23537 @subsection Assigning Task IDs
23538
23539 @noindent
23540 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
23541 the environment task that executes the main program. On
23542 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
23543 that have been created but are not yet activated.
23544
23545 On OpenVMS Alpha systems, task IDs are assigned at
23546 activation. On GNAT systems, task IDs are also assigned at
23547 task creation but do not have the same form or values as
23548 task ID values in HP Ada. There is no null task, and the
23549 environment task does not have a specific task ID value.
23550
23551 @node Task IDs and Delays
23552 @subsection Task IDs and Delays
23553
23554 @noindent
23555 On OpenVMS Alpha systems, tasking delays are implemented
23556 using Timer System Services. The Task ID is used for the
23557 identification of the timer request (the @code{REQIDT} parameter).
23558 If Timers are used in the application take care not to use
23559 @code{0} for the identification, because cancelling such a timer
23560 will cancel all timers and may lead to unpredictable results.
23561
23562 @node Task-Related Pragmas
23563 @subsection Task-Related Pragmas
23564
23565 @noindent
23566 Ada supplies the pragma @code{TASK_STORAGE}, which allows
23567 specification of the size of the guard area for a task
23568 stack. (The guard area forms an area of memory that has no
23569 read or write access and thus helps in the detection of
23570 stack overflow.) On OpenVMS Alpha systems, if the pragma
23571 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
23572 area is created. In the absence of a pragma @code{TASK_STORAGE},
23573 a default guard area is created.
23574
23575 GNAT supplies the following task-related pragmas:
23576
23577 @itemize @bullet
23578 @item  @code{TASK_INFO}
23579
23580               This pragma appears within a task definition and
23581               applies to the task in which it appears. The argument
23582               must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
23583
23584 @item  @code{TASK_STORAGE}
23585
23586               GNAT implements pragma @code{TASK_STORAGE} in the same way as
23587               HP Ada.
23588               Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
23589               @code{SUPPRESS}, and @code{VOLATILE}.
23590 @end itemize
23591 @node Scheduling and Task Priority
23592 @subsection Scheduling and Task Priority
23593
23594 @noindent
23595 HP Ada implements the Ada language requirement that
23596 when two tasks are eligible for execution and they have
23597 different priorities, the lower priority task does not
23598 execute while the higher priority task is waiting. The HP
23599 Ada Run-Time Library keeps a task running until either the
23600 task is suspended or a higher priority task becomes ready.
23601
23602 On OpenVMS Alpha systems, the default strategy is round-
23603 robin with preemption. Tasks of equal priority take turns
23604 at the processor. A task is run for a certain period of
23605 time and then placed at the tail of the ready queue for
23606 its priority level.
23607
23608 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
23609 which can be used to enable or disable round-robin
23610 scheduling of tasks with the same priority.
23611 See the relevant HP Ada run-time reference manual for
23612 information on using the pragmas to control HP Ada task
23613 scheduling.
23614
23615 GNAT follows the scheduling rules of Annex D (Real-Time
23616 Annex) of the @cite{Ada Reference Manual}. In general, this
23617 scheduling strategy is fully compatible with HP Ada
23618 although it provides some additional constraints (as
23619 fully documented in Annex D).
23620 GNAT implements time slicing control in a manner compatible with
23621 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
23622 are identical to the HP Ada 83 pragma of the same name.
23623 Note that it is not possible to mix GNAT tasking and
23624 HP Ada 83 tasking in the same program, since the two run-time
23625 libraries are not compatible.
23626
23627 @node The Task Stack
23628 @subsection The Task Stack
23629
23630 @noindent
23631 In HP Ada, a task stack is allocated each time a
23632 non-passive task is activated. As soon as the task is
23633 terminated, the storage for the task stack is deallocated.
23634 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
23635 a default stack size is used. Also, regardless of the size
23636 specified, some additional space is allocated for task
23637 management purposes. On OpenVMS Alpha systems, at least
23638 one page is allocated.
23639
23640 GNAT handles task stacks in a similar manner. In accordance with
23641 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
23642 an alternative method for controlling the task stack size.
23643 The specification of the attribute @code{T'STORAGE_SIZE} is also
23644 supported in a manner compatible with HP Ada.
23645
23646 @node External Interrupts
23647 @subsection External Interrupts
23648
23649 @noindent
23650 On HP Ada, external interrupts can be associated with task entries.
23651 GNAT is compatible with HP Ada in its handling of external interrupts.
23652
23653 @node Pragmas and Pragma-Related Features
23654 @section Pragmas and Pragma-Related Features
23655
23656 @noindent
23657 Both HP Ada and GNAT supply all language-defined pragmas
23658 as specified by the Ada 83 standard. GNAT also supplies all
23659 language-defined pragmas introduced by Ada 95 and Ada 2005.
23660 In addition, GNAT implements the implementation-defined pragmas
23661 from HP Ada 83.
23662
23663 @itemize @bullet
23664 @item  @code{AST_ENTRY}
23665
23666 @item  @code{COMMON_OBJECT}
23667
23668 @item  @code{COMPONENT_ALIGNMENT}
23669
23670 @item  @code{EXPORT_EXCEPTION}
23671
23672 @item  @code{EXPORT_FUNCTION}
23673
23674 @item  @code{EXPORT_OBJECT}
23675
23676 @item  @code{EXPORT_PROCEDURE}
23677
23678 @item  @code{EXPORT_VALUED_PROCEDURE}
23679
23680 @item  @code{FLOAT_REPRESENTATION}
23681
23682 @item  @code{IDENT}
23683
23684 @item  @code{IMPORT_EXCEPTION}
23685
23686 @item  @code{IMPORT_FUNCTION}
23687
23688 @item  @code{IMPORT_OBJECT}
23689
23690 @item  @code{IMPORT_PROCEDURE}
23691
23692 @item  @code{IMPORT_VALUED_PROCEDURE}
23693
23694 @item  @code{INLINE_GENERIC}
23695
23696 @item  @code{INTERFACE_NAME}
23697
23698 @item  @code{LONG_FLOAT}
23699
23700 @item  @code{MAIN_STORAGE}
23701
23702 @item  @code{PASSIVE}
23703
23704 @item  @code{PSECT_OBJECT}
23705
23706 @item  @code{SHARE_GENERIC}
23707
23708 @item  @code{SUPPRESS_ALL}
23709
23710 @item  @code{TASK_STORAGE}
23711
23712 @item  @code{TIME_SLICE}
23713
23714 @item  @code{TITLE}
23715 @end itemize
23716
23717 @noindent
23718 These pragmas are all fully implemented, with the exception of @code{TITLE},
23719 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
23720 recognized, but which have no
23721 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
23722 use of Ada protected objects. In GNAT, all generics are inlined.
23723
23724 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
23725 a separate subprogram specification which must appear before the
23726 subprogram body.
23727
23728 GNAT also supplies a number of implementation-defined pragmas as follows:
23729 @itemize @bullet
23730 @item  @code{ABORT_DEFER}
23731
23732 @item  @code{ADA_83}
23733
23734 @item  @code{ADA_95}
23735
23736 @item  @code{ADA_05}
23737
23738 @item  @code{ANNOTATE}
23739
23740 @item  @code{ASSERT}
23741
23742 @item  @code{C_PASS_BY_COPY}
23743
23744 @item  @code{CPP_CLASS}
23745
23746 @item  @code{CPP_CONSTRUCTOR}
23747
23748 @item  @code{CPP_DESTRUCTOR}
23749
23750 @item  @code{DEBUG}
23751
23752 @item  @code{EXTEND_SYSTEM}
23753
23754 @item  @code{LINKER_ALIAS}
23755
23756 @item  @code{LINKER_SECTION}
23757
23758 @item  @code{MACHINE_ATTRIBUTE}
23759
23760 @item  @code{NO_RETURN}
23761
23762 @item  @code{PURE_FUNCTION}
23763
23764 @item  @code{SOURCE_FILE_NAME}
23765
23766 @item  @code{SOURCE_REFERENCE}
23767
23768 @item  @code{TASK_INFO}
23769
23770 @item  @code{UNCHECKED_UNION}
23771
23772 @item  @code{UNIMPLEMENTED_UNIT}
23773
23774 @item  @code{UNIVERSAL_DATA}
23775
23776 @item  @code{UNSUPPRESS}
23777
23778 @item  @code{WARNINGS}
23779
23780 @item  @code{WEAK_EXTERNAL}
23781 @end itemize
23782
23783 @noindent
23784 For full details on these GNAT implementation-defined pragmas, see
23785 the GNAT Reference Manual.
23786
23787 @menu
23788 * Restrictions on the Pragma INLINE::
23789 * Restrictions on the Pragma INTERFACE::
23790 * Restrictions on the Pragma SYSTEM_NAME::
23791 @end menu
23792
23793 @node Restrictions on the Pragma INLINE
23794 @subsection Restrictions on Pragma @code{INLINE}
23795
23796 @noindent
23797 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
23798 @itemize @bullet
23799 @item  Parameters cannot have a task type.
23800
23801 @item  Function results cannot be task types, unconstrained
23802 array types, or unconstrained types with discriminants.
23803
23804 @item  Bodies cannot declare the following:
23805 @itemize @bullet
23806 @item  Subprogram body or stub (imported subprogram is allowed)
23807
23808 @item  Tasks
23809
23810 @item  Generic declarations
23811
23812 @item  Instantiations
23813
23814 @item  Exceptions
23815
23816 @item  Access types (types derived from access types allowed)
23817
23818 @item  Array or record types
23819
23820 @item  Dependent tasks
23821
23822 @item  Direct recursive calls of subprogram or containing
23823 subprogram, directly or via a renaming
23824
23825 @end itemize
23826 @end itemize
23827
23828 @noindent
23829 In GNAT, the only restriction on pragma @code{INLINE} is that the
23830 body must occur before the call if both are in the same
23831 unit, and the size must be appropriately small. There are
23832 no other specific restrictions which cause subprograms to
23833 be incapable of being inlined.
23834
23835 @node  Restrictions on the Pragma INTERFACE
23836 @subsection  Restrictions on Pragma @code{INTERFACE}
23837
23838 @noindent
23839 The following restrictions on pragma @code{INTERFACE}
23840 are enforced by both HP Ada and GNAT:
23841 @itemize @bullet
23842 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
23843 Default is the default on OpenVMS Alpha systems.
23844
23845 @item  Parameter passing: Language specifies default
23846 mechanisms but can be overridden with an @code{EXPORT} pragma.
23847
23848 @itemize @bullet
23849 @item  Ada: Use internal Ada rules.
23850
23851 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
23852 record or task type. Result cannot be a string, an
23853 array, or a record.
23854
23855 @item  Fortran: Parameters cannot have a task type. Result cannot
23856 be a string, an array, or a record.
23857 @end itemize
23858 @end itemize
23859
23860 @noindent
23861 GNAT is entirely upwards compatible with HP Ada, and in addition allows
23862 record parameters for all languages.
23863
23864 @node  Restrictions on the Pragma SYSTEM_NAME
23865 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
23866
23867 @noindent
23868 For HP Ada for OpenVMS Alpha, the enumeration literal
23869 for the type @code{NAME} is @code{OPENVMS_AXP}.
23870 In GNAT, the enumeration
23871 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
23872
23873 @node  Library of Predefined Units
23874 @section  Library of Predefined Units
23875
23876 @noindent
23877 A library of predefined units is provided as part of the
23878 HP Ada and GNAT implementations. HP Ada does not provide
23879 the package @code{MACHINE_CODE} but instead recommends importing
23880 assembler code.
23881
23882 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
23883 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
23884 version.
23885 The HP Ada Predefined Library units are modified to remove post-Ada 83
23886 incompatibilities and to make them interoperable with GNAT
23887 (@pxref{Changes to DECLIB}, for details).
23888 The units are located in the @file{DECLIB} directory.
23889
23890 The GNAT RTL is contained in
23891 the @file{ADALIB} directory, and
23892 the default search path is set up to find @code{DECLIB} units in preference
23893 to @code{ADALIB} units with the same name (@code{TEXT_IO},
23894 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
23895
23896 @menu
23897 * Changes to DECLIB::
23898 @end menu
23899
23900 @node Changes to DECLIB
23901 @subsection Changes to @code{DECLIB}
23902
23903 @noindent
23904 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
23905 compatibility are minor and include the following:
23906
23907 @itemize @bullet
23908 @item  Adjusting the location of pragmas and record representation
23909 clauses to obey Ada 95 (and thus Ada 2005) rules
23910
23911 @item  Adding the proper notation to generic formal parameters
23912 that take unconstrained types in instantiation
23913
23914 @item  Adding pragma @code{ELABORATE_BODY} to package specifications
23915 that have package bodies not otherwise allowed
23916
23917 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
23918 ``@code{PROTECTD}''.
23919 Currently these are found only in the @code{STARLET} package spec.
23920
23921 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
23922 where the address size is constrained to 32 bits.
23923 @end itemize
23924
23925 @noindent
23926 None of the above changes is visible to users.
23927
23928 @node Bindings
23929 @section Bindings
23930
23931 @noindent
23932 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
23933 @itemize @bullet
23934
23935 @item  Command Language Interpreter (CLI interface)
23936
23937 @item  DECtalk Run-Time Library (DTK interface)
23938
23939 @item  Librarian utility routines (LBR interface)
23940
23941 @item  General Purpose Run-Time Library (LIB interface)
23942
23943 @item  Math Run-Time Library (MTH interface)
23944
23945 @item  National Character Set Run-Time Library (NCS interface)
23946
23947 @item  Compiled Code Support Run-Time Library (OTS interface)
23948
23949 @item  Parallel Processing Run-Time Library (PPL interface)
23950
23951 @item  Screen Management Run-Time Library (SMG interface)
23952
23953 @item  Sort Run-Time Library (SOR interface)
23954
23955 @item  String Run-Time Library (STR interface)
23956
23957 @item STARLET System Library
23958 @findex Starlet
23959
23960 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
23961
23962 @item  X Windows Toolkit (XT interface)
23963
23964 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
23965 @end itemize
23966
23967 @noindent
23968 GNAT provides implementations of these HP bindings in the @code{DECLIB}
23969 directory, on both the Alpha and I64 OpenVMS platforms.
23970
23971 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
23972 in the
23973 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
23974 A pragma @code{Linker_Options} has been added to packages @code{Xm},
23975 @code{Xt}, and @code{X_Lib}
23976 causing the default X/Motif sharable image libraries to be linked in. This
23977 is done via options files named @file{xm.opt}, @file{xt.opt}, and
23978 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
23979
23980 It may be necessary to edit these options files to update or correct the
23981 library names if, for example, the newer X/Motif bindings from
23982 @file{ADA$EXAMPLES}
23983 had been (previous to installing GNAT) copied and renamed to supersede the
23984 default @file{ADA$PREDEFINED} versions.
23985
23986 @menu
23987 * Shared Libraries and Options Files::
23988 * Interfaces to C::
23989 @end menu
23990
23991 @node Shared Libraries and Options Files
23992 @subsection Shared Libraries and Options Files
23993
23994 @noindent
23995 When using the HP Ada
23996 predefined X and Motif bindings, the linking with their sharable images is
23997 done automatically by @command{GNAT LINK}.
23998 When using other X and Motif bindings, you need
23999 to add the corresponding sharable images to the command line for
24000 @code{GNAT LINK}. When linking with shared libraries, or with
24001 @file{.OPT} files, you must
24002 also add them to the command line for @command{GNAT LINK}.
24003
24004 A shared library to be used with GNAT is built in the same way as other
24005 libraries under VMS. The VMS Link command can be used in standard fashion.
24006
24007 @node Interfaces to C
24008 @subsection Interfaces to C
24009
24010 @noindent
24011 HP Ada
24012 provides the following Ada types and operations:
24013
24014 @itemize @bullet
24015 @item C types package (@code{C_TYPES})
24016
24017 @item C strings (@code{C_TYPES.NULL_TERMINATED})
24018
24019 @item Other_types (@code{SHORT_INT})
24020 @end itemize
24021
24022 @noindent
24023 Interfacing to C with GNAT, you can use the above approach
24024 described for HP Ada or the facilities of Annex B of
24025 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
24026 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
24027 information, see the section ``Interfacing to C'' in the
24028 @cite{GNAT Reference Manual}.
24029
24030 The @option{-gnatF} qualifier forces default and explicit
24031 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
24032 to be uppercased for compatibility with the default behavior
24033 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
24034
24035 @node Main Program Definition
24036 @section Main Program Definition
24037
24038 @noindent
24039 The following section discusses differences in the
24040 definition of main programs on HP Ada and GNAT.
24041 On HP Ada, main programs are defined to meet the
24042 following conditions:
24043 @itemize @bullet
24044 @item  Procedure with no formal parameters (returns @code{0} upon
24045        normal completion)
24046
24047 @item  Procedure with no formal parameters (returns @code{42} when
24048        an unhandled exception is raised)
24049
24050 @item  Function with no formal parameters whose returned value
24051        is of a discrete type
24052
24053 @item  Procedure with one @code{out} formal of a discrete type for
24054        which a specification of pragma @code{EXPORT_VALUED_PROCEDURE}
24055        is given.
24056
24057 @end itemize
24058
24059 @noindent
24060 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
24061 a main function or main procedure returns a discrete
24062 value whose size is less than 64 bits (32 on VAX systems),
24063 the value is zero- or sign-extended as appropriate.
24064 On GNAT, main programs are defined as follows:
24065 @itemize @bullet
24066 @item  Must be a non-generic, parameterless subprogram that
24067 is either a procedure or function returning an Ada
24068 @code{STANDARD.INTEGER} (the predefined type)
24069
24070 @item  Cannot be a generic subprogram or an instantiation of a
24071 generic subprogram
24072 @end itemize
24073
24074 @node Implementation-Defined Attributes
24075 @section Implementation-Defined Attributes
24076
24077 @noindent
24078 GNAT provides all HP Ada implementation-defined
24079 attributes.
24080
24081 @node Compiler and Run-Time Interfacing
24082 @section Compiler and Run-Time Interfacing
24083
24084 @noindent
24085 HP Ada provides the following qualifiers to pass options to the linker
24086 (ACS LINK):
24087 @itemize @bullet
24088 @item  @option{/WAIT} and @option{/SUBMIT}
24089
24090 @item  @option{/COMMAND}
24091
24092 @item  @option{/[NO]MAP}
24093
24094 @item  @option{/OUTPUT=@i{file-spec}}
24095
24096 @item  @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
24097 @end itemize
24098
24099 @noindent
24100 To pass options to the linker, GNAT provides the following
24101 switches:
24102
24103 @itemize @bullet
24104 @item   @option{/EXECUTABLE=@i{exec-name}}
24105
24106 @item   @option{/VERBOSE}
24107
24108 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
24109 @end itemize
24110
24111 @noindent
24112 For more information on these switches, see
24113 @ref{Switches for gnatlink}.
24114 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
24115 to control optimization. HP Ada also supplies the
24116 following pragmas:
24117 @itemize @bullet
24118 @item  @code{OPTIMIZE}
24119
24120 @item  @code{INLINE}
24121
24122 @item  @code{INLINE_GENERIC}
24123
24124 @item  @code{SUPPRESS_ALL}
24125
24126 @item  @code{PASSIVE}
24127 @end itemize
24128
24129 @noindent
24130 In GNAT, optimization is controlled strictly by command
24131 line parameters, as described in the corresponding section of this guide.
24132 The HP pragmas for control of optimization are
24133 recognized but ignored.
24134
24135 Note that in GNAT, the default is optimization off, whereas in HP Ada
24136 the default is that optimization is turned on.
24137
24138 @node Program Compilation and Library Management
24139 @section Program Compilation and Library Management
24140
24141 @noindent
24142 HP Ada and GNAT provide a comparable set of commands to
24143 build programs. HP Ada also provides a program library,
24144 which is a concept that does not exist on GNAT. Instead,
24145 GNAT provides directories of sources that are compiled as
24146 needed.
24147
24148 The following table summarizes
24149 the HP Ada commands and provides
24150 equivalent GNAT commands. In this table, some GNAT
24151 equivalents reflect the fact that GNAT does not use the
24152 concept of a program library. Instead, it uses a model
24153 in which collections of source and object files are used
24154 in a manner consistent with other languages like C and
24155 Fortran. Therefore, standard system file commands are used
24156 to manipulate these elements. Those GNAT commands are marked with
24157 an asterisk.
24158 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
24159
24160 @need 1500
24161 @multitable @columnfractions .35 .65
24162
24163 @item @emph{HP Ada Command}
24164 @tab @emph{GNAT Equivalent / Description}
24165
24166 @item @command{ADA}
24167 @tab @command{GNAT COMPILE}@*
24168 Invokes the compiler to compile one or more Ada source files.
24169
24170 @item @command{ACS ATTACH}@*
24171 @tab [No equivalent]@*
24172 Switches control of terminal from current process running the program
24173 library manager.
24174
24175 @item @command{ACS CHECK}
24176 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
24177 Forms the execution closure of one
24178 or more compiled units and checks completeness and currency.
24179
24180 @item @command{ACS COMPILE}
24181 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
24182 Forms the execution closure of one or
24183 more specified units, checks completeness and currency,
24184 identifies units that have revised source files, compiles same,
24185 and recompiles units that are or will become obsolete.
24186 Also completes incomplete generic instantiations.
24187
24188 @item @command{ACS COPY FOREIGN}
24189 @tab Copy (*)@*
24190 Copies a foreign object file into the program library as a
24191 library unit body.
24192
24193 @item @command{ACS COPY UNIT}
24194 @tab Copy (*)@*
24195 Copies a compiled unit from one program library to another.
24196
24197 @item @command{ACS CREATE LIBRARY}
24198 @tab Create /directory (*)@*
24199 Creates a program library.
24200
24201 @item @command{ACS CREATE SUBLIBRARY}
24202 @tab Create /directory (*)@*
24203 Creates a program sublibrary.
24204
24205 @item @command{ACS DELETE LIBRARY}
24206 @tab @*
24207 Deletes a program library and its contents.
24208
24209 @item @command{ACS DELETE SUBLIBRARY}
24210 @tab @*
24211 Deletes a program sublibrary and its contents.
24212
24213 @item @command{ACS DELETE UNIT}
24214 @tab Delete file (*)@*
24215 On OpenVMS systems, deletes one or more compiled units from
24216 the current program library.
24217
24218 @item @command{ACS DIRECTORY}
24219 @tab Directory (*)@*
24220 On OpenVMS systems, lists units contained in the current
24221 program library.
24222
24223 @item @command{ACS ENTER FOREIGN}
24224 @tab Copy (*)@*
24225 Allows the import of a foreign body as an Ada library
24226 specification and enters a reference to a pointer.
24227
24228 @item @command{ACS ENTER UNIT}
24229 @tab Copy (*)@*
24230 Enters a reference (pointer) from the current program library to
24231 a unit compiled into another program library.
24232
24233 @item @command{ACS EXIT}
24234 @tab [No equivalent]@*
24235 Exits from the program library manager.
24236
24237 @item @command{ACS EXPORT}
24238 @tab Copy (*)@*
24239 Creates an object file that contains system-specific object code
24240 for one or more units. With GNAT, object files can simply be copied
24241 into the desired directory.
24242
24243 @item @command{ACS EXTRACT SOURCE}
24244 @tab Copy (*)@*
24245 Allows access to the copied source file for each Ada compilation unit
24246
24247 @item @command{ACS HELP}
24248 @tab @command{HELP GNAT}@*
24249 Provides online help.
24250
24251 @item @command{ACS LINK}
24252 @tab @command{GNAT LINK}@*
24253 Links an object file containing Ada units into an executable file.
24254
24255 @item @command{ACS LOAD}
24256 @tab Copy (*)@*
24257 Loads (partially compiles) Ada units into the program library.
24258 Allows loading a program from a collection of files into a library
24259 without knowing the relationship among units.
24260
24261 @item @command{ACS MERGE}
24262 @tab Copy (*)@*
24263 Merges into the current program library, one or more units from
24264 another library where they were modified.
24265
24266 @item @command{ACS RECOMPILE}
24267 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
24268 Recompiles from   external or copied source files any obsolete
24269 unit in the closure. Also, completes any incomplete generic
24270 instantiations.
24271
24272 @item @command{ACS REENTER}
24273 @tab @command{GNAT MAKE}@*
24274 Reenters current references to units compiled after last entered
24275 with the @command{ACS ENTER UNIT} command.
24276
24277 @item @command{ACS SET LIBRARY}
24278 @tab Set default (*)@*
24279 Defines a program library to be the compilation context as well
24280 as the target library for compiler output and commands in general.
24281
24282 @item @command{ACS SET PRAGMA}
24283 @tab Edit @file{gnat.adc} (*)@*
24284 Redefines specified  values of the library characteristics
24285 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
24286 and @code{Float_Representation}.
24287
24288 @item @command{ACS SET SOURCE}
24289 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
24290 Defines the source file search list for the @command{ACS COMPILE} command.
24291
24292 @item @command{ACS SHOW LIBRARY}
24293 @tab Directory (*)@*
24294 Lists information about one or more program libraries.
24295
24296 @item @command{ACS SHOW PROGRAM}
24297 @tab [No equivalent]@*
24298 Lists information about the execution closure of one or
24299 more units in the program library.
24300
24301 @item @command{ACS SHOW SOURCE}
24302 @tab Show logical @code{ADA_INCLUDE_PATH}@*
24303 Shows the source file search used when compiling units.
24304
24305 @item @command{ACS SHOW VERSION}
24306 @tab Compile with @option{VERBOSE} option
24307 Displays the version number of the compiler and program library
24308 manager used.
24309
24310 @item @command{ACS SPAWN}
24311 @tab [No equivalent]@*
24312 Creates a subprocess of the current process (same as @command{DCL SPAWN}
24313 command).
24314
24315 @item @command{ACS VERIFY}
24316 @tab [No equivalent]@*
24317 Performs a series of consistency checks on a program library to
24318 determine whether the library structure and library files are in
24319 valid form.
24320 @end multitable
24321
24322 @noindent
24323
24324 @node Input-Output
24325 @section Input-Output
24326
24327 @noindent
24328 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
24329 Management Services (RMS) to perform operations on
24330 external files.
24331
24332 @noindent
24333 HP Ada and GNAT predefine an identical set of input-
24334 output packages. To make the use of the
24335 generic @code{TEXT_IO} operations more convenient, HP Ada
24336 provides predefined library packages that instantiate the
24337 integer and floating-point operations for the predefined
24338 integer and floating-point types as shown in the following table.
24339
24340 @multitable @columnfractions .45 .55
24341 @item @emph{Package Name} @tab Instantiation
24342
24343 @item @code{INTEGER_TEXT_IO}
24344 @tab @code{INTEGER_IO(INTEGER)}
24345
24346 @item @code{SHORT_INTEGER_TEXT_IO}
24347 @tab @code{INTEGER_IO(SHORT_INTEGER)}
24348
24349 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
24350 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
24351
24352 @item @code{FLOAT_TEXT_IO}
24353 @tab @code{FLOAT_IO(FLOAT)}
24354
24355 @item @code{LONG_FLOAT_TEXT_IO}
24356 @tab @code{FLOAT_IO(LONG_FLOAT)}
24357 @end multitable
24358
24359 @noindent
24360 The HP Ada predefined packages and their operations
24361 are implemented using OpenVMS Alpha files and input-output
24362 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
24363 Familiarity with the following is recommended:
24364 @itemize @bullet
24365 @item  RMS file organizations and access methods
24366
24367 @item  OpenVMS file specifications and directories
24368
24369 @item  OpenVMS File Definition Language (FDL)
24370 @end itemize
24371
24372 @noindent
24373 GNAT provides I/O facilities that are completely
24374 compatible with HP Ada. The distribution includes the
24375 standard HP Ada versions of all I/O packages, operating
24376 in a manner compatible with HP Ada. In particular, the
24377 following packages are by default the HP Ada (Ada 83)
24378 versions of these packages rather than the renamings
24379 suggested in Annex J of the Ada Reference Manual:
24380 @itemize @bullet
24381 @item  @code{TEXT_IO}
24382
24383 @item  @code{SEQUENTIAL_IO}
24384
24385 @item  @code{DIRECT_IO}
24386 @end itemize
24387
24388 @noindent
24389 The use of the standard child package syntax (for
24390 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
24391 packages.
24392 GNAT provides HP-compatible predefined instantiations
24393 of the @code{TEXT_IO} packages, and also
24394 provides the standard predefined instantiations required
24395 by the @cite{Ada Reference Manual}.
24396
24397 For further information on how GNAT interfaces to the file
24398 system or how I/O is implemented in programs written in
24399 mixed languages, see the chapter ``Implementation of the
24400 Standard I/O'' in the @cite{GNAT Reference Manual}.
24401 This chapter covers the following:
24402 @itemize @bullet
24403 @item  Standard I/O packages
24404
24405 @item  @code{FORM} strings
24406
24407 @item  @code{ADA.DIRECT_IO}
24408
24409 @item  @code{ADA.SEQUENTIAL_IO}
24410
24411 @item  @code{ADA.TEXT_IO}
24412
24413 @item  Stream pointer positioning
24414
24415 @item  Reading and writing non-regular files
24416
24417 @item  @code{GET_IMMEDIATE}
24418
24419 @item  Treating @code{TEXT_IO} files as streams
24420
24421 @item  Shared files
24422
24423 @item  Open modes
24424 @end itemize
24425
24426 @node Implementation Limits
24427 @section Implementation Limits
24428
24429 @noindent
24430 The following table lists implementation limits for HP Ada
24431 and GNAT systems.
24432 @multitable @columnfractions .60 .20 .20
24433 @sp 1
24434 @item  @emph{Compilation Parameter}
24435 @tab   @emph{HP Ada}
24436 @tab   @emph{GNAT}
24437 @sp 1
24438
24439 @item  In a subprogram or entry  declaration, maximum number of
24440        formal parameters that are of an unconstrained record type
24441 @tab   32
24442 @tab   No set limit
24443 @sp 1
24444
24445 @item  Maximum identifier length (number of characters)
24446 @tab   255
24447 @tab   32766
24448 @sp 1
24449
24450 @item  Maximum number of characters in a source line
24451 @tab   255
24452 @tab   32766
24453 @sp 1
24454
24455 @item  Maximum collection size   (number of bytes)
24456 @tab   2**31-1
24457 @tab   2**31-1
24458 @sp 1
24459
24460 @item  Maximum number of discriminants for a record type
24461 @tab   245
24462 @tab   No set limit
24463 @sp 1
24464
24465 @item  Maximum number of formal parameters in an entry or
24466        subprogram declaration
24467 @tab   246
24468 @tab    No set limit
24469 @sp 1
24470
24471 @item  Maximum number of dimensions in an array type
24472 @tab   255
24473 @tab   No set limit
24474 @sp 1
24475
24476 @item  Maximum number of library  units and subunits in a compilation.
24477 @tab   4095
24478 @tab   No set limit
24479 @sp 1
24480
24481 @item  Maximum number of library units and subunits in an execution.
24482 @tab   16383
24483 @tab   No set limit
24484 @sp 1
24485
24486 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
24487        or @code{PSECT_OBJECT}
24488 @tab   32757
24489 @tab   No set limit
24490 @sp 1
24491
24492 @item  Maximum number of enumeration literals in an enumeration type
24493        definition
24494 @tab   65535
24495 @tab   No set limit
24496 @sp 1
24497
24498 @item  Maximum number of lines in a source file
24499 @tab   65534
24500 @tab   No set limit
24501 @sp 1
24502
24503 @item  Maximum number of bits in any object
24504 @tab   2**31-1
24505 @tab   2**31-1
24506 @sp 1
24507
24508 @item  Maximum size of the static portion of a stack frame (approximate)
24509 @tab   2**31-1
24510 @tab   2**31-1
24511 @end multitable
24512
24513 @node Tools and Utilities
24514 @section Tools and Utilities
24515
24516 @noindent
24517 The following table lists some of the OpenVMS development tools
24518 available for HP Ada, and the corresponding tools for
24519 use with @value{EDITION} on Alpha and I64 platforms.
24520 Aside from the debugger, all the OpenVMS tools identified are part
24521 of the DECset package.
24522
24523 @iftex
24524 @c Specify table in TeX since Texinfo does a poor job
24525 @tex
24526 \smallskip
24527 \smallskip
24528 \settabs\+Language-Sensitive Editor\quad
24529    &Product with HP Ada\quad
24530    &\cr
24531 \+\it Tool
24532    &\it Product with HP Ada
24533    & \it Product with GNAT Pro\cr
24534 \smallskip
24535 \+Code Management System
24536    &HP CMS
24537    & HP CMS\cr
24538 \smallskip
24539 \+Language-Sensitive Editor
24540    &HP LSE
24541    & emacs or HP LSE (Alpha)\cr
24542 \+
24543    &
24544    & HP LSE (I64)\cr
24545 \smallskip
24546 \+Debugger
24547    &OpenVMS Debug
24548    & gdb (Alpha),\cr
24549 \+
24550    &
24551    & OpenVMS Debug (I64)\cr
24552 \smallskip
24553 \+Source Code Analyzer /
24554    &HP SCA
24555    & GNAT XREF\cr
24556 \+Cross Referencer
24557    &
24558    &\cr
24559 \smallskip
24560 \+Test Manager
24561    &HP Digital Test
24562    & HP DTM\cr
24563 \+
24564    &Manager (DTM)
24565    &\cr
24566 \smallskip
24567 \+Performance and
24568    & HP PCA
24569    & HP PCA\cr
24570 \+Coverage Analyzer
24571    &
24572    &\cr
24573 \smallskip
24574 \+Module Management
24575    & HP MMS
24576    & Not applicable\cr
24577 \+ System
24578    &
24579    &\cr
24580 \smallskip
24581 \smallskip
24582 @end tex
24583 @end iftex
24584
24585 @ifnottex
24586 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
24587 @c the TeX version above for the printed version
24588 @flushleft
24589 @c @multitable @columnfractions .3 .4 .4
24590 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
24591 @item @i{Tool}
24592  @tab @i{Tool with HP Ada}
24593  @tab @i{Tool with @value{EDITION}}
24594 @item Code Management@*System
24595  @tab HP CMS
24596  @tab HP CMS
24597 @item Language-Sensitive@*Editor
24598  @tab HP LSE
24599  @tab emacs or HP LSE (Alpha)
24600 @item
24601  @tab
24602  @tab HP LSE (I64)
24603 @item Debugger
24604  @tab OpenVMS Debug
24605  @tab gdb (Alpha),
24606 @item
24607  @tab
24608  @tab OpenVMS Debug (I64)
24609 @item Source Code Analyzer /@*Cross Referencer
24610  @tab HP SCA
24611  @tab GNAT XREF
24612 @item Test Manager
24613  @tab HP Digital Test@*Manager (DTM)
24614  @tab HP DTM
24615 @item Performance and@*Coverage Analyzer
24616  @tab HP PCA
24617  @tab HP PCA
24618 @item Module Management@*System
24619  @tab HP MMS
24620  @tab Not applicable
24621 @end multitable
24622 @end flushleft
24623 @end ifnottex
24624
24625 @end ifset
24626
24627 @c **************************************
24628 @node Platform-Specific Information for the Run-Time Libraries
24629 @appendix Platform-Specific Information for the Run-Time Libraries
24630 @cindex Tasking and threads libraries
24631 @cindex Threads libraries and tasking
24632 @cindex Run-time libraries (platform-specific information)
24633
24634 @noindent
24635 The GNAT run-time implementation may vary with respect to both the
24636 underlying threads library and the exception handling scheme.
24637 For threads support, one or more of the following are supplied:
24638 @itemize @bullet
24639 @item @b{native threads library}, a binding to the thread package from
24640 the underlying operating system
24641
24642 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
24643 POSIX thread package
24644 @end itemize
24645
24646 @noindent
24647 For exception handling, either or both of two models are supplied:
24648 @itemize @bullet
24649 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
24650 Most programs should experience a substantial speed improvement by
24651 being compiled with a ZCX run-time.
24652 This is especially true for
24653 tasking applications or applications with many exception handlers.}
24654 @cindex Zero-Cost Exceptions
24655 @cindex ZCX (Zero-Cost Exceptions)
24656 which uses binder-generated tables that
24657 are interrogated at run time to locate a handler
24658
24659 @item @b{setjmp / longjmp} (``SJLJ''),
24660 @cindex setjmp/longjmp Exception Model
24661 @cindex SJLJ (setjmp/longjmp Exception Model)
24662 which uses dynamically-set data to establish
24663 the set of handlers
24664 @end itemize
24665
24666 @noindent
24667 This appendix summarizes which combinations of threads and exception support
24668 are supplied on various GNAT platforms.
24669 It then shows how to select a particular library either
24670 permanently or temporarily,
24671 explains the properties of (and tradeoffs among) the various threads
24672 libraries, and provides some additional
24673 information about several specific platforms.
24674
24675 @menu
24676 * Summary of Run-Time Configurations::
24677 * Specifying a Run-Time Library::
24678 * Choosing the Scheduling Policy::
24679 * Solaris-Specific Considerations::
24680 * Linux-Specific Considerations::
24681 * AIX-Specific Considerations::
24682 @end menu
24683
24684 @node Summary of Run-Time Configurations
24685 @section Summary of Run-Time Configurations
24686
24687 @multitable @columnfractions .30 .70
24688 @item @b{alpha-openvms}
24689 @item @code{@ @ }@i{rts-native (default)}
24690 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
24691 @item @code{@ @ @ @ }Exceptions @tab ZCX
24692 @*
24693 @item @b{alpha-tru64}
24694 @item @code{@ @ }@i{rts-native (default)}
24695 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
24696 @item @code{@ @ @ @ }Exceptions @tab ZCX
24697 @*
24698 @item @code{@ @ }@i{rts-sjlj}
24699 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
24700 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24701 @*
24702 @item @b{ia64-hp_linux}
24703 @item @code{@ @ }@i{rts-native (default)}
24704 @item @code{@ @ @ @ }Tasking    @tab pthread library
24705 @item @code{@ @ @ @ }Exceptions @tab ZCX
24706 @*
24707 @item @b{ia64-hpux}
24708 @item @code{@ @ }@i{rts-native (default)}
24709 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
24710 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24711 @*
24712 @item @b{ia64-openvms}
24713 @item @code{@ @ }@i{rts-native (default)}
24714 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
24715 @item @code{@ @ @ @ }Exceptions @tab ZCX
24716 @*
24717 @item @b{ia64-sgi_linux}
24718 @item @code{@ @ }@i{rts-native (default)}
24719 @item @code{@ @ @ @ }Tasking    @tab pthread library
24720 @item @code{@ @ @ @ }Exceptions @tab ZCX
24721 @*
24722 @item @b{mips-irix}
24723 @item @code{@ @ }@i{rts-native (default)}
24724 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
24725 @item @code{@ @ @ @ }Exceptions @tab ZCX
24726 @*
24727 @item @b{pa-hpux}
24728 @item @code{@ @ }@i{rts-native (default)}
24729 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
24730 @item @code{@ @ @ @ }Exceptions @tab ZCX
24731 @*
24732 @item @code{@ @ }@i{rts-sjlj}
24733 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
24734 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24735 @*
24736 @item @b{ppc-aix}
24737 @item @code{@ @ }@i{rts-native (default)}
24738 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
24739 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24740 @*
24741 @item @b{ppc-darwin}
24742 @item @code{@ @ }@i{rts-native (default)}
24743 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
24744 @item @code{@ @ @ @ }Exceptions @tab ZCX
24745 @*
24746 @item @b{sparc-solaris}  @tab
24747 @item @code{@ @ }@i{rts-native (default)}
24748 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
24749 @item @code{@ @ @ @ }Exceptions @tab ZCX
24750 @*
24751 @item @code{@ @ }@i{rts-pthread}
24752 @item @code{@ @ @ @ }Tasking    @tab pthread library
24753 @item @code{@ @ @ @ }Exceptions @tab ZCX
24754 @*
24755 @item @code{@ @ }@i{rts-sjlj}
24756 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
24757 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24758 @*
24759 @item @b{sparc64-solaris}  @tab
24760 @item @code{@ @ }@i{rts-native (default)}
24761 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
24762 @item @code{@ @ @ @ }Exceptions @tab ZCX
24763 @*
24764 @item @b{x86-linux}
24765 @item @code{@ @ }@i{rts-native (default)}
24766 @item @code{@ @ @ @ }Tasking    @tab pthread library
24767 @item @code{@ @ @ @ }Exceptions @tab ZCX
24768 @*
24769 @item @code{@ @ }@i{rts-sjlj}
24770 @item @code{@ @ @ @ }Tasking    @tab pthread library
24771 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24772 @*
24773 @item @b{x86-lynx}
24774 @item @code{@ @ }@i{rts-native (default)}
24775 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
24776 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24777 @*
24778 @item @b{x86-solaris}
24779 @item @code{@ @ }@i{rts-native (default)}
24780 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
24781 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24782 @*
24783 @item @b{x86-windows}
24784 @item @code{@ @ }@i{rts-native (default)}
24785 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
24786 @item @code{@ @ @ @ }Exceptions @tab ZCX
24787 @*
24788 @item @code{@ @ }@i{rts-sjlj (default)}
24789 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
24790 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24791 @*
24792 @item @b{x86_64-linux}
24793 @item @code{@ @ }@i{rts-native (default)}
24794 @item @code{@ @ @ @ }Tasking    @tab pthread library
24795 @item @code{@ @ @ @ }Exceptions @tab ZCX
24796 @*
24797 @item @code{@ @ }@i{rts-sjlj}
24798 @item @code{@ @ @ @ }Tasking    @tab pthread library
24799 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24800 @*
24801 @end multitable
24802
24803 @node Specifying a Run-Time Library
24804 @section Specifying a Run-Time Library
24805
24806 @noindent
24807 The @file{adainclude} subdirectory containing the sources of the GNAT
24808 run-time library, and the @file{adalib} subdirectory containing the
24809 @file{ALI} files and the static and/or shared GNAT library, are located
24810 in the gcc target-dependent area:
24811
24812 @smallexample
24813 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
24814 @end smallexample
24815
24816 @noindent
24817 As indicated above, on some platforms several run-time libraries are supplied.
24818 These libraries are installed in the target dependent area and
24819 contain a complete source and binary subdirectory. The detailed description
24820 below explains the differences between the different libraries in terms of
24821 their thread support.
24822
24823 The default run-time library (when GNAT is installed) is @emph{rts-native}.
24824 This default run time is selected by the means of soft links.
24825 For example on x86-linux:
24826
24827 @smallexample
24828 @group
24829  $(target-dir)
24830      |
24831      +--- adainclude----------+
24832      |                        |
24833      +--- adalib-----------+  |
24834      |                     |  |
24835      +--- rts-native       |  |
24836      |    |                |  |
24837      |    +--- adainclude <---+
24838      |    |                |
24839      |    +--- adalib <----+
24840      |
24841      +--- rts-sjlj
24842           |
24843           +--- adainclude
24844           |
24845           +--- adalib
24846 @end group
24847 @end smallexample
24848
24849 @noindent
24850 If the @i{rts-sjlj} library is to be selected on a permanent basis,
24851 these soft links can be modified with the following commands:
24852
24853 @smallexample
24854 $ cd $target
24855 $ rm -f adainclude adalib
24856 $ ln -s rts-sjlj/adainclude adainclude
24857 $ ln -s rts-sjlj/adalib adalib
24858 @end smallexample
24859
24860 @noindent
24861 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
24862 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
24863 @file{$target/ada_object_path}.
24864
24865 Selecting another run-time library temporarily can be
24866 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
24867 @cindex @option{--RTS} option
24868
24869 @node Choosing the Scheduling Policy
24870 @section Choosing the Scheduling Policy
24871
24872 @noindent
24873 When using a POSIX threads implementation, you have a choice of several
24874 scheduling policies: @code{SCHED_FIFO},
24875 @cindex @code{SCHED_FIFO} scheduling policy
24876 @code{SCHED_RR}
24877 @cindex @code{SCHED_RR} scheduling policy
24878 and @code{SCHED_OTHER}.
24879 @cindex @code{SCHED_OTHER} scheduling policy
24880 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
24881 or @code{SCHED_RR} requires special (e.g., root) privileges.
24882
24883 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
24884 @code{SCHED_FIFO},
24885 @cindex @code{SCHED_FIFO} scheduling policy
24886 you can use one of the following:
24887
24888 @itemize @bullet
24889 @item
24890 @code{pragma Time_Slice (0.0)}
24891 @cindex pragma Time_Slice
24892 @item
24893 the corresponding binder option @option{-T0}
24894 @cindex @option{-T0} option
24895 @item
24896 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24897 @cindex pragma Task_Dispatching_Policy
24898 @end itemize
24899
24900 @noindent
24901 To specify @code{SCHED_RR},
24902 @cindex @code{SCHED_RR} scheduling policy
24903 you should use @code{pragma Time_Slice} with a
24904 value greater than @code{0.0}, or else use the corresponding @option{-T}
24905 binder option.
24906
24907 @node Solaris-Specific Considerations
24908 @section Solaris-Specific Considerations
24909 @cindex Solaris Sparc threads libraries
24910
24911 @noindent
24912 This section addresses some topics related to the various threads libraries
24913 on Sparc Solaris.
24914
24915 @menu
24916 * Solaris Threads Issues::
24917 @end menu
24918
24919 @node Solaris Threads Issues
24920 @subsection Solaris Threads Issues
24921
24922 @noindent
24923 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
24924 library based on POSIX threads --- @emph{rts-pthread}.
24925 @cindex rts-pthread threads library
24926 This run-time library has the advantage of being mostly shared across all
24927 POSIX-compliant thread implementations, and it also provides under
24928 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
24929 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
24930 and @code{PTHREAD_PRIO_PROTECT}
24931 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
24932 semantics that can be selected using the predefined pragma
24933 @code{Locking_Policy}
24934 @cindex pragma Locking_Policy (under rts-pthread)
24935 with respectively
24936 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
24937 @cindex @code{Inheritance_Locking} (under rts-pthread)
24938 @cindex @code{Ceiling_Locking} (under rts-pthread)
24939
24940 As explained above, the native run-time library is based on the Solaris thread
24941 library (@code{libthread}) and is the default library.
24942
24943 When the Solaris threads library is used (this is the default), programs
24944 compiled with GNAT can automatically take advantage of
24945 and can thus execute on multiple processors.
24946 The user can alternatively specify a processor on which the program should run
24947 to emulate a single-processor system. The multiprocessor / uniprocessor choice
24948 is made by
24949 setting the environment variable @code{GNAT_PROCESSOR}
24950 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
24951 to one of the following:
24952
24953 @table @code
24954 @item -2
24955 Use the default configuration (run the program on all
24956          available processors) - this is the same as having
24957          @code{GNAT_PROCESSOR} unset
24958
24959 @item -1
24960 Let the run-time implementation choose one processor and run the program on
24961          that processor
24962
24963 @item 0 .. Last_Proc
24964 Run the program on the specified processor.
24965   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
24966 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
24967 @end table
24968
24969 @node Linux-Specific Considerations
24970 @section Linux-Specific Considerations
24971 @cindex Linux threads libraries
24972
24973 @noindent
24974 On GNU/Linux without NPTL support (usually system with GNU C Library
24975 older than 2.3), the signal model is not POSIX compliant, which means
24976 that to send a signal to the process, you need to send the signal to all
24977 threads, e.g. by using @code{killpg()}.
24978
24979 @node AIX-Specific Considerations
24980 @section AIX-Specific Considerations
24981 @cindex AIX resolver library
24982
24983 @noindent
24984 On AIX, the resolver library initializes some internal structure on
24985 the first call to @code{get*by*} functions, which are used to implement
24986 @code{GNAT.Sockets.Get_Host_By_Name} and
24987 @code{GNAT.Sockets.Get_Host_By_Address}.
24988 If such initialization occurs within an Ada task, and the stack size for
24989 the task is the default size, a stack overflow may occur.
24990
24991 To avoid this overflow, the user should either ensure that the first call
24992 to @code{GNAT.Sockets.Get_Host_By_Name} or
24993 @code{GNAT.Sockets.Get_Host_By_Addrss}
24994 occurs in the environment task, or use @code{pragma Storage_Size} to
24995 specify a sufficiently large size for the stack of the task that contains
24996 this call.
24997
24998 @c *******************************
24999 @node Example of Binder Output File
25000 @appendix Example of Binder Output File
25001
25002 @noindent
25003 This Appendix displays the source code for @command{gnatbind}'s output
25004 file generated for a simple ``Hello World'' program.
25005 Comments have been added for clarification purposes.
25006
25007 @smallexample @c adanocomment
25008 @iftex
25009 @leftskip=0cm
25010 @end iftex
25011 --  The package is called Ada_Main unless this name is actually used
25012 --  as a unit name in the partition, in which case some other unique
25013 --  name is used.
25014
25015 with System;
25016 package ada_main is
25017
25018    Elab_Final_Code : Integer;
25019    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
25020
25021    --  The main program saves the parameters (argument count,
25022    --  argument values, environment pointer) in global variables
25023    --  for later access by other units including
25024    --  Ada.Command_Line.
25025
25026    gnat_argc : Integer;
25027    gnat_argv : System.Address;
25028    gnat_envp : System.Address;
25029
25030    --  The actual variables are stored in a library routine. This
25031    --  is useful for some shared library situations, where there
25032    --  are problems if variables are not in the library.
25033
25034    pragma Import (C, gnat_argc);
25035    pragma Import (C, gnat_argv);
25036    pragma Import (C, gnat_envp);
25037
25038    --  The exit status is similarly an external location
25039
25040    gnat_exit_status : Integer;
25041    pragma Import (C, gnat_exit_status);
25042
25043    GNAT_Version : constant String :=
25044                     "GNAT Version: 6.0.0w (20061115)";
25045    pragma Export (C, GNAT_Version, "__gnat_version");
25046
25047    --  This is the generated adafinal routine that performs
25048    --  finalization at the end of execution. In the case where
25049    --  Ada is the main program, this main program makes a call
25050    --  to adafinal at program termination.
25051
25052    procedure adafinal;
25053    pragma Export (C, adafinal, "adafinal");
25054
25055    --  This is the generated adainit routine that performs
25056    --  initialization at the start of execution. In the case
25057    --  where Ada is the main program, this main program makes
25058    --  a call to adainit at program startup.
25059
25060    procedure adainit;
25061    pragma Export (C, adainit, "adainit");
25062
25063    --  This routine is called at the start of execution. It is
25064    --  a dummy routine that is used by the debugger to breakpoint
25065    --  at the start of execution.
25066
25067    procedure Break_Start;
25068    pragma Import (C, Break_Start, "__gnat_break_start");
25069
25070    --  This is the actual generated main program (it would be
25071    --  suppressed if the no main program switch were used). As
25072    --  required by standard system conventions, this program has
25073    --  the external name main.
25074
25075    function main
25076      (argc : Integer;
25077       argv : System.Address;
25078       envp : System.Address)
25079       return Integer;
25080    pragma Export (C, main, "main");
25081
25082    --  The following set of constants give the version
25083    --  identification values for every unit in the bound
25084    --  partition. This identification is computed from all
25085    --  dependent semantic units, and corresponds to the
25086    --  string that would be returned by use of the
25087    --  Body_Version or Version attributes.
25088
25089    type Version_32 is mod 2 ** 32;
25090    u00001 : constant Version_32 := 16#7880BEB3#;
25091    u00002 : constant Version_32 := 16#0D24CBD0#;
25092    u00003 : constant Version_32 := 16#3283DBEB#;
25093    u00004 : constant Version_32 := 16#2359F9ED#;
25094    u00005 : constant Version_32 := 16#664FB847#;
25095    u00006 : constant Version_32 := 16#68E803DF#;
25096    u00007 : constant Version_32 := 16#5572E604#;
25097    u00008 : constant Version_32 := 16#46B173D8#;
25098    u00009 : constant Version_32 := 16#156A40CF#;
25099    u00010 : constant Version_32 := 16#033DABE0#;
25100    u00011 : constant Version_32 := 16#6AB38FEA#;
25101    u00012 : constant Version_32 := 16#22B6217D#;
25102    u00013 : constant Version_32 := 16#68A22947#;
25103    u00014 : constant Version_32 := 16#18CC4A56#;
25104    u00015 : constant Version_32 := 16#08258E1B#;
25105    u00016 : constant Version_32 := 16#367D5222#;
25106    u00017 : constant Version_32 := 16#20C9ECA4#;
25107    u00018 : constant Version_32 := 16#50D32CB6#;
25108    u00019 : constant Version_32 := 16#39A8BB77#;
25109    u00020 : constant Version_32 := 16#5CF8FA2B#;
25110    u00021 : constant Version_32 := 16#2F1EB794#;
25111    u00022 : constant Version_32 := 16#31AB6444#;
25112    u00023 : constant Version_32 := 16#1574B6E9#;
25113    u00024 : constant Version_32 := 16#5109C189#;
25114    u00025 : constant Version_32 := 16#56D770CD#;
25115    u00026 : constant Version_32 := 16#02F9DE3D#;
25116    u00027 : constant Version_32 := 16#08AB6B2C#;
25117    u00028 : constant Version_32 := 16#3FA37670#;
25118    u00029 : constant Version_32 := 16#476457A0#;
25119    u00030 : constant Version_32 := 16#731E1B6E#;
25120    u00031 : constant Version_32 := 16#23C2E789#;
25121    u00032 : constant Version_32 := 16#0F1BD6A1#;
25122    u00033 : constant Version_32 := 16#7C25DE96#;
25123    u00034 : constant Version_32 := 16#39ADFFA2#;
25124    u00035 : constant Version_32 := 16#571DE3E7#;
25125    u00036 : constant Version_32 := 16#5EB646AB#;
25126    u00037 : constant Version_32 := 16#4249379B#;
25127    u00038 : constant Version_32 := 16#0357E00A#;
25128    u00039 : constant Version_32 := 16#3784FB72#;
25129    u00040 : constant Version_32 := 16#2E723019#;
25130    u00041 : constant Version_32 := 16#623358EA#;
25131    u00042 : constant Version_32 := 16#107F9465#;
25132    u00043 : constant Version_32 := 16#6843F68A#;
25133    u00044 : constant Version_32 := 16#63305874#;
25134    u00045 : constant Version_32 := 16#31E56CE1#;
25135    u00046 : constant Version_32 := 16#02917970#;
25136    u00047 : constant Version_32 := 16#6CCBA70E#;
25137    u00048 : constant Version_32 := 16#41CD4204#;
25138    u00049 : constant Version_32 := 16#572E3F58#;
25139    u00050 : constant Version_32 := 16#20729FF5#;
25140    u00051 : constant Version_32 := 16#1D4F93E8#;
25141    u00052 : constant Version_32 := 16#30B2EC3D#;
25142    u00053 : constant Version_32 := 16#34054F96#;
25143    u00054 : constant Version_32 := 16#5A199860#;
25144    u00055 : constant Version_32 := 16#0E7F912B#;
25145    u00056 : constant Version_32 := 16#5760634A#;
25146    u00057 : constant Version_32 := 16#5D851835#;
25147
25148    --  The following Export pragmas export the version numbers
25149    --  with symbolic names ending in B (for body) or S
25150    --  (for spec) so that they can be located in a link. The
25151    --  information provided here is sufficient to track down
25152    --  the exact versions of units used in a given build.
25153
25154    pragma Export (C, u00001, "helloB");
25155    pragma Export (C, u00002, "system__standard_libraryB");
25156    pragma Export (C, u00003, "system__standard_libraryS");
25157    pragma Export (C, u00004, "adaS");
25158    pragma Export (C, u00005, "ada__text_ioB");
25159    pragma Export (C, u00006, "ada__text_ioS");
25160    pragma Export (C, u00007, "ada__exceptionsB");
25161    pragma Export (C, u00008, "ada__exceptionsS");
25162    pragma Export (C, u00009, "gnatS");
25163    pragma Export (C, u00010, "gnat__heap_sort_aB");
25164    pragma Export (C, u00011, "gnat__heap_sort_aS");
25165    pragma Export (C, u00012, "systemS");
25166    pragma Export (C, u00013, "system__exception_tableB");
25167    pragma Export (C, u00014, "system__exception_tableS");
25168    pragma Export (C, u00015, "gnat__htableB");
25169    pragma Export (C, u00016, "gnat__htableS");
25170    pragma Export (C, u00017, "system__exceptionsS");
25171    pragma Export (C, u00018, "system__machine_state_operationsB");
25172    pragma Export (C, u00019, "system__machine_state_operationsS");
25173    pragma Export (C, u00020, "system__machine_codeS");
25174    pragma Export (C, u00021, "system__storage_elementsB");
25175    pragma Export (C, u00022, "system__storage_elementsS");
25176    pragma Export (C, u00023, "system__secondary_stackB");
25177    pragma Export (C, u00024, "system__secondary_stackS");
25178    pragma Export (C, u00025, "system__parametersB");
25179    pragma Export (C, u00026, "system__parametersS");
25180    pragma Export (C, u00027, "system__soft_linksB");
25181    pragma Export (C, u00028, "system__soft_linksS");
25182    pragma Export (C, u00029, "system__stack_checkingB");
25183    pragma Export (C, u00030, "system__stack_checkingS");
25184    pragma Export (C, u00031, "system__tracebackB");
25185    pragma Export (C, u00032, "system__tracebackS");
25186    pragma Export (C, u00033, "ada__streamsS");
25187    pragma Export (C, u00034, "ada__tagsB");
25188    pragma Export (C, u00035, "ada__tagsS");
25189    pragma Export (C, u00036, "system__string_opsB");
25190    pragma Export (C, u00037, "system__string_opsS");
25191    pragma Export (C, u00038, "interfacesS");
25192    pragma Export (C, u00039, "interfaces__c_streamsB");
25193    pragma Export (C, u00040, "interfaces__c_streamsS");
25194    pragma Export (C, u00041, "system__file_ioB");
25195    pragma Export (C, u00042, "system__file_ioS");
25196    pragma Export (C, u00043, "ada__finalizationB");
25197    pragma Export (C, u00044, "ada__finalizationS");
25198    pragma Export (C, u00045, "system__finalization_rootB");
25199    pragma Export (C, u00046, "system__finalization_rootS");
25200    pragma Export (C, u00047, "system__finalization_implementationB");
25201    pragma Export (C, u00048, "system__finalization_implementationS");
25202    pragma Export (C, u00049, "system__string_ops_concat_3B");
25203    pragma Export (C, u00050, "system__string_ops_concat_3S");
25204    pragma Export (C, u00051, "system__stream_attributesB");
25205    pragma Export (C, u00052, "system__stream_attributesS");
25206    pragma Export (C, u00053, "ada__io_exceptionsS");
25207    pragma Export (C, u00054, "system__unsigned_typesS");
25208    pragma Export (C, u00055, "system__file_control_blockS");
25209    pragma Export (C, u00056, "ada__finalization__list_controllerB");
25210    pragma Export (C, u00057, "ada__finalization__list_controllerS");
25211
25212    -- BEGIN ELABORATION ORDER
25213    -- ada (spec)
25214    -- gnat (spec)
25215    -- gnat.heap_sort_a (spec)
25216    -- gnat.heap_sort_a (body)
25217    -- gnat.htable (spec)
25218    -- gnat.htable (body)
25219    -- interfaces (spec)
25220    -- system (spec)
25221    -- system.machine_code (spec)
25222    -- system.parameters (spec)
25223    -- system.parameters (body)
25224    -- interfaces.c_streams (spec)
25225    -- interfaces.c_streams (body)
25226    -- system.standard_library (spec)
25227    -- ada.exceptions (spec)
25228    -- system.exception_table (spec)
25229    -- system.exception_table (body)
25230    -- ada.io_exceptions (spec)
25231    -- system.exceptions (spec)
25232    -- system.storage_elements (spec)
25233    -- system.storage_elements (body)
25234    -- system.machine_state_operations (spec)
25235    -- system.machine_state_operations (body)
25236    -- system.secondary_stack (spec)
25237    -- system.stack_checking (spec)
25238    -- system.soft_links (spec)
25239    -- system.soft_links (body)
25240    -- system.stack_checking (body)
25241    -- system.secondary_stack (body)
25242    -- system.standard_library (body)
25243    -- system.string_ops (spec)
25244    -- system.string_ops (body)
25245    -- ada.tags (spec)
25246    -- ada.tags (body)
25247    -- ada.streams (spec)
25248    -- system.finalization_root (spec)
25249    -- system.finalization_root (body)
25250    -- system.string_ops_concat_3 (spec)
25251    -- system.string_ops_concat_3 (body)
25252    -- system.traceback (spec)
25253    -- system.traceback (body)
25254    -- ada.exceptions (body)
25255    -- system.unsigned_types (spec)
25256    -- system.stream_attributes (spec)
25257    -- system.stream_attributes (body)
25258    -- system.finalization_implementation (spec)
25259    -- system.finalization_implementation (body)
25260    -- ada.finalization (spec)
25261    -- ada.finalization (body)
25262    -- ada.finalization.list_controller (spec)
25263    -- ada.finalization.list_controller (body)
25264    -- system.file_control_block (spec)
25265    -- system.file_io (spec)
25266    -- system.file_io (body)
25267    -- ada.text_io (spec)
25268    -- ada.text_io (body)
25269    -- hello (body)
25270    -- END ELABORATION ORDER
25271
25272 end ada_main;
25273
25274 --  The following source file name pragmas allow the generated file
25275 --  names to be unique for different main programs. They are needed
25276 --  since the package name will always be Ada_Main.
25277
25278 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
25279 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
25280
25281 --  Generated package body for Ada_Main starts here
25282
25283 package body ada_main is
25284
25285    --  The actual finalization is performed by calling the
25286    --  library routine in System.Standard_Library.Adafinal
25287
25288    procedure Do_Finalize;
25289    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
25290
25291    -------------
25292    -- adainit --
25293    -------------
25294
25295 @findex adainit
25296    procedure adainit is
25297
25298       --  These booleans are set to True once the associated unit has
25299       --  been elaborated. It is also used to avoid elaborating the
25300       --  same unit twice.
25301
25302       E040 : Boolean;
25303       pragma Import (Ada, E040, "interfaces__c_streams_E");
25304
25305       E008 : Boolean;
25306       pragma Import (Ada, E008, "ada__exceptions_E");
25307
25308       E014 : Boolean;
25309       pragma Import (Ada, E014, "system__exception_table_E");
25310
25311       E053 : Boolean;
25312       pragma Import (Ada, E053, "ada__io_exceptions_E");
25313
25314       E017 : Boolean;
25315       pragma Import (Ada, E017, "system__exceptions_E");
25316
25317       E024 : Boolean;
25318       pragma Import (Ada, E024, "system__secondary_stack_E");
25319
25320       E030 : Boolean;
25321       pragma Import (Ada, E030, "system__stack_checking_E");
25322
25323       E028 : Boolean;
25324       pragma Import (Ada, E028, "system__soft_links_E");
25325
25326       E035 : Boolean;
25327       pragma Import (Ada, E035, "ada__tags_E");
25328
25329       E033 : Boolean;
25330       pragma Import (Ada, E033, "ada__streams_E");
25331
25332       E046 : Boolean;
25333       pragma Import (Ada, E046, "system__finalization_root_E");
25334
25335       E048 : Boolean;
25336       pragma Import (Ada, E048, "system__finalization_implementation_E");
25337
25338       E044 : Boolean;
25339       pragma Import (Ada, E044, "ada__finalization_E");
25340
25341       E057 : Boolean;
25342       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
25343
25344       E055 : Boolean;
25345       pragma Import (Ada, E055, "system__file_control_block_E");
25346
25347       E042 : Boolean;
25348       pragma Import (Ada, E042, "system__file_io_E");
25349
25350       E006 : Boolean;
25351       pragma Import (Ada, E006, "ada__text_io_E");
25352
25353       --  Set_Globals is a library routine that stores away the
25354       --  value of the indicated set of global values in global
25355       --  variables within the library.
25356
25357       procedure Set_Globals
25358         (Main_Priority            : Integer;
25359          Time_Slice_Value         : Integer;
25360          WC_Encoding              : Character;
25361          Locking_Policy           : Character;
25362          Queuing_Policy           : Character;
25363          Task_Dispatching_Policy  : Character;
25364          Adafinal                 : System.Address;
25365          Unreserve_All_Interrupts : Integer;
25366          Exception_Tracebacks     : Integer);
25367 @findex __gnat_set_globals
25368       pragma Import (C, Set_Globals, "__gnat_set_globals");
25369
25370       --  SDP_Table_Build is a library routine used to build the
25371       --  exception tables. See unit Ada.Exceptions in files
25372       --  a-except.ads/adb for full details of how zero cost
25373       --  exception handling works. This procedure, the call to
25374       --  it, and the two following tables are all omitted if the
25375       --  build is in longjmp/setjump exception mode.
25376
25377 @findex SDP_Table_Build
25378 @findex Zero Cost Exceptions
25379       procedure SDP_Table_Build
25380         (SDP_Addresses   : System.Address;
25381          SDP_Count       : Natural;
25382          Elab_Addresses  : System.Address;
25383          Elab_Addr_Count : Natural);
25384       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
25385
25386       --  Table of Unit_Exception_Table addresses. Used for zero
25387       --  cost exception handling to build the top level table.
25388
25389       ST : aliased constant array (1 .. 23) of System.Address := (
25390         Hello'UET_Address,
25391         Ada.Text_Io'UET_Address,
25392         Ada.Exceptions'UET_Address,
25393         Gnat.Heap_Sort_A'UET_Address,
25394         System.Exception_Table'UET_Address,
25395         System.Machine_State_Operations'UET_Address,
25396         System.Secondary_Stack'UET_Address,
25397         System.Parameters'UET_Address,
25398         System.Soft_Links'UET_Address,
25399         System.Stack_Checking'UET_Address,
25400         System.Traceback'UET_Address,
25401         Ada.Streams'UET_Address,
25402         Ada.Tags'UET_Address,
25403         System.String_Ops'UET_Address,
25404         Interfaces.C_Streams'UET_Address,
25405         System.File_Io'UET_Address,
25406         Ada.Finalization'UET_Address,
25407         System.Finalization_Root'UET_Address,
25408         System.Finalization_Implementation'UET_Address,
25409         System.String_Ops_Concat_3'UET_Address,
25410         System.Stream_Attributes'UET_Address,
25411         System.File_Control_Block'UET_Address,
25412         Ada.Finalization.List_Controller'UET_Address);
25413
25414       --  Table of addresses of elaboration routines. Used for
25415       --  zero cost exception handling to make sure these
25416       --  addresses are included in the top level procedure
25417       --  address table.
25418
25419       EA : aliased constant array (1 .. 23) of System.Address := (
25420         adainit'Code_Address,
25421         Do_Finalize'Code_Address,
25422         Ada.Exceptions'Elab_Spec'Address,
25423         System.Exceptions'Elab_Spec'Address,
25424         Interfaces.C_Streams'Elab_Spec'Address,
25425         System.Exception_Table'Elab_Body'Address,
25426         Ada.Io_Exceptions'Elab_Spec'Address,
25427         System.Stack_Checking'Elab_Spec'Address,
25428         System.Soft_Links'Elab_Body'Address,
25429         System.Secondary_Stack'Elab_Body'Address,
25430         Ada.Tags'Elab_Spec'Address,
25431         Ada.Tags'Elab_Body'Address,
25432         Ada.Streams'Elab_Spec'Address,
25433         System.Finalization_Root'Elab_Spec'Address,
25434         Ada.Exceptions'Elab_Body'Address,
25435         System.Finalization_Implementation'Elab_Spec'Address,
25436         System.Finalization_Implementation'Elab_Body'Address,
25437         Ada.Finalization'Elab_Spec'Address,
25438         Ada.Finalization.List_Controller'Elab_Spec'Address,
25439         System.File_Control_Block'Elab_Spec'Address,
25440         System.File_Io'Elab_Body'Address,
25441         Ada.Text_Io'Elab_Spec'Address,
25442         Ada.Text_Io'Elab_Body'Address);
25443
25444    --  Start of processing for adainit
25445
25446    begin
25447
25448       --  Call SDP_Table_Build to build the top level procedure
25449       --  table for zero cost exception handling (omitted in
25450       --  longjmp/setjump mode).
25451
25452       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
25453
25454       --  Call Set_Globals to record various information for
25455       --  this partition.  The values are derived by the binder
25456       --  from information stored in the ali files by the compiler.
25457
25458 @findex __gnat_set_globals
25459       Set_Globals
25460         (Main_Priority            => -1,
25461          --  Priority of main program, -1 if no pragma Priority used
25462
25463          Time_Slice_Value         => -1,
25464          --  Time slice from Time_Slice pragma, -1 if none used
25465
25466          WC_Encoding              => 'b',
25467          --  Wide_Character encoding used, default is brackets
25468
25469          Locking_Policy           => ' ',
25470          --  Locking_Policy used, default of space means not
25471          --  specified, otherwise it is the first character of
25472          --  the policy name.
25473
25474          Queuing_Policy           => ' ',
25475          --  Queuing_Policy used, default of space means not
25476          --  specified, otherwise it is the first character of
25477          --  the policy name.
25478
25479          Task_Dispatching_Policy  => ' ',
25480          --  Task_Dispatching_Policy used, default of space means
25481          --  not specified, otherwise first character of the
25482          --  policy name.
25483
25484          Adafinal                 => System.Null_Address,
25485          --  Address of Adafinal routine, not used anymore
25486
25487          Unreserve_All_Interrupts => 0,
25488          --  Set true if pragma Unreserve_All_Interrupts was used
25489
25490          Exception_Tracebacks     => 0);
25491          --  Indicates if exception tracebacks are enabled
25492
25493       Elab_Final_Code := 1;
25494
25495       --  Now we have the elaboration calls for all units in the partition.
25496       --  The Elab_Spec and Elab_Body attributes generate references to the
25497       --  implicit elaboration procedures generated by the compiler for
25498       --  each unit that requires elaboration.
25499
25500       if not E040 then
25501          Interfaces.C_Streams'Elab_Spec;
25502       end if;
25503       E040 := True;
25504       if not E008 then
25505          Ada.Exceptions'Elab_Spec;
25506       end if;
25507       if not E014 then
25508          System.Exception_Table'Elab_Body;
25509          E014 := True;
25510       end if;
25511       if not E053 then
25512          Ada.Io_Exceptions'Elab_Spec;
25513          E053 := True;
25514       end if;
25515       if not E017 then
25516          System.Exceptions'Elab_Spec;
25517          E017 := True;
25518       end if;
25519       if not E030 then
25520          System.Stack_Checking'Elab_Spec;
25521       end if;
25522       if not E028 then
25523          System.Soft_Links'Elab_Body;
25524          E028 := True;
25525       end if;
25526       E030 := True;
25527       if not E024 then
25528          System.Secondary_Stack'Elab_Body;
25529          E024 := True;
25530       end if;
25531       if not E035 then
25532          Ada.Tags'Elab_Spec;
25533       end if;
25534       if not E035 then
25535          Ada.Tags'Elab_Body;
25536          E035 := True;
25537       end if;
25538       if not E033 then
25539          Ada.Streams'Elab_Spec;
25540          E033 := True;
25541       end if;
25542       if not E046 then
25543          System.Finalization_Root'Elab_Spec;
25544       end if;
25545       E046 := True;
25546       if not E008 then
25547          Ada.Exceptions'Elab_Body;
25548          E008 := True;
25549       end if;
25550       if not E048 then
25551          System.Finalization_Implementation'Elab_Spec;
25552       end if;
25553       if not E048 then
25554          System.Finalization_Implementation'Elab_Body;
25555          E048 := True;
25556       end if;
25557       if not E044 then
25558          Ada.Finalization'Elab_Spec;
25559       end if;
25560       E044 := True;
25561       if not E057 then
25562          Ada.Finalization.List_Controller'Elab_Spec;
25563       end if;
25564       E057 := True;
25565       if not E055 then
25566          System.File_Control_Block'Elab_Spec;
25567          E055 := True;
25568       end if;
25569       if not E042 then
25570          System.File_Io'Elab_Body;
25571          E042 := True;
25572       end if;
25573       if not E006 then
25574          Ada.Text_Io'Elab_Spec;
25575       end if;
25576       if not E006 then
25577          Ada.Text_Io'Elab_Body;
25578          E006 := True;
25579       end if;
25580
25581       Elab_Final_Code := 0;
25582    end adainit;
25583
25584    --------------
25585    -- adafinal --
25586    --------------
25587
25588 @findex adafinal
25589    procedure adafinal is
25590    begin
25591       Do_Finalize;
25592    end adafinal;
25593
25594    ----------
25595    -- main --
25596    ----------
25597
25598    --  main is actually a function, as in the ANSI C standard,
25599    --  defined to return the exit status. The three parameters
25600    --  are the argument count, argument values and environment
25601    --  pointer.
25602
25603 @findex Main Program
25604    function main
25605      (argc : Integer;
25606       argv : System.Address;
25607       envp : System.Address)
25608       return Integer
25609    is
25610       --  The initialize routine performs low level system
25611       --  initialization using a standard library routine which
25612       --  sets up signal handling and performs any other
25613       --  required setup. The routine can be found in file
25614       --  a-init.c.
25615
25616 @findex __gnat_initialize
25617       procedure initialize;
25618       pragma Import (C, initialize, "__gnat_initialize");
25619
25620       --  The finalize routine performs low level system
25621       --  finalization using a standard library routine. The
25622       --  routine is found in file a-final.c and in the standard
25623       --  distribution is a dummy routine that does nothing, so
25624       --  really this is a hook for special user finalization.
25625
25626 @findex __gnat_finalize
25627       procedure finalize;
25628       pragma Import (C, finalize, "__gnat_finalize");
25629
25630       --  We get to the main program of the partition by using
25631       --  pragma Import because if we try to with the unit and
25632       --  call it Ada style, then not only do we waste time
25633       --  recompiling it, but also, we don't really know the right
25634       --  switches (e.g. identifier character set) to be used
25635       --  to compile it.
25636
25637       procedure Ada_Main_Program;
25638       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
25639
25640    --  Start of processing for main
25641
25642    begin
25643       --  Save global variables
25644
25645       gnat_argc := argc;
25646       gnat_argv := argv;
25647       gnat_envp := envp;
25648
25649       --  Call low level system initialization
25650
25651       Initialize;
25652
25653       --  Call our generated Ada initialization routine
25654
25655       adainit;
25656
25657       --  This is the point at which we want the debugger to get
25658       --  control
25659
25660       Break_Start;
25661
25662       --  Now we call the main program of the partition
25663
25664       Ada_Main_Program;
25665
25666       --  Perform Ada finalization
25667
25668       adafinal;
25669
25670       --  Perform low level system finalization
25671
25672       Finalize;
25673
25674       --  Return the proper exit status
25675       return (gnat_exit_status);
25676    end;
25677
25678 --  This section is entirely comments, so it has no effect on the
25679 --  compilation of the Ada_Main package. It provides the list of
25680 --  object files and linker options, as well as some standard
25681 --  libraries needed for the link. The gnatlink utility parses
25682 --  this b~hello.adb file to read these comment lines to generate
25683 --  the appropriate command line arguments for the call to the
25684 --  system linker. The BEGIN/END lines are used for sentinels for
25685 --  this parsing operation.
25686
25687 --  The exact file names will of course depend on the environment,
25688 --  host/target and location of files on the host system.
25689
25690 @findex Object file list
25691 -- BEGIN Object file/option list
25692    --   ./hello.o
25693    --   -L./
25694    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
25695    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
25696 -- END Object file/option list
25697
25698 end ada_main;
25699 @end smallexample
25700
25701 @noindent
25702 The Ada code in the above example is exactly what is generated by the
25703 binder. We have added comments to more clearly indicate the function
25704 of each part of the generated @code{Ada_Main} package.
25705
25706 The code is standard Ada in all respects, and can be processed by any
25707 tools that handle Ada. In particular, it is possible to use the debugger
25708 in Ada mode to debug the generated @code{Ada_Main} package. For example,
25709 suppose that for reasons that you do not understand, your program is crashing
25710 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
25711 you can place a breakpoint on the call:
25712
25713 @smallexample @c ada
25714 Ada.Text_Io'Elab_Body;
25715 @end smallexample
25716
25717 @noindent
25718 and trace the elaboration routine for this package to find out where
25719 the problem might be (more usually of course you would be debugging
25720 elaboration code in your own application).
25721
25722 @node Elaboration Order Handling in GNAT
25723 @appendix Elaboration Order Handling in GNAT
25724 @cindex Order of elaboration
25725 @cindex Elaboration control
25726
25727 @menu
25728 * Elaboration Code::
25729 * Checking the Elaboration Order::
25730 * Controlling the Elaboration Order::
25731 * Controlling Elaboration in GNAT - Internal Calls::
25732 * Controlling Elaboration in GNAT - External Calls::
25733 * Default Behavior in GNAT - Ensuring Safety::
25734 * Treatment of Pragma Elaborate::
25735 * Elaboration Issues for Library Tasks::
25736 * Mixing Elaboration Models::
25737 * What to Do If the Default Elaboration Behavior Fails::
25738 * Elaboration for Access-to-Subprogram Values::
25739 * Summary of Procedures for Elaboration Control::
25740 * Other Elaboration Order Considerations::
25741 @end menu
25742
25743 @noindent
25744 This chapter describes the handling of elaboration code in Ada and
25745 in GNAT, and discusses how the order of elaboration of program units can
25746 be controlled in GNAT, either automatically or with explicit programming
25747 features.
25748
25749 @node Elaboration Code
25750 @section Elaboration Code
25751
25752 @noindent
25753 Ada provides rather general mechanisms for executing code at elaboration
25754 time, that is to say before the main program starts executing. Such code arises
25755 in three contexts:
25756
25757 @table @asis
25758 @item Initializers for variables.
25759 Variables declared at the library level, in package specs or bodies, can
25760 require initialization that is performed at elaboration time, as in:
25761 @smallexample @c ada
25762 @cartouche
25763 Sqrt_Half : Float := Sqrt (0.5);
25764 @end cartouche
25765 @end smallexample
25766
25767 @item Package initialization code
25768 Code in a @code{BEGIN-END} section at the outer level of a package body is
25769 executed as part of the package body elaboration code.
25770
25771 @item Library level task allocators
25772 Tasks that are declared using task allocators at the library level
25773 start executing immediately and hence can execute at elaboration time.
25774 @end table
25775
25776 @noindent
25777 Subprogram calls are possible in any of these contexts, which means that
25778 any arbitrary part of the program may be executed as part of the elaboration
25779 code. It is even possible to write a program which does all its work at
25780 elaboration time, with a null main program, although stylistically this
25781 would usually be considered an inappropriate way to structure
25782 a program.
25783
25784 An important concern arises in the context of elaboration code:
25785 we have to be sure that it is executed in an appropriate order. What we
25786 have is a series of elaboration code sections, potentially one section
25787 for each unit in the program. It is important that these execute
25788 in the correct order. Correctness here means that, taking the above
25789 example of the declaration of @code{Sqrt_Half},
25790 if some other piece of
25791 elaboration code references @code{Sqrt_Half},
25792 then it must run after the
25793 section of elaboration code that contains the declaration of
25794 @code{Sqrt_Half}.
25795
25796 There would never be any order of elaboration problem if we made a rule
25797 that whenever you @code{with} a unit, you must elaborate both the spec and body
25798 of that unit before elaborating the unit doing the @code{with}'ing:
25799
25800 @smallexample @c ada
25801 @group
25802 @cartouche
25803 with Unit_1;
25804 package Unit_2 is ...
25805 @end cartouche
25806 @end group
25807 @end smallexample
25808
25809 @noindent
25810 would require that both the body and spec of @code{Unit_1} be elaborated
25811 before the spec of @code{Unit_2}. However, a rule like that would be far too
25812 restrictive. In particular, it would make it impossible to have routines
25813 in separate packages that were mutually recursive.
25814
25815 You might think that a clever enough compiler could look at the actual
25816 elaboration code and determine an appropriate correct order of elaboration,
25817 but in the general case, this is not possible. Consider the following
25818 example.
25819
25820 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
25821 that references
25822 the variable @code{Sqrt_1}, which is declared in the elaboration code
25823 of the body of @code{Unit_1}:
25824
25825 @smallexample @c ada
25826 @cartouche
25827 Sqrt_1 : Float := Sqrt (0.1);
25828 @end cartouche
25829 @end smallexample
25830
25831 @noindent
25832 The elaboration code of the body of @code{Unit_1} also contains:
25833
25834 @smallexample @c ada
25835 @group
25836 @cartouche
25837 if expression_1 = 1 then
25838    Q := Unit_2.Func_2;
25839 end if;
25840 @end cartouche
25841 @end group
25842 @end smallexample
25843
25844 @noindent
25845 @code{Unit_2} is exactly parallel,
25846 it has a procedure @code{Func_2} that references
25847 the variable @code{Sqrt_2}, which is declared in the elaboration code of
25848 the body @code{Unit_2}:
25849
25850 @smallexample @c ada
25851 @cartouche
25852 Sqrt_2 : Float := Sqrt (0.1);
25853 @end cartouche
25854 @end smallexample
25855
25856 @noindent
25857 The elaboration code of the body of @code{Unit_2} also contains:
25858
25859 @smallexample @c ada
25860 @group
25861 @cartouche
25862 if expression_2 = 2 then
25863    Q := Unit_1.Func_1;
25864 end if;
25865 @end cartouche
25866 @end group
25867 @end smallexample
25868
25869 @noindent
25870 Now the question is, which of the following orders of elaboration is
25871 acceptable:
25872
25873 @smallexample
25874 @group
25875 Spec of Unit_1
25876 Spec of Unit_2
25877 Body of Unit_1
25878 Body of Unit_2
25879 @end group
25880 @end smallexample
25881
25882 @noindent
25883 or
25884
25885 @smallexample
25886 @group
25887 Spec of Unit_2
25888 Spec of Unit_1
25889 Body of Unit_2
25890 Body of Unit_1
25891 @end group
25892 @end smallexample
25893
25894 @noindent
25895 If you carefully analyze the flow here, you will see that you cannot tell
25896 at compile time the answer to this question.
25897 If @code{expression_1} is not equal to 1,
25898 and @code{expression_2} is not equal to 2,
25899 then either order is acceptable, because neither of the function calls is
25900 executed. If both tests evaluate to true, then neither order is acceptable
25901 and in fact there is no correct order.
25902
25903 If one of the two expressions is true, and the other is false, then one
25904 of the above orders is correct, and the other is incorrect. For example,
25905 if @code{expression_1} /= 1 and @code{expression_2} = 2,
25906 then the call to @code{Func_1}
25907 will occur, but not the call to @code{Func_2.}
25908 This means that it is essential
25909 to elaborate the body of @code{Unit_1} before
25910 the body of @code{Unit_2}, so the first
25911 order of elaboration is correct and the second is wrong.
25912
25913 By making @code{expression_1} and @code{expression_2}
25914 depend on input data, or perhaps
25915 the time of day, we can make it impossible for the compiler or binder
25916 to figure out which of these expressions will be true, and hence it
25917 is impossible to guarantee a safe order of elaboration at run time.
25918
25919 @node Checking the Elaboration Order
25920 @section Checking the Elaboration Order
25921
25922 @noindent
25923 In some languages that involve the same kind of elaboration problems,
25924 e.g. Java and C++, the programmer is expected to worry about these
25925 ordering problems himself, and it is common to
25926 write a program in which an incorrect elaboration order  gives
25927 surprising results, because it references variables before they
25928 are initialized.
25929 Ada is designed to be a safe language, and a programmer-beware approach is
25930 clearly not sufficient. Consequently, the language provides three lines
25931 of defense:
25932
25933 @table @asis
25934 @item Standard rules
25935 Some standard rules restrict the possible choice of elaboration
25936 order. In particular, if you @code{with} a unit, then its spec is always
25937 elaborated before the unit doing the @code{with}. Similarly, a parent
25938 spec is always elaborated before the child spec, and finally
25939 a spec is always elaborated before its corresponding body.
25940
25941 @item Dynamic elaboration checks
25942 @cindex Elaboration checks
25943 @cindex Checks, elaboration
25944 Dynamic checks are made at run time, so that if some entity is accessed
25945 before it is elaborated (typically  by means of a subprogram call)
25946 then the exception (@code{Program_Error}) is raised.
25947
25948 @item Elaboration control
25949 Facilities are provided for the programmer to specify the desired order
25950 of elaboration.
25951 @end table
25952
25953 Let's look at these facilities in more detail. First, the rules for
25954 dynamic checking. One possible rule would be simply to say that the
25955 exception is raised if you access a variable which has not yet been
25956 elaborated. The trouble with this approach is that it could require
25957 expensive checks on every variable reference. Instead Ada has two
25958 rules which are a little more restrictive, but easier to check, and
25959 easier to state:
25960
25961 @table @asis
25962 @item Restrictions on calls
25963 A subprogram can only be called at elaboration time if its body
25964 has been elaborated. The rules for elaboration given above guarantee
25965 that the spec of the subprogram has been elaborated before the
25966 call, but not the body. If this rule is violated, then the
25967 exception @code{Program_Error} is raised.
25968
25969 @item Restrictions on instantiations
25970 A generic unit can only be instantiated if the body of the generic
25971 unit has been elaborated. Again, the rules for elaboration given above
25972 guarantee that the spec of the generic unit has been elaborated
25973 before the instantiation, but not the body. If this rule is
25974 violated, then the exception @code{Program_Error} is raised.
25975 @end table
25976
25977 @noindent
25978 The idea is that if the body has been elaborated, then any variables
25979 it references must have been elaborated; by checking for the body being
25980 elaborated we guarantee that none of its references causes any
25981 trouble. As we noted above, this is a little too restrictive, because a
25982 subprogram that has no non-local references in its body may in fact be safe
25983 to call. However, it really would be unsafe to rely on this, because
25984 it would mean that the caller was aware of details of the implementation
25985 in the body. This goes against the basic tenets of Ada.
25986
25987 A plausible implementation can be described as follows.
25988 A Boolean variable is associated with each subprogram
25989 and each generic unit. This variable is initialized to False, and is set to
25990 True at the point body is elaborated. Every call or instantiation checks the
25991 variable, and raises @code{Program_Error} if the variable is False.
25992
25993 Note that one might think that it would be good enough to have one Boolean
25994 variable for each package, but that would not deal with cases of trying
25995 to call a body in the same package as the call
25996 that has not been elaborated yet.
25997 Of course a compiler may be able to do enough analysis to optimize away
25998 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
25999 does such optimizations, but still the easiest conceptual model is to
26000 think of there being one variable per subprogram.
26001
26002 @node Controlling the Elaboration Order
26003 @section Controlling the Elaboration Order
26004
26005 @noindent
26006 In the previous section we discussed the rules in Ada which ensure
26007 that @code{Program_Error} is raised if an incorrect elaboration order is
26008 chosen. This prevents erroneous executions, but we need mechanisms to
26009 specify a correct execution and avoid the exception altogether.
26010 To achieve this, Ada provides a number of features for controlling
26011 the order of elaboration. We discuss these features in this section.
26012
26013 First, there are several ways of indicating to the compiler that a given
26014 unit has no elaboration problems:
26015
26016 @table @asis
26017 @item packages that do not require a body
26018 A library package that does not require a body does not permit
26019 a body (this rule was introduced in Ada 95).
26020 Thus if we have a such a package, as in:
26021
26022 @smallexample @c ada
26023 @group
26024 @cartouche
26025 package Definitions is
26026    generic
26027       type m is new integer;
26028    package Subp is
26029       type a is array (1 .. 10) of m;
26030       type b is array (1 .. 20) of m;
26031    end Subp;
26032 end Definitions;
26033 @end cartouche
26034 @end group
26035 @end smallexample
26036
26037 @noindent
26038 A package that @code{with}'s @code{Definitions} may safely instantiate
26039 @code{Definitions.Subp} because the compiler can determine that there
26040 definitely is no package body to worry about in this case
26041
26042 @item pragma Pure
26043 @cindex pragma Pure
26044 @findex Pure
26045 Places sufficient restrictions on a unit to guarantee that
26046 no call to any subprogram in the unit can result in an
26047 elaboration problem. This means that the compiler does not need
26048 to worry about the point of elaboration of such units, and in
26049 particular, does not need to check any calls to any subprograms
26050 in this unit.
26051
26052 @item pragma Preelaborate
26053 @findex Preelaborate
26054 @cindex pragma Preelaborate
26055 This pragma places slightly less stringent restrictions on a unit than
26056 does pragma Pure,
26057 but these restrictions are still sufficient to ensure that there
26058 are no elaboration problems with any calls to the unit.
26059
26060 @item pragma Elaborate_Body
26061 @findex Elaborate_Body
26062 @cindex pragma Elaborate_Body
26063 This pragma requires that the body of a unit be elaborated immediately
26064 after its spec. Suppose a unit @code{A} has such a pragma,
26065 and unit @code{B} does
26066 a @code{with} of unit @code{A}. Recall that the standard rules require
26067 the spec of unit @code{A}
26068 to be elaborated before the @code{with}'ing unit; given the pragma in
26069 @code{A}, we also know that the body of @code{A}
26070 will be elaborated before @code{B}, so
26071 that calls to @code{A} are safe and do not need a check.
26072 @end table
26073
26074 @noindent
26075 Note that,
26076 unlike pragma @code{Pure} and pragma @code{Preelaborate},
26077 the use of
26078 @code{Elaborate_Body} does not guarantee that the program is
26079 free of elaboration problems, because it may not be possible
26080 to satisfy the requested elaboration order.
26081 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
26082 If a programmer
26083 marks @code{Unit_1} as @code{Elaborate_Body},
26084 and not @code{Unit_2,} then the order of
26085 elaboration will be:
26086
26087 @smallexample
26088 @group
26089 Spec of Unit_2
26090 Spec of Unit_1
26091 Body of Unit_1
26092 Body of Unit_2
26093 @end group
26094 @end smallexample
26095
26096 @noindent
26097 Now that means that the call to @code{Func_1} in @code{Unit_2}
26098 need not be checked,
26099 it must be safe. But the call to @code{Func_2} in
26100 @code{Unit_1} may still fail if
26101 @code{Expression_1} is equal to 1,
26102 and the programmer must still take
26103 responsibility for this not being the case.
26104
26105 If all units carry a pragma @code{Elaborate_Body}, then all problems are
26106 eliminated, except for calls entirely within a body, which are
26107 in any case fully under programmer control. However, using the pragma
26108 everywhere is not always possible.
26109 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
26110 we marked both of them as having pragma @code{Elaborate_Body}, then
26111 clearly there would be no possible elaboration order.
26112
26113 The above pragmas allow a server to guarantee safe use by clients, and
26114 clearly this is the preferable approach. Consequently a good rule
26115 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
26116 and if this is not possible,
26117 mark them as @code{Elaborate_Body} if possible.
26118 As we have seen, there are situations where neither of these
26119 three pragmas can be used.
26120 So we also provide methods for clients to control the
26121 order of elaboration of the servers on which they depend:
26122
26123 @table @asis
26124 @item pragma Elaborate (unit)
26125 @findex Elaborate
26126 @cindex pragma Elaborate
26127 This pragma is placed in the context clause, after a @code{with} clause,
26128 and it requires that the body of the named unit be elaborated before
26129 the unit in which the pragma occurs. The idea is to use this pragma
26130 if the current unit calls at elaboration time, directly or indirectly,
26131 some subprogram in the named unit.
26132
26133 @item pragma Elaborate_All (unit)
26134 @findex Elaborate_All
26135 @cindex pragma Elaborate_All
26136 This is a stronger version of the Elaborate pragma. Consider the
26137 following example:
26138
26139 @smallexample
26140 Unit A @code{with}'s unit B and calls B.Func in elab code
26141 Unit B @code{with}'s unit C, and B.Func calls C.Func
26142 @end smallexample
26143
26144 @noindent
26145 Now if we put a pragma @code{Elaborate (B)}
26146 in unit @code{A}, this ensures that the
26147 body of @code{B} is elaborated before the call, but not the
26148 body of @code{C}, so
26149 the call to @code{C.Func} could still cause @code{Program_Error} to
26150 be raised.
26151
26152 The effect of a pragma @code{Elaborate_All} is stronger, it requires
26153 not only that the body of the named unit be elaborated before the
26154 unit doing the @code{with}, but also the bodies of all units that the
26155 named unit uses, following @code{with} links transitively. For example,
26156 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
26157 then it requires
26158 not only that the body of @code{B} be elaborated before @code{A},
26159 but also the
26160 body of @code{C}, because @code{B} @code{with}'s @code{C}.
26161 @end table
26162
26163 @noindent
26164 We are now in a position to give a usage rule in Ada for avoiding
26165 elaboration problems, at least if dynamic dispatching and access to
26166 subprogram values are not used. We will handle these cases separately
26167 later.
26168
26169 The rule is simple. If a unit has elaboration code that can directly or
26170 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
26171 a generic package in a @code{with}'ed unit,
26172 then if the @code{with}'ed unit does not have
26173 pragma @code{Pure} or @code{Preelaborate}, then the client should have
26174 a pragma @code{Elaborate_All}
26175 for the @code{with}'ed unit. By following this rule a client is
26176 assured that calls can be made without risk of an exception.
26177
26178 For generic subprogram instantiations, the rule can be relaxed to
26179 require only a pragma @code{Elaborate} since elaborating the body
26180 of a subprogram cannot cause any transitive elaboration (we are
26181 not calling the subprogram in this case, just elaborating its
26182 declaration).
26183
26184 If this rule is not followed, then a program may be in one of four
26185 states:
26186
26187 @table @asis
26188 @item No order exists
26189 No order of elaboration exists which follows the rules, taking into
26190 account any @code{Elaborate}, @code{Elaborate_All},
26191 or @code{Elaborate_Body} pragmas. In
26192 this case, an Ada compiler must diagnose the situation at bind
26193 time, and refuse to build an executable program.
26194
26195 @item One or more orders exist, all incorrect
26196 One or more acceptable elaboration orders exist, and all of them
26197 generate an elaboration order problem. In this case, the binder
26198 can build an executable program, but @code{Program_Error} will be raised
26199 when the program is run.
26200
26201 @item Several orders exist, some right, some incorrect
26202 One or more acceptable elaboration orders exists, and some of them
26203 work, and some do not. The programmer has not controlled
26204 the order of elaboration, so the binder may or may not pick one of
26205 the correct orders, and the program may or may not raise an
26206 exception when it is run. This is the worst case, because it means
26207 that the program may fail when moved to another compiler, or even
26208 another version of the same compiler.
26209
26210 @item One or more orders exists, all correct
26211 One ore more acceptable elaboration orders exist, and all of them
26212 work. In this case the program runs successfully. This state of
26213 affairs can be guaranteed by following the rule we gave above, but
26214 may be true even if the rule is not followed.
26215 @end table
26216
26217 @noindent
26218 Note that one additional advantage of following our rules on the use
26219 of @code{Elaborate} and @code{Elaborate_All}
26220 is that the program continues to stay in the ideal (all orders OK) state
26221 even if maintenance
26222 changes some bodies of some units. Conversely, if a program that does
26223 not follow this rule happens to be safe at some point, this state of affairs
26224 may deteriorate silently as a result of maintenance changes.
26225
26226 You may have noticed that the above discussion did not mention
26227 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
26228 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
26229 code in the body makes calls to some other unit, so it is still necessary
26230 to use @code{Elaborate_All} on such units.
26231
26232 @node Controlling Elaboration in GNAT - Internal Calls
26233 @section Controlling Elaboration in GNAT - Internal Calls
26234
26235 @noindent
26236 In the case of internal calls, i.e. calls within a single package, the
26237 programmer has full control over the order of elaboration, and it is up
26238 to the programmer to elaborate declarations in an appropriate order. For
26239 example writing:
26240
26241 @smallexample @c ada
26242 @group
26243 @cartouche
26244 function One return Float;
26245
26246 Q : Float := One;
26247
26248 function One return Float is
26249 begin
26250      return 1.0;
26251 end One;
26252 @end cartouche
26253 @end group
26254 @end smallexample
26255
26256 @noindent
26257 will obviously raise @code{Program_Error} at run time, because function
26258 One will be called before its body is elaborated. In this case GNAT will
26259 generate a warning that the call will raise @code{Program_Error}:
26260
26261 @smallexample
26262 @group
26263 @cartouche
26264  1. procedure y is
26265  2.    function One return Float;
26266  3.
26267  4.    Q : Float := One;
26268                     |
26269     >>> warning: cannot call "One" before body is elaborated
26270     >>> warning: Program_Error will be raised at run time
26271
26272  5.
26273  6.    function One return Float is
26274  7.    begin
26275  8.         return 1.0;
26276  9.    end One;
26277 10.
26278 11. begin
26279 12.    null;
26280 13. end;
26281 @end cartouche
26282 @end group
26283 @end smallexample
26284
26285 @noindent
26286 Note that in this particular case, it is likely that the call is safe, because
26287 the function @code{One} does not access any global variables.
26288 Nevertheless in Ada, we do not want the validity of the check to depend on
26289 the contents of the body (think about the separate compilation case), so this
26290 is still wrong, as we discussed in the previous sections.
26291
26292 The error is easily corrected by rearranging the declarations so that the
26293 body of @code{One} appears before the declaration containing the call
26294 (note that in Ada 95 and Ada 2005,
26295 declarations can appear in any order, so there is no restriction that
26296 would prevent this reordering, and if we write:
26297
26298 @smallexample @c ada
26299 @group
26300 @cartouche
26301 function One return Float;
26302
26303 function One return Float is
26304 begin
26305      return 1.0;
26306 end One;
26307
26308 Q : Float := One;
26309 @end cartouche
26310 @end group
26311 @end smallexample
26312
26313 @noindent
26314 then all is well, no warning is generated, and no
26315 @code{Program_Error} exception
26316 will be raised.
26317 Things are more complicated when a chain of subprograms is executed:
26318
26319 @smallexample @c ada
26320 @group
26321 @cartouche
26322 function A return Integer;
26323 function B return Integer;
26324 function C return Integer;
26325
26326 function B return Integer is begin return A; end;
26327 function C return Integer is begin return B; end;
26328
26329 X : Integer := C;
26330
26331 function A return Integer is begin return 1; end;
26332 @end cartouche
26333 @end group
26334 @end smallexample
26335
26336 @noindent
26337 Now the call to @code{C}
26338 at elaboration time in the declaration of @code{X} is correct, because
26339 the body of @code{C} is already elaborated,
26340 and the call to @code{B} within the body of
26341 @code{C} is correct, but the call
26342 to @code{A} within the body of @code{B} is incorrect, because the body
26343 of @code{A} has not been elaborated, so @code{Program_Error}
26344 will be raised on the call to @code{A}.
26345 In this case GNAT will generate a
26346 warning that @code{Program_Error} may be
26347 raised at the point of the call. Let's look at the warning:
26348
26349 @smallexample
26350 @group
26351 @cartouche
26352  1. procedure x is
26353  2.    function A return Integer;
26354  3.    function B return Integer;
26355  4.    function C return Integer;
26356  5.
26357  6.    function B return Integer is begin return A; end;
26358                                                     |
26359     >>> warning: call to "A" before body is elaborated may
26360                  raise Program_Error
26361     >>> warning: "B" called at line 7
26362     >>> warning: "C" called at line 9
26363
26364  7.    function C return Integer is begin return B; end;
26365  8.
26366  9.    X : Integer := C;
26367 10.
26368 11.    function A return Integer is begin return 1; end;
26369 12.
26370 13. begin
26371 14.    null;
26372 15. end;
26373 @end cartouche
26374 @end group
26375 @end smallexample
26376
26377 @noindent
26378 Note that the message here says ``may raise'', instead of the direct case,
26379 where the message says ``will be raised''. That's because whether
26380 @code{A} is
26381 actually called depends in general on run-time flow of control.
26382 For example, if the body of @code{B} said
26383
26384 @smallexample @c ada
26385 @group
26386 @cartouche
26387 function B return Integer is
26388 begin
26389    if some-condition-depending-on-input-data then
26390       return A;
26391    else
26392       return 1;
26393    end if;
26394 end B;
26395 @end cartouche
26396 @end group
26397 @end smallexample
26398
26399 @noindent
26400 then we could not know until run time whether the incorrect call to A would
26401 actually occur, so @code{Program_Error} might
26402 or might not be raised. It is possible for a compiler to
26403 do a better job of analyzing bodies, to
26404 determine whether or not @code{Program_Error}
26405 might be raised, but it certainly
26406 couldn't do a perfect job (that would require solving the halting problem
26407 and is provably impossible), and because this is a warning anyway, it does
26408 not seem worth the effort to do the analysis. Cases in which it
26409 would be relevant are rare.
26410
26411 In practice, warnings of either of the forms given
26412 above will usually correspond to
26413 real errors, and should be examined carefully and eliminated.
26414 In the rare case where a warning is bogus, it can be suppressed by any of
26415 the following methods:
26416
26417 @itemize @bullet
26418 @item
26419 Compile with the @option{-gnatws} switch set
26420
26421 @item
26422 Suppress @code{Elaboration_Check} for the called subprogram
26423
26424 @item
26425 Use pragma @code{Warnings_Off} to turn warnings off for the call
26426 @end itemize
26427
26428 @noindent
26429 For the internal elaboration check case,
26430 GNAT by default generates the
26431 necessary run-time checks to ensure
26432 that @code{Program_Error} is raised if any
26433 call fails an elaboration check. Of course this can only happen if a
26434 warning has been issued as described above. The use of pragma
26435 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
26436 some of these checks, meaning that it may be possible (but is not
26437 guaranteed) for a program to be able to call a subprogram whose body
26438 is not yet elaborated, without raising a @code{Program_Error} exception.
26439
26440 @node Controlling Elaboration in GNAT - External Calls
26441 @section Controlling Elaboration in GNAT - External Calls
26442
26443 @noindent
26444 The previous section discussed the case in which the execution of a
26445 particular thread of elaboration code occurred entirely within a
26446 single unit. This is the easy case to handle, because a programmer
26447 has direct and total control over the order of elaboration, and
26448 furthermore, checks need only be generated in cases which are rare
26449 and which the compiler can easily detect.
26450 The situation is more complex when separate compilation is taken into account.
26451 Consider the following:
26452
26453 @smallexample @c ada
26454 @cartouche
26455 @group
26456 package Math is
26457    function Sqrt (Arg : Float) return Float;
26458 end Math;
26459
26460 package body Math is
26461    function Sqrt (Arg : Float) return Float is
26462    begin
26463          ...
26464    end Sqrt;
26465 end Math;
26466 @end group
26467 @group
26468 with Math;
26469 package Stuff is
26470    X : Float := Math.Sqrt (0.5);
26471 end Stuff;
26472
26473 with Stuff;
26474 procedure Main is
26475 begin
26476    ...
26477 end Main;
26478 @end group
26479 @end cartouche
26480 @end smallexample
26481
26482 @noindent
26483 where @code{Main} is the main program. When this program is executed, the
26484 elaboration code must first be executed, and one of the jobs of the
26485 binder is to determine the order in which the units of a program are
26486 to be elaborated. In this case we have four units: the spec and body
26487 of @code{Math},
26488 the spec of @code{Stuff} and the body of @code{Main}).
26489 In what order should the four separate sections of elaboration code
26490 be executed?
26491
26492 There are some restrictions in the order of elaboration that the binder
26493 can choose. In particular, if unit U has a @code{with}
26494 for a package @code{X}, then you
26495 are assured that the spec of @code{X}
26496 is elaborated before U , but you are
26497 not assured that the body of @code{X}
26498 is elaborated before U.
26499 This means that in the above case, the binder is allowed to choose the
26500 order:
26501
26502 @smallexample
26503 spec of Math
26504 spec of Stuff
26505 body of Math
26506 body of Main
26507 @end smallexample
26508
26509 @noindent
26510 but that's not good, because now the call to @code{Math.Sqrt}
26511 that happens during
26512 the elaboration of the @code{Stuff}
26513 spec happens before the body of @code{Math.Sqrt} is
26514 elaborated, and hence causes @code{Program_Error} exception to be raised.
26515 At first glance, one might say that the binder is misbehaving, because
26516 obviously you want to elaborate the body of something you @code{with}
26517 first, but
26518 that is not a general rule that can be followed in all cases. Consider
26519
26520 @smallexample @c ada
26521 @group
26522 @cartouche
26523 package X is ...
26524
26525 package Y is ...
26526
26527 with X;
26528 package body Y is ...
26529
26530 with Y;
26531 package body X is ...
26532 @end cartouche
26533 @end group
26534 @end smallexample
26535
26536 @noindent
26537 This is a common arrangement, and, apart from the order of elaboration
26538 problems that might arise in connection with elaboration code, this works fine.
26539 A rule that says that you must first elaborate the body of anything you
26540 @code{with} cannot work in this case:
26541 the body of @code{X} @code{with}'s @code{Y},
26542 which means you would have to
26543 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
26544 which means
26545 you have to elaborate the body of @code{X} first, but ... and we have a
26546 loop that cannot be broken.
26547
26548 It is true that the binder can in many cases guess an order of elaboration
26549 that is unlikely to cause a @code{Program_Error}
26550 exception to be raised, and it tries to do so (in the
26551 above example of @code{Math/Stuff/Spec}, the GNAT binder will
26552 by default
26553 elaborate the body of @code{Math} right after its spec, so all will be well).
26554
26555 However, a program that blindly relies on the binder to be helpful can
26556 get into trouble, as we discussed in the previous sections, so
26557 GNAT
26558 provides a number of facilities for assisting the programmer in
26559 developing programs that are robust with respect to elaboration order.
26560
26561 @node Default Behavior in GNAT - Ensuring Safety
26562 @section Default Behavior in GNAT - Ensuring Safety
26563
26564 @noindent
26565 The default behavior in GNAT ensures elaboration safety. In its
26566 default mode GNAT implements the
26567 rule we previously described as the right approach. Let's restate it:
26568
26569 @itemize
26570 @item
26571 @emph{If a unit has elaboration code that can directly or indirectly make a
26572 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
26573 package in a @code{with}'ed unit, then if the @code{with}'ed unit
26574 does not have pragma @code{Pure} or
26575 @code{Preelaborate}, then the client should have an
26576 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
26577
26578 @emph{In the case of instantiating a generic subprogram, it is always
26579 sufficient to have only an @code{Elaborate} pragma for the
26580 @code{with}'ed unit.}
26581 @end itemize
26582
26583 @noindent
26584 By following this rule a client is assured that calls and instantiations
26585 can be made without risk of an exception.
26586
26587 In this mode GNAT traces all calls that are potentially made from
26588 elaboration code, and puts in any missing implicit @code{Elaborate}
26589 and @code{Elaborate_All} pragmas.
26590 The advantage of this approach is that no elaboration problems
26591 are possible if the binder can find an elaboration order that is
26592 consistent with these implicit @code{Elaborate} and
26593 @code{Elaborate_All} pragmas. The
26594 disadvantage of this approach is that no such order may exist.
26595
26596 If the binder does not generate any diagnostics, then it means that it has
26597 found an elaboration order that is guaranteed to be safe. However, the binder
26598 may still be relying on implicitly generated @code{Elaborate} and
26599 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
26600 guaranteed.
26601
26602 If it is important to guarantee portability, then the compilations should
26603 use the
26604 @option{-gnatwl}
26605 (warn on elaboration problems) switch. This will cause warning messages
26606 to be generated indicating the missing @code{Elaborate} and
26607 @code{Elaborate_All} pragmas.
26608 Consider the following source program:
26609
26610 @smallexample @c ada
26611 @group
26612 @cartouche
26613 with k;
26614 package j is
26615   m : integer := k.r;
26616 end;
26617 @end cartouche
26618 @end group
26619 @end smallexample
26620
26621 @noindent
26622 where it is clear that there
26623 should be a pragma @code{Elaborate_All}
26624 for unit @code{k}. An implicit pragma will be generated, and it is
26625 likely that the binder will be able to honor it. However, if you want
26626 to port this program to some other Ada compiler than GNAT.
26627 it is safer to include the pragma explicitly in the source. If this
26628 unit is compiled with the
26629 @option{-gnatwl}
26630 switch, then the compiler outputs a warning:
26631
26632 @smallexample
26633 @group
26634 @cartouche
26635 1. with k;
26636 2. package j is
26637 3.   m : integer := k.r;
26638                      |
26639    >>> warning: call to "r" may raise Program_Error
26640    >>> warning: missing pragma Elaborate_All for "k"
26641
26642 4. end;
26643 @end cartouche
26644 @end group
26645 @end smallexample
26646
26647 @noindent
26648 and these warnings can be used as a guide for supplying manually
26649 the missing pragmas. It is usually a bad idea to use this warning
26650 option during development. That's because it will warn you when
26651 you need to put in a pragma, but cannot warn you when it is time
26652 to take it out. So the use of pragma @code{Elaborate_All} may lead to
26653 unnecessary dependencies and even false circularities.
26654
26655 This default mode is more restrictive than the Ada Reference
26656 Manual, and it is possible to construct programs which will compile
26657 using the dynamic model described there, but will run into a
26658 circularity using the safer static model we have described.
26659
26660 Of course any Ada compiler must be able to operate in a mode
26661 consistent with the requirements of the Ada Reference Manual,
26662 and in particular must have the capability of implementing the
26663 standard dynamic model of elaboration with run-time checks.
26664
26665 In GNAT, this standard mode can be achieved either by the use of
26666 the @option{-gnatE} switch on the compiler (@command{gcc} or
26667 @command{gnatmake}) command, or by the use of the configuration pragma:
26668
26669 @smallexample @c ada
26670 pragma Elaboration_Checks (RM);
26671 @end smallexample
26672
26673 @noindent
26674 Either approach will cause the unit affected to be compiled using the
26675 standard dynamic run-time elaboration checks described in the Ada
26676 Reference Manual. The static model is generally preferable, since it
26677 is clearly safer to rely on compile and link time checks rather than
26678 run-time checks. However, in the case of legacy code, it may be
26679 difficult to meet the requirements of the static model. This
26680 issue is further discussed in
26681 @ref{What to Do If the Default Elaboration Behavior Fails}.
26682
26683 Note that the static model provides a strict subset of the allowed
26684 behavior and programs of the Ada Reference Manual, so if you do
26685 adhere to the static model and no circularities exist,
26686 then you are assured that your program will
26687 work using the dynamic model, providing that you remove any
26688 pragma Elaborate statements from the source.
26689
26690 @node Treatment of Pragma Elaborate
26691 @section Treatment of Pragma Elaborate
26692 @cindex Pragma Elaborate
26693
26694 @noindent
26695 The use of @code{pragma Elaborate}
26696 should generally be avoided in Ada 95 and Ada 2005 programs,
26697 since there is no guarantee that transitive calls
26698 will be properly handled. Indeed at one point, this pragma was placed
26699 in Annex J (Obsolescent Features), on the grounds that it is never useful.
26700
26701 Now that's a bit restrictive. In practice, the case in which
26702 @code{pragma Elaborate} is useful is when the caller knows that there
26703 are no transitive calls, or that the called unit contains all necessary
26704 transitive @code{pragma Elaborate} statements, and legacy code often
26705 contains such uses.
26706
26707 Strictly speaking the static mode in GNAT should ignore such pragmas,
26708 since there is no assurance at compile time that the necessary safety
26709 conditions are met. In practice, this would cause GNAT to be incompatible
26710 with correctly written Ada 83 code that had all necessary
26711 @code{pragma Elaborate} statements in place. Consequently, we made the
26712 decision that GNAT in its default mode will believe that if it encounters
26713 a @code{pragma Elaborate} then the programmer knows what they are doing,
26714 and it will trust that no elaboration errors can occur.
26715
26716 The result of this decision is two-fold. First to be safe using the
26717 static mode, you should remove all @code{pragma Elaborate} statements.
26718 Second, when fixing circularities in existing code, you can selectively
26719 use @code{pragma Elaborate} statements to convince the static mode of
26720 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
26721 statement.
26722
26723 When using the static mode with @option{-gnatwl}, any use of
26724 @code{pragma Elaborate} will generate a warning about possible
26725 problems.
26726
26727 @node Elaboration Issues for Library Tasks
26728 @section Elaboration Issues for Library Tasks
26729 @cindex Library tasks, elaboration issues
26730 @cindex Elaboration of library tasks
26731
26732 @noindent
26733 In this section we examine special elaboration issues that arise for
26734 programs that declare library level tasks.
26735
26736 Generally the model of execution of an Ada program is that all units are
26737 elaborated, and then execution of the program starts. However, the
26738 declaration of library tasks definitely does not fit this model. The
26739 reason for this is that library tasks start as soon as they are declared
26740 (more precisely, as soon as the statement part of the enclosing package
26741 body is reached), that is to say before elaboration
26742 of the program is complete. This means that if such a task calls a
26743 subprogram, or an entry in another task, the callee may or may not be
26744 elaborated yet, and in the standard
26745 Reference Manual model of dynamic elaboration checks, you can even
26746 get timing dependent Program_Error exceptions, since there can be
26747 a race between the elaboration code and the task code.
26748
26749 The static model of elaboration in GNAT seeks to avoid all such
26750 dynamic behavior, by being conservative, and the conservative
26751 approach in this particular case is to assume that all the code
26752 in a task body is potentially executed at elaboration time if
26753 a task is declared at the library level.
26754
26755 This can definitely result in unexpected circularities. Consider
26756 the following example
26757
26758 @smallexample @c ada
26759 package Decls is
26760   task Lib_Task is
26761      entry Start;
26762   end Lib_Task;
26763
26764   type My_Int is new Integer;
26765
26766   function Ident (M : My_Int) return My_Int;
26767 end Decls;
26768
26769 with Utils;
26770 package body Decls is
26771   task body Lib_Task is
26772   begin
26773      accept Start;
26774      Utils.Put_Val (2);
26775   end Lib_Task;
26776
26777   function Ident (M : My_Int) return My_Int is
26778   begin
26779      return M;
26780   end Ident;
26781 end Decls;
26782
26783 with Decls;
26784 package Utils is
26785   procedure Put_Val (Arg : Decls.My_Int);
26786 end Utils;
26787
26788 with Text_IO;
26789 package body Utils is
26790   procedure Put_Val (Arg : Decls.My_Int) is
26791   begin
26792      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26793   end Put_Val;
26794 end Utils;
26795
26796 with Decls;
26797 procedure Main is
26798 begin
26799    Decls.Lib_Task.Start;
26800 end;
26801 @end smallexample
26802
26803 @noindent
26804 If the above example is compiled in the default static elaboration
26805 mode, then a circularity occurs. The circularity comes from the call
26806 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
26807 this call occurs in elaboration code, we need an implicit pragma
26808 @code{Elaborate_All} for @code{Utils}. This means that not only must
26809 the spec and body of @code{Utils} be elaborated before the body
26810 of @code{Decls}, but also the spec and body of any unit that is
26811 @code{with'ed} by the body of @code{Utils} must also be elaborated before
26812 the body of @code{Decls}. This is the transitive implication of
26813 pragma @code{Elaborate_All} and it makes sense, because in general
26814 the body of @code{Put_Val} might have a call to something in a
26815 @code{with'ed} unit.
26816
26817 In this case, the body of Utils (actually its spec) @code{with's}
26818 @code{Decls}. Unfortunately this means that the body of @code{Decls}
26819 must be elaborated before itself, in case there is a call from the
26820 body of @code{Utils}.
26821
26822 Here is the exact chain of events we are worrying about:
26823
26824 @enumerate
26825 @item
26826 In the body of @code{Decls} a call is made from within the body of a library
26827 task to a subprogram in the package @code{Utils}. Since this call may
26828 occur at elaboration time (given that the task is activated at elaboration
26829 time), we have to assume the worst, i.e. that the
26830 call does happen at elaboration time.
26831
26832 @item
26833 This means that the body and spec of @code{Util} must be elaborated before
26834 the body of @code{Decls} so that this call does not cause an access before
26835 elaboration.
26836
26837 @item
26838 Within the body of @code{Util}, specifically within the body of
26839 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
26840 by this package.
26841
26842 @item
26843 One such @code{with}'ed package is package @code{Decls}, so there
26844 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
26845 In fact there is such a call in this example, but we would have to
26846 assume that there was such a call even if it were not there, since
26847 we are not supposed to write the body of @code{Decls} knowing what
26848 is in the body of @code{Utils}; certainly in the case of the
26849 static elaboration model, the compiler does not know what is in
26850 other bodies and must assume the worst.
26851
26852 @item
26853 This means that the spec and body of @code{Decls} must also be
26854 elaborated before we elaborate the unit containing the call, but
26855 that unit is @code{Decls}! This means that the body of @code{Decls}
26856 must be elaborated before itself, and that's a circularity.
26857 @end enumerate
26858
26859 @noindent
26860 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
26861 the body of @code{Decls} you will get a true Ada Reference Manual
26862 circularity that makes the program illegal.
26863
26864 In practice, we have found that problems with the static model of
26865 elaboration in existing code often arise from library tasks, so
26866 we must address this particular situation.
26867
26868 Note that if we compile and run the program above, using the dynamic model of
26869 elaboration (that is to say use the @option{-gnatE} switch),
26870 then it compiles, binds,
26871 links, and runs, printing the expected result of 2. Therefore in some sense
26872 the circularity here is only apparent, and we need to capture
26873 the properties of this program that  distinguish it from other library-level
26874 tasks that have real elaboration problems.
26875
26876 We have four possible answers to this question:
26877
26878 @itemize @bullet
26879
26880 @item
26881 Use the dynamic model of elaboration.
26882
26883 If we use the @option{-gnatE} switch, then as noted above, the program works.
26884 Why is this? If we examine the task body, it is apparent that the task cannot
26885 proceed past the
26886 @code{accept} statement until after elaboration has been completed, because
26887 the corresponding entry call comes from the main program, not earlier.
26888 This is why the dynamic model works here. But that's really giving
26889 up on a precise analysis, and we prefer to take this approach only if we cannot
26890 solve the
26891 problem in any other manner. So let us examine two ways to reorganize
26892 the program to avoid the potential elaboration problem.
26893
26894 @item
26895 Split library tasks into separate packages.
26896
26897 Write separate packages, so that library tasks are isolated from
26898 other declarations as much as possible. Let us look at a variation on
26899 the above program.
26900
26901 @smallexample @c ada
26902 package Decls1 is
26903   task Lib_Task is
26904      entry Start;
26905   end Lib_Task;
26906 end Decls1;
26907
26908 with Utils;
26909 package body Decls1 is
26910   task body Lib_Task is
26911   begin
26912      accept Start;
26913      Utils.Put_Val (2);
26914   end Lib_Task;
26915 end Decls1;
26916
26917 package Decls2 is
26918   type My_Int is new Integer;
26919   function Ident (M : My_Int) return My_Int;
26920 end Decls2;
26921
26922 with Utils;
26923 package body Decls2 is
26924   function Ident (M : My_Int) return My_Int is
26925   begin
26926      return M;
26927   end Ident;
26928 end Decls2;
26929
26930 with Decls2;
26931 package Utils is
26932   procedure Put_Val (Arg : Decls2.My_Int);
26933 end Utils;
26934
26935 with Text_IO;
26936 package body Utils is
26937   procedure Put_Val (Arg : Decls2.My_Int) is
26938   begin
26939      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
26940   end Put_Val;
26941 end Utils;
26942
26943 with Decls1;
26944 procedure Main is
26945 begin
26946    Decls1.Lib_Task.Start;
26947 end;
26948 @end smallexample
26949
26950 @noindent
26951 All we have done is to split @code{Decls} into two packages, one
26952 containing the library task, and one containing everything else. Now
26953 there is no cycle, and the program compiles, binds, links and executes
26954 using the default static model of elaboration.
26955
26956 @item
26957 Declare separate task types.
26958
26959 A significant part of the problem arises because of the use of the
26960 single task declaration form. This means that the elaboration of
26961 the task type, and the elaboration of the task itself (i.e. the
26962 creation of the task) happen at the same time. A good rule
26963 of style in Ada is to always create explicit task types. By
26964 following the additional step of placing task objects in separate
26965 packages from the task type declaration, many elaboration problems
26966 are avoided. Here is another modified example of the example program:
26967
26968 @smallexample @c ada
26969 package Decls is
26970   task type Lib_Task_Type is
26971      entry Start;
26972   end Lib_Task_Type;
26973
26974   type My_Int is new Integer;
26975
26976   function Ident (M : My_Int) return My_Int;
26977 end Decls;
26978
26979 with Utils;
26980 package body Decls is
26981   task body Lib_Task_Type is
26982   begin
26983      accept Start;
26984      Utils.Put_Val (2);
26985   end Lib_Task_Type;
26986
26987   function Ident (M : My_Int) return My_Int is
26988   begin
26989      return M;
26990   end Ident;
26991 end Decls;
26992
26993 with Decls;
26994 package Utils is
26995   procedure Put_Val (Arg : Decls.My_Int);
26996 end Utils;
26997
26998 with Text_IO;
26999 package body Utils is
27000   procedure Put_Val (Arg : Decls.My_Int) is
27001   begin
27002      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27003   end Put_Val;
27004 end Utils;
27005
27006 with Decls;
27007 package Declst is
27008    Lib_Task : Decls.Lib_Task_Type;
27009 end Declst;
27010
27011 with Declst;
27012 procedure Main is
27013 begin
27014    Declst.Lib_Task.Start;
27015 end;
27016 @end smallexample
27017
27018 @noindent
27019 What we have done here is to replace the @code{task} declaration in
27020 package @code{Decls} with a @code{task type} declaration. Then we
27021 introduce a separate package @code{Declst} to contain the actual
27022 task object. This separates the elaboration issues for
27023 the @code{task type}
27024 declaration, which causes no trouble, from the elaboration issues
27025 of the task object, which is also unproblematic, since it is now independent
27026 of the elaboration of  @code{Utils}.
27027 This separation of concerns also corresponds to
27028 a generally sound engineering principle of separating declarations
27029 from instances. This version of the program also compiles, binds, links,
27030 and executes, generating the expected output.
27031
27032 @item
27033 Use No_Entry_Calls_In_Elaboration_Code restriction.
27034 @cindex No_Entry_Calls_In_Elaboration_Code
27035
27036 The previous two approaches described how a program can be restructured
27037 to avoid the special problems caused by library task bodies. in practice,
27038 however, such restructuring may be difficult to apply to existing legacy code,
27039 so we must consider solutions that do not require massive rewriting.
27040
27041 Let us consider more carefully why our original sample program works
27042 under the dynamic model of elaboration. The reason is that the code
27043 in the task body blocks immediately on the @code{accept}
27044 statement. Now of course there is nothing to prohibit elaboration
27045 code from making entry calls (for example from another library level task),
27046 so we cannot tell in isolation that
27047 the task will not execute the accept statement  during elaboration.
27048
27049 However, in practice it is very unusual to see elaboration code
27050 make any entry calls, and the pattern of tasks starting
27051 at elaboration time and then immediately blocking on @code{accept} or
27052 @code{select} statements is very common. What this means is that
27053 the compiler is being too pessimistic when it analyzes the
27054 whole package body as though it might be executed at elaboration
27055 time.
27056
27057 If we know that the elaboration code contains no entry calls, (a very safe
27058 assumption most of the time, that could almost be made the default
27059 behavior), then we can compile all units of the program under control
27060 of the following configuration pragma:
27061
27062 @smallexample
27063 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
27064 @end smallexample
27065
27066 @noindent
27067 This pragma can be placed in the @file{gnat.adc} file in the usual
27068 manner. If we take our original unmodified program and compile it
27069 in the presence of a @file{gnat.adc} containing the above pragma,
27070 then once again, we can compile, bind, link, and execute, obtaining
27071 the expected result. In the presence of this pragma, the compiler does
27072 not trace calls in a task body, that appear after the first @code{accept}
27073 or @code{select} statement, and therefore does not report a potential
27074 circularity in the original program.
27075
27076 The compiler will check to the extent it can that the above
27077 restriction is not violated, but it is not always possible to do a
27078 complete check at compile time, so it is important to use this
27079 pragma only if the stated restriction is in fact met, that is to say
27080 no task receives an entry call before elaboration of all units is completed.
27081
27082 @end itemize
27083
27084 @node Mixing Elaboration Models
27085 @section Mixing Elaboration Models
27086 @noindent
27087 So far, we have assumed that the entire program is either compiled
27088 using the dynamic model or static model, ensuring consistency. It
27089 is possible to mix the two models, but rules have to be followed
27090 if this mixing is done to ensure that elaboration checks are not
27091 omitted.
27092
27093 The basic rule is that @emph{a unit compiled with the static model cannot
27094 be @code{with'ed} by a unit compiled with the dynamic model}. The
27095 reason for this is that in the static model, a unit assumes that
27096 its clients guarantee to use (the equivalent of) pragma
27097 @code{Elaborate_All} so that no elaboration checks are required
27098 in inner subprograms, and this assumption is violated if the
27099 client is compiled with dynamic checks.
27100
27101 The precise rule is as follows. A unit that is compiled with dynamic
27102 checks can only @code{with} a unit that meets at least one of the
27103 following criteria:
27104
27105 @itemize @bullet
27106
27107 @item
27108 The @code{with'ed} unit is itself compiled with dynamic elaboration
27109 checks (that is with the @option{-gnatE} switch.
27110
27111 @item
27112 The @code{with'ed} unit is an internal GNAT implementation unit from
27113 the System, Interfaces, Ada, or GNAT hierarchies.
27114
27115 @item
27116 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
27117
27118 @item
27119 The @code{with'ing} unit (that is the client) has an explicit pragma
27120 @code{Elaborate_All} for the @code{with'ed} unit.
27121
27122 @end itemize
27123
27124 @noindent
27125 If this rule is violated, that is if a unit with dynamic elaboration
27126 checks @code{with's} a unit that does not meet one of the above four
27127 criteria, then the binder (@code{gnatbind}) will issue a warning
27128 similar to that in the following example:
27129
27130 @smallexample
27131 warning: "x.ads" has dynamic elaboration checks and with's
27132 warning:   "y.ads" which has static elaboration checks
27133 @end smallexample
27134
27135 @noindent
27136 These warnings indicate that the rule has been violated, and that as a result
27137 elaboration checks may be missed in the resulting executable file.
27138 This warning may be suppressed using the @option{-ws} binder switch
27139 in the usual manner.
27140
27141 One useful application of this mixing rule is in the case of a subsystem
27142 which does not itself @code{with} units from the remainder of the
27143 application. In this case, the entire subsystem can be compiled with
27144 dynamic checks to resolve a circularity in the subsystem, while
27145 allowing the main application that uses this subsystem to be compiled
27146 using the more reliable default static model.
27147
27148 @node What to Do If the Default Elaboration Behavior Fails
27149 @section What to Do If the Default Elaboration Behavior Fails
27150
27151 @noindent
27152 If the binder cannot find an acceptable order, it outputs detailed
27153 diagnostics. For example:
27154 @smallexample
27155 @group
27156 @iftex
27157 @leftskip=0cm
27158 @end iftex
27159 error: elaboration circularity detected
27160 info:   "proc (body)" must be elaborated before "pack (body)"
27161 info:     reason: Elaborate_All probably needed in unit "pack (body)"
27162 info:     recompile "pack (body)" with -gnatwl
27163 info:                             for full details
27164 info:       "proc (body)"
27165 info:         is needed by its spec:
27166 info:       "proc (spec)"
27167 info:         which is withed by:
27168 info:       "pack (body)"
27169 info:  "pack (body)" must be elaborated before "proc (body)"
27170 info:     reason: pragma Elaborate in unit "proc (body)"
27171 @end group
27172
27173 @end smallexample
27174
27175 @noindent
27176 In this case we have a cycle that the binder cannot break. On the one
27177 hand, there is an explicit pragma Elaborate in @code{proc} for
27178 @code{pack}. This means that the body of @code{pack} must be elaborated
27179 before the body of @code{proc}. On the other hand, there is elaboration
27180 code in @code{pack} that calls a subprogram in @code{proc}. This means
27181 that for maximum safety, there should really be a pragma
27182 Elaborate_All in @code{pack} for @code{proc} which would require that
27183 the body of @code{proc} be elaborated before the body of
27184 @code{pack}. Clearly both requirements cannot be satisfied.
27185 Faced with a circularity of this kind, you have three different options.
27186
27187 @table @asis
27188 @item Fix the program
27189 The most desirable option from the point of view of long-term maintenance
27190 is to rearrange the program so that the elaboration problems are avoided.
27191 One useful technique is to place the elaboration code into separate
27192 child packages. Another is to move some of the initialization code to
27193 explicitly called subprograms, where the program controls the order
27194 of initialization explicitly. Although this is the most desirable option,
27195 it may be impractical and involve too much modification, especially in
27196 the case of complex legacy code.
27197
27198 @item Perform dynamic checks
27199 If the compilations are done using the
27200 @option{-gnatE}
27201 (dynamic elaboration check) switch, then GNAT behaves in a quite different
27202 manner. Dynamic checks are generated for all calls that could possibly result
27203 in raising an exception. With this switch, the compiler does not generate
27204 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
27205 exactly as specified in the @cite{Ada Reference Manual}.
27206 The binder will generate
27207 an executable program that may or may not raise @code{Program_Error}, and then
27208 it is the programmer's job to ensure that it does not raise an exception. Note
27209 that it is important to compile all units with the switch, it cannot be used
27210 selectively.
27211
27212 @item Suppress checks
27213 The drawback of dynamic checks is that they generate a
27214 significant overhead at run time, both in space and time. If you
27215 are absolutely sure that your program cannot raise any elaboration
27216 exceptions, and you still want to use the dynamic elaboration model,
27217 then you can use the configuration pragma
27218 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
27219 example this pragma could be placed in the @file{gnat.adc} file.
27220
27221 @item Suppress checks selectively
27222 When you know that certain calls or instantiations in elaboration code cannot
27223 possibly lead to an elaboration error, and the binder nevertheless complains
27224 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
27225 elaboration circularities, it is possible to remove those warnings locally and
27226 obtain a program that will bind. Clearly this can be unsafe, and it is the
27227 responsibility of the programmer to make sure that the resulting program has no
27228 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
27229 used with different granularity to suppress warnings and break elaboration
27230 circularities:
27231
27232 @itemize @bullet
27233 @item
27234 Place the pragma that names the called subprogram in the declarative part
27235 that contains the call.
27236
27237 @item
27238 Place the pragma in the declarative part, without naming an entity. This
27239 disables warnings on all calls in the corresponding  declarative region.
27240
27241 @item
27242 Place the pragma in the package spec that declares the called subprogram,
27243 and name the subprogram. This disables warnings on all elaboration calls to
27244 that subprogram.
27245
27246 @item
27247 Place the pragma in the package spec that declares the called subprogram,
27248 without naming any entity. This disables warnings on all elaboration calls to
27249 all subprograms declared in this spec.
27250
27251 @item Use Pragma Elaborate
27252 As previously described in section @xref{Treatment of Pragma Elaborate},
27253 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
27254 that no elaboration checks are required on calls to the designated unit.
27255 There may be cases in which the caller knows that no transitive calls
27256 can occur, so that a @code{pragma Elaborate} will be sufficient in a
27257 case where @code{pragma Elaborate_All} would cause a circularity.
27258 @end itemize
27259
27260 @noindent
27261 These five cases are listed in order of decreasing safety, and therefore
27262 require increasing programmer care in their application. Consider the
27263 following program:
27264
27265 @smallexample @c adanocomment
27266 package Pack1 is
27267   function F1 return Integer;
27268   X1 : Integer;
27269 end Pack1;
27270
27271 package Pack2 is
27272   function F2 return Integer;
27273   function Pure (x : integer) return integer;
27274   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
27275   --  pragma Suppress (Elaboration_Check);              -- (4)
27276 end Pack2;
27277
27278 with Pack2;
27279 package body Pack1 is
27280   function F1 return Integer is
27281   begin
27282     return 100;
27283   end F1;
27284   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
27285 begin
27286   declare
27287     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
27288     --  pragma Suppress(Elaboration_Check);             -- (2)
27289   begin
27290     X1 := Pack2.F2 + 1;                --  Elab. call (2)
27291   end;
27292 end Pack1;
27293
27294 with Pack1;
27295 package body Pack2 is
27296   function F2 return Integer is
27297   begin
27298      return Pack1.F1;
27299   end F2;
27300   function Pure (x : integer) return integer is
27301   begin
27302      return x ** 3 - 3 * x;
27303   end;
27304 end Pack2;
27305
27306 with Pack1, Ada.Text_IO;
27307 procedure Proc3 is
27308 begin
27309   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
27310 end Proc3;
27311 @end smallexample
27312 In the absence of any pragmas, an attempt to bind this program produces
27313 the following diagnostics:
27314 @smallexample
27315 @group
27316 @iftex
27317 @leftskip=.5cm
27318 @end iftex
27319 error: elaboration circularity detected
27320 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
27321 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
27322 info:       recompile "pack1 (body)" with -gnatwl for full details
27323 info:          "pack1 (body)"
27324 info:             must be elaborated along with its spec:
27325 info:          "pack1 (spec)"
27326 info:             which is withed by:
27327 info:          "pack2 (body)"
27328 info:             which must be elaborated along with its spec:
27329 info:          "pack2 (spec)"
27330 info:             which is withed by:
27331 info:          "pack1 (body)"
27332 @end group
27333 @end smallexample
27334 The sources of the circularity are the two calls to @code{Pack2.Pure} and
27335 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
27336 F2 is safe, even though F2 calls F1, because the call appears after the
27337 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
27338 remove the warning on the call. It is also possible to use pragma (2)
27339 because there are no other potentially unsafe calls in the block.
27340
27341 @noindent
27342 The call to @code{Pure} is safe because this function does not depend on the
27343 state of @code{Pack2}. Therefore any call to this function is safe, and it
27344 is correct to place pragma (3) in the corresponding package spec.
27345
27346 @noindent
27347 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
27348 warnings on all calls to functions declared therein. Note that this is not
27349 necessarily safe, and requires more detailed examination of the subprogram
27350 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
27351 be already elaborated.
27352 @end table
27353
27354 @noindent
27355 It is hard to generalize on which of these four approaches should be
27356 taken. Obviously if it is possible to fix the program so that the default
27357 treatment works, this is preferable, but this may not always be practical.
27358 It is certainly simple enough to use
27359 @option{-gnatE}
27360 but the danger in this case is that, even if the GNAT binder
27361 finds a correct elaboration order, it may not always do so,
27362 and certainly a binder from another Ada compiler might not. A
27363 combination of testing and analysis (for which the warnings generated
27364 with the
27365 @option{-gnatwl}
27366 switch can be useful) must be used to ensure that the program is free
27367 of errors. One switch that is useful in this testing is the
27368 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
27369 switch for
27370 @code{gnatbind}.
27371 Normally the binder tries to find an order that has the best chance
27372 of avoiding elaboration problems. However, if this switch is used, the binder
27373 plays a devil's advocate role, and tries to choose the order that
27374 has the best chance of failing. If your program works even with this
27375 switch, then it has a better chance of being error free, but this is still
27376 not a guarantee.
27377
27378 For an example of this approach in action, consider the C-tests (executable
27379 tests) from the ACVC suite. If these are compiled and run with the default
27380 treatment, then all but one of them succeed without generating any error
27381 diagnostics from the binder. However, there is one test that fails, and
27382 this is not surprising, because the whole point of this test is to ensure
27383 that the compiler can handle cases where it is impossible to determine
27384 a correct order statically, and it checks that an exception is indeed
27385 raised at run time.
27386
27387 This one test must be compiled and run using the
27388 @option{-gnatE}
27389 switch, and then it passes. Alternatively, the entire suite can
27390 be run using this switch. It is never wrong to run with the dynamic
27391 elaboration switch if your code is correct, and we assume that the
27392 C-tests are indeed correct (it is less efficient, but efficiency is
27393 not a factor in running the ACVC tests.)
27394
27395 @node Elaboration for Access-to-Subprogram Values
27396 @section Elaboration for Access-to-Subprogram Values
27397 @cindex Access-to-subprogram
27398
27399 @noindent
27400 Access-to-subprogram types (introduced in Ada 95) complicate
27401 the handling of elaboration. The trouble is that it becomes
27402 impossible to tell at compile time which procedure
27403 is being called. This means that it is not possible for the binder
27404 to analyze the elaboration requirements in this case.
27405
27406 If at the point at which the access value is created
27407 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
27408 the body of the subprogram is
27409 known to have been elaborated, then the access value is safe, and its use
27410 does not require a check. This may be achieved by appropriate arrangement
27411 of the order of declarations if the subprogram is in the current unit,
27412 or, if the subprogram is in another unit, by using pragma
27413 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
27414 on the referenced unit.
27415
27416 If the referenced body is not known to have been elaborated at the point
27417 the access value is created, then any use of the access value must do a
27418 dynamic check, and this dynamic check will fail and raise a
27419 @code{Program_Error} exception if the body has not been elaborated yet.
27420 GNAT will generate the necessary checks, and in addition, if the
27421 @option{-gnatwl}
27422 switch is set, will generate warnings that such checks are required.
27423
27424 The use of dynamic dispatching for tagged types similarly generates
27425 a requirement for dynamic checks, and premature calls to any primitive
27426 operation of a tagged type before the body of the operation has been
27427 elaborated, will result in the raising of @code{Program_Error}.
27428
27429 @node Summary of Procedures for Elaboration Control
27430 @section Summary of Procedures for Elaboration Control
27431 @cindex Elaboration control
27432
27433 @noindent
27434 First, compile your program with the default options, using none of
27435 the special elaboration control switches. If the binder successfully
27436 binds your program, then you can be confident that, apart from issues
27437 raised by the use of access-to-subprogram types and dynamic dispatching,
27438 the program is free of elaboration errors. If it is important that the
27439 program be portable, then use the
27440 @option{-gnatwl}
27441 switch to generate warnings about missing @code{Elaborate} or
27442 @code{Elaborate_All} pragmas, and supply the missing pragmas.
27443
27444 If the program fails to bind using the default static elaboration
27445 handling, then you can fix the program to eliminate the binder
27446 message, or recompile the entire program with the
27447 @option{-gnatE} switch to generate dynamic elaboration checks,
27448 and, if you are sure there really are no elaboration problems,
27449 use a global pragma @code{Suppress (Elaboration_Check)}.
27450
27451 @node Other Elaboration Order Considerations
27452 @section Other Elaboration Order Considerations
27453 @noindent
27454 This section has been entirely concerned with the issue of finding a valid
27455 elaboration order, as defined by the Ada Reference Manual. In a case
27456 where several elaboration orders are valid, the task is to find one
27457 of the possible valid elaboration orders (and the static model in GNAT
27458 will ensure that this is achieved).
27459
27460 The purpose of the elaboration rules in the Ada Reference Manual is to
27461 make sure that no entity is accessed before it has been elaborated. For
27462 a subprogram, this means that the spec and body must have been elaborated
27463 before the subprogram is called. For an object, this means that the object
27464 must have been elaborated before its value is read or written. A violation
27465 of either of these two requirements is an access before elaboration order,
27466 and this section has been all about avoiding such errors.
27467
27468 In the case where more than one order of elaboration is possible, in the
27469 sense that access before elaboration errors are avoided, then any one of
27470 the orders is ``correct'' in the sense that it meets the requirements of
27471 the Ada Reference Manual, and no such error occurs.
27472
27473 However, it may be the case for a given program, that there are
27474 constraints on the order of elaboration that come not from consideration
27475 of avoiding elaboration errors, but rather from extra-lingual logic
27476 requirements. Consider this example:
27477
27478 @smallexample @c ada
27479 with Init_Constants;
27480 package Constants is
27481    X : Integer := 0;
27482    Y : Integer := 0;
27483 end Constants;
27484
27485 package Init_Constants is
27486    procedure P; -- require a body
27487 end Init_Constants;
27488
27489 with Constants;
27490 package body Init_Constants is
27491    procedure P is begin null; end;
27492 begin
27493    Constants.X := 3;
27494    Constants.Y := 4;
27495 end Init_Constants;
27496
27497 with Constants;
27498 package Calc is
27499    Z : Integer := Constants.X + Constants.Y;
27500 end Calc;
27501
27502 with Calc;
27503 with Text_IO; use Text_IO;
27504 procedure Main is
27505 begin
27506    Put_Line (Calc.Z'Img);
27507 end Main;
27508 @end smallexample
27509
27510 @noindent
27511 In this example, there is more than one valid order of elaboration. For
27512 example both the following are correct orders:
27513
27514 @smallexample
27515 Init_Constants spec
27516 Constants spec
27517 Calc spec
27518 Init_Constants body
27519 Main body
27520
27521   and
27522
27523 Init_Constants spec
27524 Init_Constants body
27525 Constants spec
27526 Calc spec
27527 Main body
27528 @end smallexample
27529
27530 @noindent
27531 There is no language rule to prefer one or the other, both are correct
27532 from an order of elaboration point of view. But the programmatic effects
27533 of the two orders are very different. In the first, the elaboration routine
27534 of @code{Calc} initializes @code{Z} to zero, and then the main program
27535 runs with this value of zero. But in the second order, the elaboration
27536 routine of @code{Calc} runs after the body of Init_Constants has set
27537 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
27538 runs.
27539
27540 One could perhaps by applying pretty clever non-artificial intelligence
27541 to the situation guess that it is more likely that the second order of
27542 elaboration is the one desired, but there is no formal linguistic reason
27543 to prefer one over the other. In fact in this particular case, GNAT will
27544 prefer the second order, because of the rule that bodies are elaborated
27545 as soon as possible, but it's just luck that this is what was wanted
27546 (if indeed the second order was preferred).
27547
27548 If the program cares about the order of elaboration routines in a case like
27549 this, it is important to specify the order required. In this particular
27550 case, that could have been achieved by adding to the spec of Calc:
27551
27552 @smallexample @c ada
27553 pragma Elaborate_All (Constants);
27554 @end smallexample
27555
27556 @noindent
27557 which requires that the body (if any) and spec of @code{Constants},
27558 as well as the body and spec of any unit @code{with}'ed by
27559 @code{Constants} be elaborated before @code{Calc} is elaborated.
27560
27561 Clearly no automatic method can always guess which alternative you require,
27562 and if you are working with legacy code that had constraints of this kind
27563 which were not properly specified by adding @code{Elaborate} or
27564 @code{Elaborate_All} pragmas, then indeed it is possible that two different
27565 compilers can choose different orders.
27566
27567 However, GNAT does attempt to diagnose the common situation where there
27568 are uninitialized variables in the visible part of a package spec, and the
27569 corresponding package body has an elaboration block that directly or
27570 indirectly initialized one or more of these variables. This is the situation
27571 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
27572 a warning that suggests this addition if it detects this situation.
27573
27574 The @code{gnatbind}
27575 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
27576 out problems. This switch causes bodies to be elaborated as late as possible
27577 instead of as early as possible. In the example above, it would have forced
27578 the choice of the first elaboration order. If you get different results
27579 when using this switch, and particularly if one set of results is right,
27580 and one is wrong as far as you are concerned, it shows that you have some
27581 missing @code{Elaborate} pragmas. For the example above, we have the
27582 following output:
27583
27584 @smallexample
27585 gnatmake -f -q main
27586 main
27587  7
27588 gnatmake -f -q main -bargs -p
27589 main
27590  0
27591 @end smallexample
27592
27593 @noindent
27594 It is of course quite unlikely that both these results are correct, so
27595 it is up to you in a case like this to investigate the source of the
27596 difference, by looking at the two elaboration orders that are chosen,
27597 and figuring out which is correct, and then adding the necessary
27598 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
27599
27600
27601
27602 @c *******************************
27603 @node Conditional Compilation
27604 @appendix Conditional Compilation
27605 @c *******************************
27606 @cindex Conditional compilation
27607
27608 @noindent
27609 It is often necessary to arrange for a single source program
27610 to serve multiple purposes, where it is compiled in different
27611 ways to achieve these different goals. Some examples of the
27612 need for this feature are
27613
27614 @itemize @bullet
27615 @item  Adapting a program to a different hardware environment
27616 @item  Adapting a program to a different target architecture
27617 @item  Turning debugging features on and off
27618 @item  Arranging for a program to compile with different compilers
27619 @end itemize
27620
27621 @noindent
27622 In C, or C++, the typical approach would be to use the preprocessor
27623 that is defined as part of the language. The Ada language does not
27624 contain such a feature. This is not an oversight, but rather a very
27625 deliberate design decision, based on the experience that overuse of
27626 the preprocessing features in C and C++ can result in programs that
27627 are extremely difficult to maintain. For example, if we have ten
27628 switches that can be on or off, this means that there are a thousand
27629 separate programs, any one of which might not even be syntactically
27630 correct, and even if syntactically correct, the resulting program
27631 might not work correctly. Testing all combinations can quickly become
27632 impossible.
27633
27634 Nevertheless, the need to tailor programs certainly exists, and in
27635 this Appendix we will discuss how this can
27636 be achieved using Ada in general, and GNAT in particular.
27637
27638 @menu
27639 * Use of Boolean Constants::
27640 * Debugging - A Special Case::
27641 * Conditionalizing Declarations::
27642 * Use of Alternative Implementations::
27643 * Preprocessing::
27644 @end menu
27645
27646 @node Use of Boolean Constants
27647 @section Use of Boolean Constants
27648
27649 @noindent
27650 In the case where the difference is simply which code
27651 sequence is executed, the cleanest solution is to use Boolean
27652 constants to control which code is executed.
27653
27654 @smallexample @c ada
27655 @group
27656 FP_Initialize_Required : constant Boolean := True;
27657 ...
27658 if FP_Initialize_Required then
27659 ...
27660 end if;
27661 @end group
27662 @end smallexample
27663
27664 @noindent
27665 Not only will the code inside the @code{if} statement not be executed if
27666 the constant Boolean is @code{False}, but it will also be completely
27667 deleted from the program.
27668 However, the code is only deleted after the @code{if} statement
27669 has been checked for syntactic and semantic correctness.
27670 (In contrast, with preprocessors the code is deleted before the
27671 compiler ever gets to see it, so it is not checked until the switch
27672 is turned on.)
27673 @cindex Preprocessors (contrasted with conditional compilation)
27674
27675 Typically the Boolean constants will be in a separate package,
27676 something like:
27677
27678 @smallexample @c ada
27679 @group
27680 package Config is
27681    FP_Initialize_Required : constant Boolean := True;
27682    Reset_Available        : constant Boolean := False;
27683    ...
27684 end Config;
27685 @end group
27686 @end smallexample
27687
27688 @noindent
27689 The @code{Config} package exists in multiple forms for the various targets,
27690 with an appropriate script selecting the version of @code{Config} needed.
27691 Then any other unit requiring conditional compilation can do a @code{with}
27692 of @code{Config} to make the constants visible.
27693
27694
27695 @node Debugging - A Special Case
27696 @section Debugging - A Special Case
27697
27698 @noindent
27699 A common use of conditional code is to execute statements (for example
27700 dynamic checks, or output of intermediate results) under control of a
27701 debug switch, so that the debugging behavior can be turned on and off.
27702 This can be done using a Boolean constant to control whether the code
27703 is active:
27704
27705 @smallexample @c ada
27706 @group
27707 if Debugging then
27708    Put_Line ("got to the first stage!");
27709 end if;
27710 @end group
27711 @end smallexample
27712
27713 @noindent
27714 or
27715
27716 @smallexample @c ada
27717 @group
27718 if Debugging and then Temperature > 999.0 then
27719    raise Temperature_Crazy;
27720 end if;
27721 @end group
27722 @end smallexample
27723
27724 @noindent
27725 Since this is a common case, there are special features to deal with
27726 this in a convenient manner. For the case of tests, Ada 2005 has added
27727 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
27728 @cindex pragma @code{Assert}
27729 on the @code{Assert} pragma that has always been available in GNAT, so this
27730 feature may be used with GNAT even if you are not using Ada 2005 features.
27731 The use of pragma @code{Assert} is described in the
27732 @cite{GNAT Reference Manual}, but as an example, the last test could be written:
27733
27734 @smallexample @c ada
27735 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
27736 @end smallexample
27737
27738 @noindent
27739 or simply
27740
27741 @smallexample @c ada
27742 pragma Assert (Temperature <= 999.0);
27743 @end smallexample
27744
27745 @noindent
27746 In both cases, if assertions are active and the temperature is excessive,
27747 the exception @code{Assert_Failure} will be raised, with the given string in
27748 the first case or a string indicating the location of the pragma in the second
27749 case used as the exception message.
27750
27751 You can turn assertions on and off by using the @code{Assertion_Policy}
27752 pragma.
27753 @cindex pragma @code{Assertion_Policy}
27754 This is an Ada 2005 pragma which is implemented in all modes by
27755 GNAT, but only in the latest versions of GNAT which include Ada 2005
27756 capability. Alternatively, you can use the @option{-gnata} switch
27757 @cindex @option{-gnata} switch
27758 to enable assertions from the command line (this is recognized by all versions
27759 of GNAT).
27760
27761 For the example above with the @code{Put_Line}, the GNAT-specific pragma
27762 @code{Debug} can be used:
27763 @cindex pragma @code{Debug}
27764
27765 @smallexample @c ada
27766 pragma Debug (Put_Line ("got to the first stage!"));
27767 @end smallexample
27768
27769 @noindent
27770 If debug pragmas are enabled, the argument, which must be of the form of
27771 a procedure call, is executed (in this case, @code{Put_Line} will be called).
27772 Only one call can be present, but of course a special debugging procedure
27773 containing any code you like can be included in the program and then
27774 called in a pragma @code{Debug} argument as needed.
27775
27776 One advantage of pragma @code{Debug} over the @code{if Debugging then}
27777 construct is that pragma @code{Debug} can appear in declarative contexts,
27778 such as at the very beginning of a procedure, before local declarations have
27779 been elaborated.
27780
27781 Debug pragmas are enabled using either the @option{-gnata} switch that also
27782 controls assertions, or with a separate Debug_Policy pragma.
27783 @cindex pragma @code{Debug_Policy}
27784 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
27785 in Ada 95 and Ada 83 programs as well), and is analogous to
27786 pragma @code{Assertion_Policy} to control assertions.
27787
27788 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
27789 and thus they can appear in @file{gnat.adc} if you are not using a
27790 project file, or in the file designated to contain configuration pragmas
27791 in a project file.
27792 They then apply to all subsequent compilations. In practice the use of
27793 the @option{-gnata} switch is often the most convenient method of controlling
27794 the status of these pragmas.
27795
27796 Note that a pragma is not a statement, so in contexts where a statement
27797 sequence is required, you can't just write a pragma on its own. You have
27798 to add a @code{null} statement.
27799
27800 @smallexample @c ada
27801 @group
27802 if ... then
27803    ... -- some statements
27804 else
27805    pragma Assert (Num_Cases < 10);
27806    null;
27807 end if;
27808 @end group
27809 @end smallexample
27810
27811
27812 @node Conditionalizing Declarations
27813 @section Conditionalizing Declarations
27814
27815 @noindent
27816 In some cases, it may be necessary to conditionalize declarations to meet
27817 different requirements. For example we might want a bit string whose length
27818 is set to meet some hardware message requirement.
27819
27820 In some cases, it may be possible to do this using declare blocks controlled
27821 by conditional constants:
27822
27823 @smallexample @c ada
27824 @group
27825 if Small_Machine then
27826    declare
27827       X : Bit_String (1 .. 10);
27828    begin
27829       ...
27830    end;
27831 else
27832    declare
27833       X : Large_Bit_String (1 .. 1000);
27834    begin
27835       ...
27836    end;
27837 end if;
27838 @end group
27839 @end smallexample
27840
27841 @noindent
27842 Note that in this approach, both declarations are analyzed by the
27843 compiler so this can only be used where both declarations are legal,
27844 even though one of them will not be used.
27845
27846 Another approach is to define integer constants, e.g. @code{Bits_Per_Word}, or
27847 Boolean constants, e.g. @code{Little_Endian}, and then write declarations
27848 that are parameterized by these constants. For example
27849
27850 @smallexample @c ada
27851 @group
27852 for Rec use
27853   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
27854 end record;
27855 @end group
27856 @end smallexample
27857
27858 @noindent
27859 If @code{Bits_Per_Word} is set to 32, this generates either
27860
27861 @smallexample @c ada
27862 @group
27863 for Rec use
27864   Field1 at 0 range 0 .. 32;
27865 end record;
27866 @end group
27867 @end smallexample
27868
27869 @noindent
27870 for the big endian case, or
27871
27872 @smallexample @c ada
27873 @group
27874 for Rec use record
27875   Field1 at 0 range 10 .. 32;
27876 end record;
27877 @end group
27878 @end smallexample
27879
27880 @noindent
27881 for the little endian case. Since a powerful subset of Ada expression
27882 notation is usable for creating static constants, clever use of this
27883 feature can often solve quite difficult problems in conditionalizing
27884 compilation (note incidentally that in Ada 95, the little endian
27885 constant was introduced as @code{System.Default_Bit_Order}, so you do not
27886 need to define this one yourself).
27887
27888
27889 @node Use of Alternative Implementations
27890 @section Use of Alternative Implementations
27891
27892 @noindent
27893 In some cases, none of the approaches described above are adequate. This
27894 can occur for example if the set of declarations required is radically
27895 different for two different configurations.
27896
27897 In this situation, the official Ada way of dealing with conditionalizing
27898 such code is to write separate units for the different cases. As long as
27899 this does not result in excessive duplication of code, this can be done
27900 without creating maintenance problems. The approach is to share common
27901 code as far as possible, and then isolate the code and declarations
27902 that are different. Subunits are often a convenient method for breaking
27903 out a piece of a unit that is to be conditionalized, with separate files
27904 for different versions of the subunit for different targets, where the
27905 build script selects the right one to give to the compiler.
27906 @cindex Subunits (and conditional compilation)
27907
27908 As an example, consider a situation where a new feature in Ada 2005
27909 allows something to be done in a really nice way. But your code must be able
27910 to compile with an Ada 95 compiler. Conceptually you want to say:
27911
27912 @smallexample @c ada
27913 @group
27914 if Ada_2005 then
27915    ... neat Ada 2005 code
27916 else
27917    ... not quite as neat Ada 95 code
27918 end if;
27919 @end group
27920 @end smallexample
27921
27922 @noindent
27923 where @code{Ada_2005} is a Boolean constant.
27924
27925 But this won't work when @code{Ada_2005} is set to @code{False},
27926 since the @code{then} clause will be illegal for an Ada 95 compiler.
27927 (Recall that although such unreachable code would eventually be deleted
27928 by the compiler, it still needs to be legal.  If it uses features
27929 introduced in Ada 2005, it will be illegal in Ada 95.)
27930
27931 So instead we write
27932
27933 @smallexample @c ada
27934 procedure Insert is separate;
27935 @end smallexample
27936
27937 @noindent
27938 Then we have two files for the subunit @code{Insert}, with the two sets of
27939 code.
27940 If the package containing this is called @code{File_Queries}, then we might
27941 have two files
27942
27943 @itemize @bullet
27944 @item    @file{file_queries-insert-2005.adb}
27945 @item    @file{file_queries-insert-95.adb}
27946 @end itemize
27947
27948 @noindent
27949 and the build script renames the appropriate file to
27950
27951 @smallexample
27952 file_queries-insert.adb
27953 @end smallexample
27954
27955 @noindent
27956 and then carries out the compilation.
27957
27958 This can also be done with project files' naming schemes. For example:
27959
27960 @smallexample @c project
27961 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
27962 @end smallexample
27963
27964 @noindent
27965 Note also that with project files it is desirable to use a different extension
27966 than @file{ads} / @file{adb} for alternativee versions. Otherwise a naming
27967 conflict may arise through another commonly used feature: to declare as part
27968 of the project a set of directories containing all the sources obeying the
27969 default naming scheme.
27970
27971 The use of alternative units is certainly feasible in all situations,
27972 and for example the Ada part of the GNAT run-time is conditionalized
27973 based on the target architecture using this approach. As a specific example,
27974 consider the implementation of the AST feature in VMS. There is one
27975 spec:
27976
27977 @smallexample
27978 s-asthan.ads
27979 @end smallexample
27980
27981 @noindent
27982 which is the same for all architectures, and three bodies:
27983
27984 @table @file
27985 @item    s-asthan.adb
27986 used for all non-VMS operating systems
27987 @item    s-asthan-vms-alpha.adb
27988 used for VMS on the Alpha
27989 @item    s-asthan-vms-ia64.adb
27990 used for VMS on the ia64
27991 @end table
27992
27993 @noindent
27994 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
27995 this operating system feature is not available, and the two remaining
27996 versions interface with the corresponding versions of VMS to provide
27997 VMS-compatible AST handling. The GNAT build script knows the architecture
27998 and operating system, and automatically selects the right version,
27999 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
28000
28001 Another style for arranging alternative implementations is through Ada's
28002 access-to-subprogram facility.
28003 In case some functionality is to be conditionally included,
28004 you can declare an access-to-procedure variable @code{Ref} that is initialized
28005 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
28006 when appropriate.
28007 In some library package, set @code{Ref} to @code{Proc'Access} for some
28008 procedure @code{Proc} that performs the relevant processing.
28009 The initialization only occurs if the library package is included in the
28010 program.
28011 The same idea can also be implemented using tagged types and dispatching
28012 calls.
28013
28014
28015 @node Preprocessing
28016 @section Preprocessing
28017 @cindex Preprocessing
28018
28019 @noindent
28020 Although it is quite possible to conditionalize code without the use of
28021 C-style preprocessing, as described earlier in this section, it is
28022 nevertheless convenient in some cases to use the C approach. Moreover,
28023 older Ada compilers have often provided some preprocessing capability,
28024 so legacy code may depend on this approach, even though it is not
28025 standard.
28026
28027 To accommodate such use, GNAT provides a preprocessor (modeled to a large
28028 extent on the various preprocessors that have been used
28029 with legacy code on other compilers, to enable easier transition).
28030
28031 The preprocessor may be used in two separate modes. It can be used quite
28032 separately from the compiler, to generate a separate output source file
28033 that is then fed to the compiler as a separate step. This is the
28034 @code{gnatprep} utility, whose use is fully described in
28035 @ref{Preprocessing Using gnatprep}.
28036 @cindex @code{gnatprep}
28037
28038 The preprocessing language allows such constructs as
28039
28040 @smallexample
28041 @group
28042 #if DEBUG or PRIORITY > 4 then
28043    bunch of declarations
28044 #else
28045    completely different bunch of declarations
28046 #end if;
28047 @end group
28048 @end smallexample
28049
28050 @noindent
28051 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
28052 defined either on the command line or in a separate file.
28053
28054 The other way of running the preprocessor is even closer to the C style and
28055 often more convenient. In this approach the preprocessing is integrated into
28056 the compilation process. The compiler is fed the preprocessor input which
28057 includes @code{#if} lines etc, and then the compiler carries out the
28058 preprocessing internally and processes the resulting output.
28059 For more details on this approach, see @ref{Integrated Preprocessing}.
28060
28061
28062 @c *******************************
28063 @node Inline Assembler
28064 @appendix Inline Assembler
28065 @c *******************************
28066
28067 @noindent
28068 If you need to write low-level software that interacts directly
28069 with the hardware, Ada provides two ways to incorporate assembly
28070 language code into your program.  First, you can import and invoke
28071 external routines written in assembly language, an Ada feature fully
28072 supported by GNAT@.  However, for small sections of code it may be simpler
28073 or more efficient to include assembly language statements directly
28074 in your Ada source program, using the facilities of the implementation-defined
28075 package @code{System.Machine_Code}, which incorporates the gcc
28076 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
28077 including the following:
28078
28079 @itemize @bullet
28080 @item No need to use non-Ada tools
28081 @item Consistent interface over different targets
28082 @item Automatic usage of the proper calling conventions
28083 @item Access to Ada constants and variables
28084 @item Definition of intrinsic routines
28085 @item Possibility of inlining a subprogram comprising assembler code
28086 @item Code optimizer can take Inline Assembler code into account
28087 @end itemize
28088
28089 This chapter presents a series of examples to show you how to use
28090 the Inline Assembler.  Although it focuses on the Intel x86,
28091 the general approach applies also to other processors.
28092 It is assumed that you are familiar with Ada
28093 and with assembly language programming.
28094
28095 @menu
28096 * Basic Assembler Syntax::
28097 * A Simple Example of Inline Assembler::
28098 * Output Variables in Inline Assembler::
28099 * Input Variables in Inline Assembler::
28100 * Inlining Inline Assembler Code::
28101 * Other Asm Functionality::
28102 @end menu
28103
28104 @c ---------------------------------------------------------------------------
28105 @node Basic Assembler Syntax
28106 @section Basic Assembler Syntax
28107
28108 @noindent
28109 The assembler used by GNAT and gcc is based not on the Intel assembly
28110 language, but rather on a language that descends from the AT&T Unix
28111 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
28112 The following table summarizes the main features of @emph{as} syntax
28113 and points out the differences from the Intel conventions.
28114 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
28115 pre-processor) documentation for further information.
28116
28117 @table @asis
28118 @item Register names
28119 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
28120 @*
28121 Intel: No extra punctuation; for example @code{eax}
28122
28123 @item Immediate operand
28124 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
28125 @*
28126 Intel: No extra punctuation; for example @code{4}
28127
28128 @item Address
28129 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
28130 @*
28131 Intel: No extra punctuation; for example @code{loc}
28132
28133 @item Memory contents
28134 gcc / @emph{as}: No extra punctuation; for example @code{loc}
28135 @*
28136 Intel: Square brackets; for example @code{[loc]}
28137
28138 @item Register contents
28139 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
28140 @*
28141 Intel: Square brackets; for example @code{[eax]}
28142
28143 @item Hexadecimal numbers
28144 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
28145 @*
28146 Intel: Trailing ``h''; for example @code{A0h}
28147
28148 @item Operand size
28149 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
28150 a 16-bit word
28151 @*
28152 Intel: Implicit, deduced by assembler; for example @code{mov}
28153
28154 @item Instruction repetition
28155 gcc / @emph{as}: Split into two lines; for example
28156 @*
28157 @code{rep}
28158 @*
28159 @code{stosl}
28160 @*
28161 Intel: Keep on one line; for example @code{rep stosl}
28162
28163 @item Order of operands
28164 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
28165 @*
28166 Intel: Destination first; for example @code{mov eax, 4}
28167 @end table
28168
28169 @c ---------------------------------------------------------------------------
28170 @node A Simple Example of Inline Assembler
28171 @section A Simple Example of Inline Assembler
28172
28173 @noindent
28174 The following example will generate a single assembly language statement,
28175 @code{nop}, which does nothing.  Despite its lack of run-time effect,
28176 the example will be useful in illustrating the basics of
28177 the Inline Assembler facility.
28178
28179 @smallexample @c ada
28180 @group
28181 with System.Machine_Code; use System.Machine_Code;
28182 procedure Nothing is
28183 begin
28184    Asm ("nop");
28185 end Nothing;
28186 @end group
28187 @end smallexample
28188
28189 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
28190 here it takes one parameter, a @emph{template string} that must be a static
28191 expression and that will form the generated instruction.
28192 @code{Asm} may be regarded as a compile-time procedure that parses
28193 the template string and additional parameters (none here),
28194 from which it generates a sequence of assembly language instructions.
28195
28196 The examples in this chapter will illustrate several of the forms
28197 for invoking @code{Asm}; a complete specification of the syntax
28198 is found in the @cite{GNAT Reference Manual}.
28199
28200 Under the standard GNAT conventions, the @code{Nothing} procedure
28201 should be in a file named @file{nothing.adb}.
28202 You can build the executable in the usual way:
28203 @smallexample
28204 gnatmake nothing
28205 @end smallexample
28206 However, the interesting aspect of this example is not its run-time behavior
28207 but rather the generated assembly code.
28208 To see this output, invoke the compiler as follows:
28209 @smallexample
28210    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
28211 @end smallexample
28212 where the options are:
28213
28214 @table @code
28215 @item -c
28216 compile only (no bind or link)
28217 @item -S
28218 generate assembler listing
28219 @item -fomit-frame-pointer
28220 do not set up separate stack frames
28221 @item -gnatp
28222 do not add runtime checks
28223 @end table
28224
28225 This gives a human-readable assembler version of the code. The resulting
28226 file will have the same name as the Ada source file, but with a @code{.s}
28227 extension. In our example, the file @file{nothing.s} has the following
28228 contents:
28229
28230 @smallexample
28231 @group
28232 .file "nothing.adb"
28233 gcc2_compiled.:
28234 ___gnu_compiled_ada:
28235 .text
28236    .align 4
28237 .globl __ada_nothing
28238 __ada_nothing:
28239 #APP
28240    nop
28241 #NO_APP
28242    jmp L1
28243    .align 2,0x90
28244 L1:
28245    ret
28246 @end group
28247 @end smallexample
28248
28249 The assembly code you included is clearly indicated by
28250 the compiler, between the @code{#APP} and @code{#NO_APP}
28251 delimiters. The character before the 'APP' and 'NOAPP'
28252 can differ on different targets. For example, GNU/Linux uses '#APP' while
28253 on NT you will see '/APP'.
28254
28255 If you make a mistake in your assembler code (such as using the
28256 wrong size modifier, or using a wrong operand for the instruction) GNAT
28257 will report this error in a temporary file, which will be deleted when
28258 the compilation is finished.  Generating an assembler file will help
28259 in such cases, since you can assemble this file separately using the
28260 @emph{as} assembler that comes with gcc.
28261
28262 Assembling the file using the command
28263
28264 @smallexample
28265 as @file{nothing.s}
28266 @end smallexample
28267 @noindent
28268 will give you error messages whose lines correspond to the assembler
28269 input file, so you can easily find and correct any mistakes you made.
28270 If there are no errors, @emph{as} will generate an object file
28271 @file{nothing.out}.
28272
28273 @c ---------------------------------------------------------------------------
28274 @node Output Variables in Inline Assembler
28275 @section Output Variables in Inline Assembler
28276
28277 @noindent
28278 The examples in this section, showing how to access the processor flags,
28279 illustrate how to specify the destination operands for assembly language
28280 statements.
28281
28282 @smallexample @c ada
28283 @group
28284 with Interfaces; use Interfaces;
28285 with Ada.Text_IO; use Ada.Text_IO;
28286 with System.Machine_Code; use System.Machine_Code;
28287 procedure Get_Flags is
28288    Flags : Unsigned_32;
28289    use ASCII;
28290 begin
28291    Asm ("pushfl"          & LF & HT & -- push flags on stack
28292         "popl %%eax"      & LF & HT & -- load eax with flags
28293         "movl %%eax, %0",             -- store flags in variable
28294         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28295    Put_Line ("Flags register:" & Flags'Img);
28296 end Get_Flags;
28297 @end group
28298 @end smallexample
28299
28300 In order to have a nicely aligned assembly listing, we have separated
28301 multiple assembler statements in the Asm template string with linefeed
28302 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
28303 The resulting section of the assembly output file is:
28304
28305 @smallexample
28306 @group
28307 #APP
28308    pushfl
28309    popl %eax
28310    movl %eax, -40(%ebp)
28311 #NO_APP
28312 @end group
28313 @end smallexample
28314
28315 It would have been legal to write the Asm invocation as:
28316
28317 @smallexample
28318 Asm ("pushfl popl %%eax movl %%eax, %0")
28319 @end smallexample
28320
28321 but in the generated assembler file, this would come out as:
28322
28323 @smallexample
28324 #APP
28325    pushfl popl %eax movl %eax, -40(%ebp)
28326 #NO_APP
28327 @end smallexample
28328
28329 which is not so convenient for the human reader.
28330
28331 We use Ada comments
28332 at the end of each line to explain what the assembler instructions
28333 actually do.  This is a useful convention.
28334
28335 When writing Inline Assembler instructions, you need to precede each register
28336 and variable name with a percent sign.  Since the assembler already requires
28337 a percent sign at the beginning of a register name, you need two consecutive
28338 percent signs for such names in the Asm template string, thus @code{%%eax}.
28339 In the generated assembly code, one of the percent signs will be stripped off.
28340
28341 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28342 variables: operands you later define using @code{Input} or @code{Output}
28343 parameters to @code{Asm}.
28344 An output variable is illustrated in
28345 the third statement in the Asm template string:
28346 @smallexample
28347 movl %%eax, %0
28348 @end smallexample
28349 The intent is to store the contents of the eax register in a variable that can
28350 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
28351 necessarily work, since the compiler might optimize by using a register
28352 to hold Flags, and the expansion of the @code{movl} instruction would not be
28353 aware of this optimization.  The solution is not to store the result directly
28354 but rather to advise the compiler to choose the correct operand form;
28355 that is the purpose of the @code{%0} output variable.
28356
28357 Information about the output variable is supplied in the @code{Outputs}
28358 parameter to @code{Asm}:
28359 @smallexample
28360 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28361 @end smallexample
28362
28363 The output is defined by the @code{Asm_Output} attribute of the target type;
28364 the general format is
28365 @smallexample
28366 Type'Asm_Output (constraint_string, variable_name)
28367 @end smallexample
28368
28369 The constraint string directs the compiler how
28370 to store/access the associated variable.  In the example
28371 @smallexample
28372 Unsigned_32'Asm_Output ("=m", Flags);
28373 @end smallexample
28374 the @code{"m"} (memory) constraint tells the compiler that the variable
28375 @code{Flags} should be stored in a memory variable, thus preventing
28376 the optimizer from keeping it in a register.  In contrast,
28377 @smallexample
28378 Unsigned_32'Asm_Output ("=r", Flags);
28379 @end smallexample
28380 uses the @code{"r"} (register) constraint, telling the compiler to
28381 store the variable in a register.
28382
28383 If the constraint is preceded by the equal character (@strong{=}), it tells
28384 the compiler that the variable will be used to store data into it.
28385
28386 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28387 allowing the optimizer to choose whatever it deems best.
28388
28389 There are a fairly large number of constraints, but the ones that are
28390 most useful (for the Intel x86 processor) are the following:
28391
28392 @table @code
28393 @item =
28394 output constraint
28395 @item g
28396 global (i.e. can be stored anywhere)
28397 @item m
28398 in memory
28399 @item I
28400 a constant
28401 @item a
28402 use eax
28403 @item b
28404 use ebx
28405 @item c
28406 use ecx
28407 @item d
28408 use edx
28409 @item S
28410 use esi
28411 @item D
28412 use edi
28413 @item r
28414 use one of eax, ebx, ecx or edx
28415 @item q
28416 use one of eax, ebx, ecx, edx, esi or edi
28417 @end table
28418
28419 The full set of constraints is described in the gcc and @emph{as}
28420 documentation; note that it is possible to combine certain constraints
28421 in one constraint string.
28422
28423 You specify the association of an output variable with an assembler operand
28424 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
28425 integer.  Thus in
28426 @smallexample @c ada
28427 @group
28428 Asm ("pushfl"          & LF & HT & -- push flags on stack
28429      "popl %%eax"      & LF & HT & -- load eax with flags
28430      "movl %%eax, %0",             -- store flags in variable
28431      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28432 @end group
28433 @end smallexample
28434 @noindent
28435 @code{%0} will be replaced in the expanded code by the appropriate operand,
28436 whatever
28437 the compiler decided for the @code{Flags} variable.
28438
28439 In general, you may have any number of output variables:
28440 @itemize @bullet
28441 @item
28442 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28443 @item
28444 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28445 of @code{Asm_Output} attributes
28446 @end itemize
28447
28448 For example:
28449 @smallexample @c ada
28450 @group
28451 Asm ("movl %%eax, %0" & LF & HT &
28452      "movl %%ebx, %1" & LF & HT &
28453      "movl %%ecx, %2",
28454      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
28455                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
28456                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
28457 @end group
28458 @end smallexample
28459 @noindent
28460 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28461 in the Ada program.
28462
28463 As a variation on the @code{Get_Flags} example, we can use the constraints
28464 string to direct the compiler to store the eax register into the @code{Flags}
28465 variable, instead of including the store instruction explicitly in the
28466 @code{Asm} template string:
28467
28468 @smallexample @c ada
28469 @group
28470 with Interfaces; use Interfaces;
28471 with Ada.Text_IO; use Ada.Text_IO;
28472 with System.Machine_Code; use System.Machine_Code;
28473 procedure Get_Flags_2 is
28474    Flags : Unsigned_32;
28475    use ASCII;
28476 begin
28477    Asm ("pushfl"      & LF & HT & -- push flags on stack
28478         "popl %%eax",             -- save flags in eax
28479         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28480    Put_Line ("Flags register:" & Flags'Img);
28481 end Get_Flags_2;
28482 @end group
28483 @end smallexample
28484
28485 @noindent
28486 The @code{"a"} constraint tells the compiler that the @code{Flags}
28487 variable will come from the eax register. Here is the resulting code:
28488
28489 @smallexample
28490 @group
28491 #APP
28492    pushfl
28493    popl %eax
28494 #NO_APP
28495    movl %eax,-40(%ebp)
28496 @end group
28497 @end smallexample
28498
28499 @noindent
28500 The compiler generated the store of eax into Flags after
28501 expanding the assembler code.
28502
28503 Actually, there was no need to pop the flags into the eax register;
28504 more simply, we could just pop the flags directly into the program variable:
28505
28506 @smallexample @c ada
28507 @group
28508 with Interfaces; use Interfaces;
28509 with Ada.Text_IO; use Ada.Text_IO;
28510 with System.Machine_Code; use System.Machine_Code;
28511 procedure Get_Flags_3 is
28512    Flags : Unsigned_32;
28513    use ASCII;
28514 begin
28515    Asm ("pushfl"  & LF & HT & -- push flags on stack
28516         "pop %0",             -- save flags in Flags
28517         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28518    Put_Line ("Flags register:" & Flags'Img);
28519 end Get_Flags_3;
28520 @end group
28521 @end smallexample
28522
28523 @c ---------------------------------------------------------------------------
28524 @node Input Variables in Inline Assembler
28525 @section Input Variables in Inline Assembler
28526
28527 @noindent
28528 The example in this section illustrates how to specify the source operands
28529 for assembly language statements.
28530 The program simply increments its input value by 1:
28531
28532 @smallexample @c ada
28533 @group
28534 with Interfaces; use Interfaces;
28535 with Ada.Text_IO; use Ada.Text_IO;
28536 with System.Machine_Code; use System.Machine_Code;
28537 procedure Increment is
28538
28539    function Incr (Value : Unsigned_32) return Unsigned_32 is
28540       Result : Unsigned_32;
28541    begin
28542       Asm ("incl %0",
28543            Inputs  => Unsigned_32'Asm_Input ("a", Value),
28544            Outputs => Unsigned_32'Asm_Output ("=a", Result));
28545       return Result;
28546    end Incr;
28547
28548    Value : Unsigned_32;
28549
28550 begin
28551    Value := 5;
28552    Put_Line ("Value before is" & Value'Img);
28553    Value := Incr (Value);
28554    Put_Line ("Value after is" & Value'Img);
28555 end Increment;
28556 @end group
28557 @end smallexample
28558
28559 The @code{Outputs} parameter to @code{Asm} specifies
28560 that the result will be in the eax register and that it is to be stored
28561 in the @code{Result} variable.
28562
28563 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28564 but with an @code{Asm_Input} attribute.
28565 The @code{"="} constraint, indicating an output value, is not present.
28566
28567 You can have multiple input variables, in the same way that you can have more
28568 than one output variable.
28569
28570 The parameter count (%0, %1) etc, now starts at the first input
28571 statement, and continues with the output statements.
28572 When both parameters use the same variable, the
28573 compiler will treat them as the same %n operand, which is the case here.
28574
28575 Just as the @code{Outputs} parameter causes the register to be stored into the
28576 target variable after execution of the assembler statements, so does the
28577 @code{Inputs} parameter cause its variable to be loaded into the register
28578 before execution of the assembler statements.
28579
28580 Thus the effect of the @code{Asm} invocation is:
28581 @enumerate
28582 @item load the 32-bit value of @code{Value} into eax
28583 @item execute the @code{incl %eax} instruction
28584 @item store the contents of eax into the @code{Result} variable
28585 @end enumerate
28586
28587 The resulting assembler file (with @option{-O2} optimization) contains:
28588 @smallexample
28589 @group
28590 _increment__incr.1:
28591    subl $4,%esp
28592    movl 8(%esp),%eax
28593 #APP
28594    incl %eax
28595 #NO_APP
28596    movl %eax,%edx
28597    movl %ecx,(%esp)
28598    addl $4,%esp
28599    ret
28600 @end group
28601 @end smallexample
28602
28603 @c ---------------------------------------------------------------------------
28604 @node Inlining Inline Assembler Code
28605 @section Inlining Inline Assembler Code
28606
28607 @noindent
28608 For a short subprogram such as the @code{Incr} function in the previous
28609 section, the overhead of the call and return (creating / deleting the stack
28610 frame) can be significant, compared to the amount of code in the subprogram
28611 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
28612 which directs the compiler to expand invocations of the subprogram at the
28613 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28614 Here is the resulting program:
28615
28616 @smallexample @c ada
28617 @group
28618 with Interfaces; use Interfaces;
28619 with Ada.Text_IO; use Ada.Text_IO;
28620 with System.Machine_Code; use System.Machine_Code;
28621 procedure Increment_2 is
28622
28623    function Incr (Value : Unsigned_32) return Unsigned_32 is
28624       Result : Unsigned_32;
28625    begin
28626       Asm ("incl %0",
28627            Inputs  => Unsigned_32'Asm_Input ("a", Value),
28628            Outputs => Unsigned_32'Asm_Output ("=a", Result));
28629       return Result;
28630    end Incr;
28631    pragma Inline (Increment);
28632
28633    Value : Unsigned_32;
28634
28635 begin
28636    Value := 5;
28637    Put_Line ("Value before is" & Value'Img);
28638    Value := Increment (Value);
28639    Put_Line ("Value after is" & Value'Img);
28640 end Increment_2;
28641 @end group
28642 @end smallexample
28643
28644 Compile the program with both optimization (@option{-O2}) and inlining
28645 enabled (@option{-gnatpn} instead of @option{-gnatp}).
28646
28647 The @code{Incr} function is still compiled as usual, but at the
28648 point in @code{Increment} where our function used to be called:
28649
28650 @smallexample
28651 @group
28652 pushl %edi
28653 call _increment__incr.1
28654 @end group
28655 @end smallexample
28656
28657 @noindent
28658 the code for the function body directly appears:
28659
28660 @smallexample
28661 @group
28662 movl %esi,%eax
28663 #APP
28664    incl %eax
28665 #NO_APP
28666    movl %eax,%edx
28667 @end group
28668 @end smallexample
28669
28670 @noindent
28671 thus saving the overhead of stack frame setup and an out-of-line call.
28672
28673 @c ---------------------------------------------------------------------------
28674 @node Other Asm Functionality
28675 @section Other @code{Asm} Functionality
28676
28677 @noindent
28678 This section describes two important parameters to the @code{Asm}
28679 procedure: @code{Clobber}, which identifies register usage;
28680 and @code{Volatile}, which inhibits unwanted optimizations.
28681
28682 @menu
28683 * The Clobber Parameter::
28684 * The Volatile Parameter::
28685 @end menu
28686
28687 @c ---------------------------------------------------------------------------
28688 @node The Clobber Parameter
28689 @subsection The @code{Clobber} Parameter
28690
28691 @noindent
28692 One of the dangers of intermixing assembly language and a compiled language
28693 such as Ada is that the compiler needs to be aware of which registers are
28694 being used by the assembly code.  In some cases, such as the earlier examples,
28695 the constraint string is sufficient to indicate register usage (e.g.,
28696 @code{"a"} for
28697 the eax register).  But more generally, the compiler needs an explicit
28698 identification of the registers that are used by the Inline Assembly
28699 statements.
28700
28701 Using a register that the compiler doesn't know about
28702 could be a side effect of an instruction (like @code{mull}
28703 storing its result in both eax and edx).
28704 It can also arise from explicit register usage in your
28705 assembly code; for example:
28706 @smallexample
28707 @group
28708 Asm ("movl %0, %%ebx" & LF & HT &
28709      "movl %%ebx, %1",
28710      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
28711      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
28712 @end group
28713 @end smallexample
28714 @noindent
28715 where the compiler (since it does not analyze the @code{Asm} template string)
28716 does not know you are using the ebx register.
28717
28718 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28719 to identify the registers that will be used by your assembly code:
28720
28721 @smallexample
28722 @group
28723 Asm ("movl %0, %%ebx" & LF & HT &
28724      "movl %%ebx, %1",
28725      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
28726      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28727      Clobber => "ebx");
28728 @end group
28729 @end smallexample
28730
28731 The Clobber parameter is a static string expression specifying the
28732 register(s) you are using.  Note that register names are @emph{not} prefixed
28733 by a percent sign. Also, if more than one register is used then their names
28734 are separated by commas; e.g., @code{"eax, ebx"}
28735
28736 The @code{Clobber} parameter has several additional uses:
28737 @enumerate
28738 @item Use ``register'' name @code{cc} to indicate that flags might have changed
28739 @item Use ``register'' name @code{memory} if you changed a memory location
28740 @end enumerate
28741
28742 @c ---------------------------------------------------------------------------
28743 @node The Volatile Parameter
28744 @subsection The @code{Volatile} Parameter
28745 @cindex Volatile parameter
28746
28747 @noindent
28748 Compiler optimizations in the presence of Inline Assembler may sometimes have
28749 unwanted effects.  For example, when an @code{Asm} invocation with an input
28750 variable is inside a loop, the compiler might move the loading of the input
28751 variable outside the loop, regarding it as a one-time initialization.
28752
28753 If this effect is not desired, you can disable such optimizations by setting
28754 the @code{Volatile} parameter to @code{True}; for example:
28755
28756 @smallexample @c ada
28757 @group
28758 Asm ("movl %0, %%ebx" & LF & HT &
28759      "movl %%ebx, %1",
28760      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
28761      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
28762      Clobber  => "ebx",
28763      Volatile => True);
28764 @end group
28765 @end smallexample
28766
28767 By default, @code{Volatile} is set to @code{False} unless there is no
28768 @code{Outputs} parameter.
28769
28770 Although setting @code{Volatile} to @code{True} prevents unwanted
28771 optimizations, it will also disable other optimizations that might be
28772 important for efficiency. In general, you should set @code{Volatile}
28773 to @code{True} only if the compiler's optimizations have created
28774 problems.
28775 @c END OF INLINE ASSEMBLER CHAPTER
28776 @c ===============================
28777
28778 @c ***********************************
28779 @c * Compatibility and Porting Guide *
28780 @c ***********************************
28781 @node Compatibility and Porting Guide
28782 @appendix Compatibility and Porting Guide
28783
28784 @noindent
28785 This chapter describes the compatibility issues that may arise between
28786 GNAT and other Ada compilation systems (including those for Ada 83),
28787 and shows how GNAT can expedite porting
28788 applications developed in other Ada environments.
28789
28790 @menu
28791 * Compatibility with Ada 83::
28792 * Compatibility between Ada 95 and Ada 2005::
28793 * Implementation-dependent characteristics::
28794 * Compatibility with Other Ada Systems::
28795 * Representation Clauses::
28796 @ifclear vms
28797 @c Brief section is only in non-VMS version
28798 @c Full chapter is in VMS version
28799 * Compatibility with HP Ada 83::
28800 @end ifclear
28801 @ifset vms
28802 * Transitioning to 64-Bit GNAT for OpenVMS::
28803 @end ifset
28804 @end menu
28805
28806 @node Compatibility with Ada 83
28807 @section Compatibility with Ada 83
28808 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
28809
28810 @noindent
28811 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
28812 particular, the design intention was that the difficulties associated
28813 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
28814 that occur when moving from one Ada 83 system to another.
28815
28816 However, there are a number of points at which there are minor
28817 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
28818 full details of these issues,
28819 and should be consulted for a complete treatment.
28820 In practice the
28821 following subsections treat the most likely issues to be encountered.
28822
28823 @menu
28824 * Legal Ada 83 programs that are illegal in Ada 95::
28825 * More deterministic semantics::
28826 * Changed semantics::
28827 * Other language compatibility issues::
28828 @end menu
28829
28830 @node Legal Ada 83 programs that are illegal in Ada 95
28831 @subsection Legal Ada 83 programs that are illegal in Ada 95
28832
28833 Some legal Ada 83 programs are illegal (i.e. they will fail to compile) in
28834 Ada 95 and thus also in Ada 2005:
28835
28836 @table @emph
28837 @item Character literals
28838 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
28839 @code{Wide_Character} as a new predefined character type, some uses of
28840 character literals that were legal in Ada 83 are illegal in Ada 95.
28841 For example:
28842 @smallexample @c ada
28843    for Char in 'A' .. 'Z' loop ... end loop;
28844 @end smallexample
28845
28846 @noindent
28847 The problem is that @code{'A'} and @code{'Z'} could be from either
28848 @code{Character} or @code{Wide_Character}.  The simplest correction
28849 is to make the type explicit; e.g.:
28850 @smallexample @c ada
28851    for Char in Character range 'A' .. 'Z' loop ... end loop;
28852 @end smallexample
28853
28854 @item New reserved words
28855 The identifiers @code{abstract}, @code{aliased}, @code{protected},
28856 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
28857 Existing Ada 83 code using any of these identifiers must be edited to
28858 use some alternative name.
28859
28860 @item Freezing rules
28861 The rules in Ada 95 are slightly different with regard to the point at
28862 which entities are frozen, and representation pragmas and clauses are
28863 not permitted past the freeze point.  This shows up most typically in
28864 the form of an error message complaining that a representation item
28865 appears too late, and the appropriate corrective action is to move
28866 the item nearer to the declaration of the entity to which it refers.
28867
28868 A particular case is that representation pragmas
28869 @ifset vms
28870 (including the
28871 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
28872 @end ifset
28873 cannot be applied to a subprogram body.  If necessary, a separate subprogram
28874 declaration must be introduced to which the pragma can be applied.
28875
28876 @item Optional bodies for library packages
28877 In Ada 83, a package that did not require a package body was nevertheless
28878 allowed to have one.  This lead to certain surprises in compiling large
28879 systems (situations in which the body could be unexpectedly ignored by the
28880 binder).  In Ada 95, if a package does not require a body then it is not
28881 permitted to have a body.  To fix this problem, simply remove a redundant
28882 body if it is empty, or, if it is non-empty, introduce a dummy declaration
28883 into the spec that makes the body required.  One approach is to add a private
28884 part to the package declaration (if necessary), and define a parameterless
28885 procedure called @code{Requires_Body}, which must then be given a dummy
28886 procedure body in the package body, which then becomes required.
28887 Another approach (assuming that this does not introduce elaboration
28888 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
28889 since one effect of this pragma is to require the presence of a package body.
28890
28891 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
28892 In Ada 95, the exception @code{Numeric_Error} is a renaming of
28893 @code{Constraint_Error}.
28894 This means that it is illegal to have separate exception handlers for
28895 the two exceptions.  The fix is simply to remove the handler for the
28896 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
28897 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
28898
28899 @item Indefinite subtypes in generics
28900 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
28901 as the actual for a generic formal private type, but then the instantiation
28902 would be illegal if there were any instances of declarations of variables
28903 of this type in the generic body.  In Ada 95, to avoid this clear violation
28904 of the methodological principle known as the ``contract model'',
28905 the generic declaration explicitly indicates whether
28906 or not such instantiations are permitted.  If a generic formal parameter
28907 has explicit unknown discriminants, indicated by using @code{(<>)} after the
28908 type name, then it can be instantiated with indefinite types, but no
28909 stand-alone variables can be declared of this type.  Any attempt to declare
28910 such a variable will result in an illegality at the time the generic is
28911 declared.  If the @code{(<>)} notation is not used, then it is illegal
28912 to instantiate the generic with an indefinite type.
28913 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
28914 It will show up as a compile time error, and
28915 the fix is usually simply to add the @code{(<>)} to the generic declaration.
28916 @end table
28917
28918 @node More deterministic semantics
28919 @subsection More deterministic semantics
28920
28921 @table @emph
28922 @item Conversions
28923 Conversions from real types to integer types round away from 0.  In Ada 83
28924 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
28925 implementation freedom was intended to support unbiased rounding in
28926 statistical applications, but in practice it interfered with portability.
28927 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
28928 is required.  Numeric code may be affected by this change in semantics.
28929 Note, though, that this issue is no worse than already existed in Ada 83
28930 when porting code from one vendor to another.
28931
28932 @item Tasking
28933 The Real-Time Annex introduces a set of policies that define the behavior of
28934 features that were implementation dependent in Ada 83, such as the order in
28935 which open select branches are executed.
28936 @end table
28937
28938 @node Changed semantics
28939 @subsection Changed semantics
28940
28941 @noindent
28942 The worst kind of incompatibility is one where a program that is legal in
28943 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
28944 possible in Ada 83.  Fortunately this is extremely rare, but the one
28945 situation that you should be alert to is the change in the predefined type
28946 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
28947
28948 @table @emph
28949 @item Range of type @code{Character}
28950 The range of @code{Standard.Character} is now the full 256 characters
28951 of Latin-1, whereas in most Ada 83 implementations it was restricted
28952 to 128 characters. Although some of the effects of
28953 this change will be manifest in compile-time rejection of legal
28954 Ada 83 programs it is possible for a working Ada 83 program to have
28955 a different effect in Ada 95, one that was not permitted in Ada 83.
28956 As an example, the expression
28957 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
28958 delivers @code{255} as its value.
28959 In general, you should look at the logic of any
28960 character-processing Ada 83 program and see whether it needs to be adapted
28961 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
28962 character handling package that may be relevant if code needs to be adapted
28963 to account for the additional Latin-1 elements.
28964 The desirable fix is to
28965 modify the program to accommodate the full character set, but in some cases
28966 it may be convenient to define a subtype or derived type of Character that
28967 covers only the restricted range.
28968 @cindex Latin-1
28969 @end table
28970
28971 @node Other language compatibility issues
28972 @subsection Other language compatibility issues
28973
28974 @table @emph
28975 @item @option{-gnat83} switch
28976 All implementations of GNAT provide a switch that causes GNAT to operate
28977 in Ada 83 mode.  In this mode, some but not all compatibility problems
28978 of the type described above are handled automatically.  For example, the
28979 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
28980 as identifiers as in Ada 83.
28981 However,
28982 in practice, it is usually advisable to make the necessary modifications
28983 to the program to remove the need for using this switch.
28984 See @ref{Compiling Different Versions of Ada}.
28985
28986 @item Support for removed Ada 83 pragmas and attributes
28987 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
28988 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
28989 compilers are allowed, but not required, to implement these missing
28990 elements.  In contrast with some other compilers, GNAT implements all
28991 such pragmas and attributes, eliminating this compatibility concern.  These
28992 include @code{pragma Interface} and the floating point type attributes
28993 (@code{Emax}, @code{Mantissa}, etc.), among other items.
28994 @end table
28995
28996
28997 @node Compatibility between Ada 95 and Ada 2005
28998 @section Compatibility between Ada 95 and Ada 2005
28999 @cindex Compatibility between Ada 95 and Ada 2005
29000
29001 @noindent
29002 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
29003 a number of incompatibilities. Several are enumerated below;
29004 for a complete description please see the
29005 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
29006 @cite{Rationale for Ada 2005}.
29007
29008 @table @emph
29009 @item New reserved words.
29010 The words @code{interface}, @code{overriding} and @code{synchronized} are
29011 reserved in Ada 2005.
29012 A pre-Ada 2005 program that uses any of these as an identifier will be
29013 illegal.
29014
29015 @item New declarations in predefined packages.
29016 A number of packages in the predefined environment contain new declarations:
29017 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
29018 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
29019 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
29020 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
29021 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
29022 If an Ada 95 program does a @code{with} and @code{use} of any of these
29023 packages, the new declarations may cause name clashes.
29024
29025 @item Access parameters.
29026 A nondispatching subprogram with an access parameter cannot be renamed
29027 as a dispatching operation.  This was permitted in Ada 95.
29028
29029 @item Access types, discriminants, and constraints.
29030 Rule changes in this area have led to some incompatibilities; for example,
29031 constrained subtypes of some access types are not permitted in Ada 2005.
29032
29033 @item Aggregates for limited types.
29034 The allowance of aggregates for limited types in Ada 2005 raises the
29035 possibility of ambiguities in legal Ada 95 programs, since additional types
29036 now need to be considered in expression resolution.
29037
29038 @item Fixed-point multiplication and division.
29039 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
29040 were legal in Ada 95 and invoked the predefined versions of these operations,
29041 are now ambiguous.
29042 The ambiguity may be resolved either by applying a type conversion to the
29043 expression, or by explicitly invoking the operation from package
29044 @code{Standard}.
29045
29046 @item Return-by-reference types.
29047 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
29048 can declare a function returning a value from an anonymous access type.
29049 @end table
29050
29051
29052 @node Implementation-dependent characteristics
29053 @section Implementation-dependent characteristics
29054 @noindent
29055 Although the Ada language defines the semantics of each construct as
29056 precisely as practical, in some situations (for example for reasons of
29057 efficiency, or where the effect is heavily dependent on the host or target
29058 platform) the implementation is allowed some freedom.  In porting Ada 83
29059 code to GNAT, you need to be aware of whether / how the existing code
29060 exercised such implementation dependencies.  Such characteristics fall into
29061 several categories, and GNAT offers specific support in assisting the
29062 transition from certain Ada 83 compilers.
29063
29064 @menu
29065 * Implementation-defined pragmas::
29066 * Implementation-defined attributes::
29067 * Libraries::
29068 * Elaboration order::
29069 * Target-specific aspects::
29070 @end menu
29071
29072 @node Implementation-defined pragmas
29073 @subsection Implementation-defined pragmas
29074
29075 @noindent
29076 Ada compilers are allowed to supplement the language-defined pragmas, and
29077 these are a potential source of non-portability.  All GNAT-defined pragmas
29078 are described in the GNAT Reference Manual, and these include several that
29079 are specifically intended to correspond to other vendors' Ada 83 pragmas.
29080 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
29081 For
29082 compatibility with HP Ada 83, GNAT supplies the pragmas
29083 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
29084 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
29085 and @code{Volatile}.
29086 Other relevant pragmas include @code{External} and @code{Link_With}.
29087 Some vendor-specific
29088 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
29089 recognized, thus
29090 avoiding compiler rejection of units that contain such pragmas; they are not
29091 relevant in a GNAT context and hence are not otherwise implemented.
29092
29093 @node Implementation-defined attributes
29094 @subsection Implementation-defined attributes
29095
29096 Analogous to pragmas, the set of attributes may be extended by an
29097 implementation.  All GNAT-defined attributes are described in the
29098 @cite{GNAT Reference Manual}, and these include several that are specifically
29099 intended
29100 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
29101 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
29102 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
29103 @code{Type_Class}.
29104
29105 @node Libraries
29106 @subsection Libraries
29107 @noindent
29108 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
29109 code uses vendor-specific libraries then there are several ways to manage
29110 this in Ada 95 or Ada 2005:
29111 @enumerate
29112 @item
29113 If the source code for the libraries (specifications and bodies) are
29114 available, then the libraries can be migrated in the same way as the
29115 application.
29116 @item
29117 If the source code for the specifications but not the bodies are
29118 available, then you can reimplement the bodies.
29119 @item
29120 Some features introduced by Ada 95 obviate the need for library support.  For
29121 example most Ada 83 vendors supplied a package for unsigned integers.  The
29122 Ada 95 modular type feature is the preferred way to handle this need, so
29123 instead of migrating or reimplementing the unsigned integer package it may
29124 be preferable to retrofit the application using modular types.
29125 @end enumerate
29126
29127 @node Elaboration order
29128 @subsection Elaboration order
29129 @noindent
29130 The implementation can choose any elaboration order consistent with the unit
29131 dependency relationship.  This freedom means that some orders can result in
29132 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
29133 to invoke a subprogram its body has been elaborated, or to instantiate a
29134 generic before the generic body has been elaborated.  By default GNAT
29135 attempts to choose a safe order (one that will not encounter access before
29136 elaboration problems) by implicitly inserting @code{Elaborate} or
29137 @code{Elaborate_All} pragmas where
29138 needed.  However, this can lead to the creation of elaboration circularities
29139 and a resulting rejection of the program by gnatbind.  This issue is
29140 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
29141 In brief, there are several
29142 ways to deal with this situation:
29143
29144 @itemize @bullet
29145 @item
29146 Modify the program to eliminate the circularities, e.g. by moving
29147 elaboration-time code into explicitly-invoked procedures
29148 @item
29149 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
29150 @code{Elaborate} pragmas, and then inhibit the generation of implicit
29151 @code{Elaborate_All}
29152 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
29153 (by selectively suppressing elaboration checks via pragma
29154 @code{Suppress(Elaboration_Check)} when it is safe to do so).
29155 @end itemize
29156
29157 @node Target-specific aspects
29158 @subsection Target-specific aspects
29159 @noindent
29160 Low-level applications need to deal with machine addresses, data
29161 representations, interfacing with assembler code, and similar issues.  If
29162 such an Ada 83 application is being ported to different target hardware (for
29163 example where the byte endianness has changed) then you will need to
29164 carefully examine the program logic; the porting effort will heavily depend
29165 on the robustness of the original design.  Moreover, Ada 95 (and thus
29166 Ada 2005) are sometimes
29167 incompatible with typical Ada 83 compiler practices regarding implicit
29168 packing, the meaning of the Size attribute, and the size of access values.
29169 GNAT's approach to these issues is described in @ref{Representation Clauses}.
29170
29171 @node Compatibility with Other Ada Systems
29172 @section Compatibility with Other Ada Systems
29173
29174 @noindent
29175 If programs avoid the use of implementation dependent and
29176 implementation defined features, as documented in the @cite{Ada
29177 Reference Manual}, there should be a high degree of portability between
29178 GNAT and other Ada systems.  The following are specific items which
29179 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
29180 compilers, but do not affect porting code to GNAT@.
29181 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
29182 the following issues may or may not arise for Ada 2005 programs
29183 when other compilers appear.)
29184
29185 @table @emph
29186 @item Ada 83 Pragmas and Attributes
29187 Ada 95 compilers are allowed, but not required, to implement the missing
29188 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
29189 GNAT implements all such pragmas and attributes, eliminating this as
29190 a compatibility concern, but some other Ada 95 compilers reject these
29191 pragmas and attributes.
29192
29193 @item Specialized Needs Annexes
29194 GNAT implements the full set of special needs annexes.  At the
29195 current time, it is the only Ada 95 compiler to do so.  This means that
29196 programs making use of these features may not be portable to other Ada
29197 95 compilation systems.
29198
29199 @item Representation Clauses
29200 Some other Ada 95 compilers implement only the minimal set of
29201 representation clauses required by the Ada 95 reference manual.  GNAT goes
29202 far beyond this minimal set, as described in the next section.
29203 @end table
29204
29205 @node Representation Clauses
29206 @section Representation Clauses
29207
29208 @noindent
29209 The Ada 83 reference manual was quite vague in describing both the minimal
29210 required implementation of representation clauses, and also their precise
29211 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
29212 minimal set of capabilities required is still quite limited.
29213
29214 GNAT implements the full required set of capabilities in
29215 Ada 95 and Ada 2005, but also goes much further, and in particular
29216 an effort has been made to be compatible with existing Ada 83 usage to the
29217 greatest extent possible.
29218
29219 A few cases exist in which Ada 83 compiler behavior is incompatible with
29220 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
29221 intentional or accidental dependence on specific implementation dependent
29222 characteristics of these Ada 83 compilers.  The following is a list of
29223 the cases most likely to arise in existing Ada 83 code.
29224
29225 @table @emph
29226 @item Implicit Packing
29227 Some Ada 83 compilers allowed a Size specification to cause implicit
29228 packing of an array or record.  This could cause expensive implicit
29229 conversions for change of representation in the presence of derived
29230 types, and the Ada design intends to avoid this possibility.
29231 Subsequent AI's were issued to make it clear that such implicit
29232 change of representation in response to a Size clause is inadvisable,
29233 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
29234 Reference Manuals as implementation advice that is followed by GNAT@.
29235 The problem will show up as an error
29236 message rejecting the size clause.  The fix is simply to provide
29237 the explicit pragma @code{Pack}, or for more fine tuned control, provide
29238 a Component_Size clause.
29239
29240 @item Meaning of Size Attribute
29241 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
29242 the minimal number of bits required to hold values of the type.  For example,
29243 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
29244 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
29245 some 32 in this situation.  This problem will usually show up as a compile
29246 time error, but not always.  It is a good idea to check all uses of the
29247 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
29248 Object_Size can provide a useful way of duplicating the behavior of
29249 some Ada 83 compiler systems.
29250
29251 @item Size of Access Types
29252 A common assumption in Ada 83 code is that an access type is in fact a pointer,
29253 and that therefore it will be the same size as a System.Address value.  This
29254 assumption is true for GNAT in most cases with one exception.  For the case of
29255 a pointer to an unconstrained array type (where the bounds may vary from one
29256 value of the access type to another), the default is to use a ``fat pointer'',
29257 which is represented as two separate pointers, one to the bounds, and one to
29258 the array.  This representation has a number of advantages, including improved
29259 efficiency.  However, it may cause some difficulties in porting existing Ada 83
29260 code which makes the assumption that, for example, pointers fit in 32 bits on
29261 a machine with 32-bit addressing.
29262
29263 To get around this problem, GNAT also permits the use of ``thin pointers'' for
29264 access types in this case (where the designated type is an unconstrained array
29265 type).  These thin pointers are indeed the same size as a System.Address value.
29266 To specify a thin pointer, use a size clause for the type, for example:
29267
29268 @smallexample @c ada
29269 type X is access all String;
29270 for X'Size use Standard'Address_Size;
29271 @end smallexample
29272
29273 @noindent
29274 which will cause the type X to be represented using a single pointer.
29275 When using this representation, the bounds are right behind the array.
29276 This representation is slightly less efficient, and does not allow quite
29277 such flexibility in the use of foreign pointers or in using the
29278 Unrestricted_Access attribute to create pointers to non-aliased objects.
29279 But for any standard portable use of the access type it will work in
29280 a functionally correct manner and allow porting of existing code.
29281 Note that another way of forcing a thin pointer representation
29282 is to use a component size clause for the element size in an array,
29283 or a record representation clause for an access field in a record.
29284 @end table
29285
29286 @ifclear vms
29287 @c This brief section is only in the non-VMS version
29288 @c The complete chapter on HP Ada is in the VMS version
29289 @node Compatibility with HP Ada 83
29290 @section Compatibility with HP Ada 83
29291
29292 @noindent
29293 The VMS version of GNAT fully implements all the pragmas and attributes
29294 provided by HP Ada 83, as well as providing the standard HP Ada 83
29295 libraries, including Starlet.  In addition, data layouts and parameter
29296 passing conventions are highly compatible.  This means that porting
29297 existing HP Ada 83 code to GNAT in VMS systems should be easier than
29298 most other porting efforts.  The following are some of the most
29299 significant differences between GNAT and HP Ada 83.
29300
29301 @table @emph
29302 @item Default floating-point representation
29303 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
29304 it is VMS format.  GNAT does implement the necessary pragmas
29305 (Long_Float, Float_Representation) for changing this default.
29306
29307 @item System
29308 The package System in GNAT exactly corresponds to the definition in the
29309 Ada 95 reference manual, which means that it excludes many of the
29310 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
29311 that contains the additional definitions, and a special pragma,
29312 Extend_System allows this package to be treated transparently as an
29313 extension of package System.
29314
29315 @item To_Address
29316 The definitions provided by Aux_DEC are exactly compatible with those
29317 in the HP Ada 83 version of System, with one exception.
29318 HP Ada provides the following declarations:
29319
29320 @smallexample @c ada
29321 TO_ADDRESS (INTEGER)
29322 TO_ADDRESS (UNSIGNED_LONGWORD)
29323 TO_ADDRESS (@i{universal_integer})
29324 @end smallexample
29325
29326 @noindent
29327 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
29328 an extension to Ada 83 not strictly compatible with the reference manual.
29329 In GNAT, we are constrained to be exactly compatible with the standard,
29330 and this means we cannot provide this capability.  In HP Ada 83, the
29331 point of this definition is to deal with a call like:
29332
29333 @smallexample @c ada
29334 TO_ADDRESS (16#12777#);
29335 @end smallexample
29336
29337 @noindent
29338 Normally, according to the Ada 83 standard, one would expect this to be
29339 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
29340 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
29341 definition using @i{universal_integer} takes precedence.
29342
29343 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
29344 is not possible to be 100% compatible.  Since there are many programs using
29345 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
29346 to change the name of the function in the UNSIGNED_LONGWORD case, so the
29347 declarations provided in the GNAT version of AUX_Dec are:
29348
29349 @smallexample @c ada
29350 function To_Address (X : Integer) return Address;
29351 pragma Pure_Function (To_Address);
29352
29353 function To_Address_Long (X : Unsigned_Longword)
29354  return Address;
29355 pragma Pure_Function (To_Address_Long);
29356 @end smallexample
29357
29358 @noindent
29359 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
29360 change the name to TO_ADDRESS_LONG@.
29361
29362 @item Task_Id values
29363 The Task_Id values assigned will be different in the two systems, and GNAT
29364 does not provide a specified value for the Task_Id of the environment task,
29365 which in GNAT is treated like any other declared task.
29366 @end table
29367
29368 @noindent
29369 For full details on these and other less significant compatibility issues,
29370 see appendix E of the HP publication entitled @cite{HP Ada, Technical
29371 Overview and Comparison on HP Platforms}.
29372
29373 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
29374 attributes are recognized, although only a subset of them can sensibly
29375 be implemented.  The description of pragmas in the
29376 @cite{GNAT Reference Manual}
29377 indicates whether or not they are applicable to non-VMS systems.
29378 @end ifclear
29379
29380 @ifset vms
29381 @node Transitioning to 64-Bit GNAT for OpenVMS
29382 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
29383
29384 @noindent
29385 This section is meant to assist users of pre-2006 @value{EDITION}
29386 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
29387 the version of the GNAT technology supplied in 2006 and later for
29388 OpenVMS on both Alpha and I64.
29389
29390 @menu
29391 * Introduction to transitioning::
29392 * Migration of 32 bit code::
29393 * Taking advantage of 64 bit addressing::
29394 * Technical details::
29395 @end menu
29396
29397 @node Introduction to transitioning
29398 @subsection Introduction
29399
29400 @noindent
29401 64-bit @value{EDITION} for Open VMS has been designed to meet
29402 three main goals:
29403
29404 @enumerate
29405 @item
29406 Providing a full conforming implementation of Ada 95 and Ada 2005
29407
29408 @item
29409 Allowing maximum backward compatibility, thus easing migration of existing
29410 Ada source code
29411
29412 @item
29413 Supplying a path for exploiting the full 64-bit address range
29414 @end enumerate
29415
29416 @noindent
29417 Ada's strong typing semantics has made it
29418 impractical to have different 32-bit and 64-bit modes. As soon as
29419 one object could possibly be outside the 32-bit address space, this
29420 would make it necessary for the @code{System.Address} type to be 64 bits.
29421 In particular, this would cause inconsistencies if 32-bit code is
29422 called from 64-bit code that raises an exception.
29423
29424 This issue has been resolved by always using 64-bit addressing
29425 at the system level, but allowing for automatic conversions between
29426 32-bit and 64-bit addresses where required. Thus users who
29427 do not currently require 64-bit addressing capabilities, can
29428 recompile their code with only minimal changes (and indeed
29429 if the code is written in portable Ada, with no assumptions about
29430 the size of the @code{Address} type, then no changes at all are necessary).
29431 At the same time,
29432 this approach provides a simple, gradual upgrade path to future
29433 use of larger memories than available for 32-bit systems.
29434 Also, newly written applications or libraries will by default
29435 be fully compatible with future systems exploiting 64-bit
29436 addressing capabilities.
29437
29438 @ref{Migration of 32 bit code}, will focus on porting applications
29439 that do not require more than 2 GB of
29440 addressable memory. This code will be referred to as
29441 @emph{32-bit code}.
29442 For applications intending to exploit the full 64-bit address space,
29443 @ref{Taking advantage of 64 bit addressing},
29444 will consider further changes that may be required.
29445 Such code will be referred to below as @emph{64-bit code}.
29446
29447 @node Migration of 32 bit code
29448 @subsection Migration of 32-bit code
29449
29450 @menu
29451 * Address types::
29452 * Access types::
29453 * Unchecked conversions::
29454 * Predefined constants::
29455 * Interfacing with C::
29456 * Experience with source compatibility::
29457 @end menu
29458
29459 @node Address types
29460 @subsubsection Address types
29461
29462 @noindent
29463 To solve the problem of mixing 64-bit and 32-bit addressing,
29464 while maintaining maximum backward compatibility, the following
29465 approach has been taken:
29466
29467 @itemize @bullet
29468 @item
29469 @code{System.Address} always has a size of 64 bits
29470
29471 @item
29472 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
29473 @end itemize
29474
29475 @noindent
29476 Since @code{System.Short_Address} is a subtype of @code{System.Address},
29477 a @code{Short_Address}
29478 may be used where an @code{Address} is required, and vice versa, without
29479 needing explicit type conversions.
29480 By virtue of the Open VMS parameter passing conventions,
29481 even imported
29482 and exported subprograms that have 32-bit address parameters are
29483 compatible with those that have 64-bit address parameters.
29484 (See @ref{Making code 64 bit clean} for details.)
29485
29486 The areas that may need attention are those where record types have
29487 been defined that contain components of the type @code{System.Address}, and
29488 where objects of this type are passed to code expecting a record layout with
29489 32-bit addresses.
29490
29491 Different compilers on different platforms cannot be
29492 expected to represent the same type in the same way,
29493 since alignment constraints
29494 and other system-dependent properties affect the compiler's decision.
29495 For that reason, Ada code
29496 generally uses representation clauses to specify the expected
29497 layout where required.
29498
29499 If such a representation clause uses 32 bits for a component having
29500 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
29501 will detect that error and produce a specific diagnostic message.
29502 The developer should then determine whether the representation
29503 should be 64 bits or not and make either of two changes:
29504 change the size to 64 bits and leave the type as @code{System.Address}, or
29505 leave the size as 32 bits and change the type to @code{System.Short_Address}.
29506 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
29507 required in any code setting or accessing the field; the compiler will
29508 automatically perform any needed conversions between address
29509 formats.
29510
29511 @node Access types
29512 @subsubsection Access types
29513
29514 @noindent
29515 By default, objects designated by access values are always
29516 allocated in the 32-bit
29517 address space. Thus legacy code will never contain
29518 any objects that are not addressable with 32-bit addresses, and
29519 the compiler will never raise exceptions as result of mixing
29520 32-bit and 64-bit addresses.
29521
29522 However, the access values themselves are represented in 64 bits, for optimum
29523 performance and future compatibility with 64-bit code. As was
29524 the case with @code{System.Address}, the compiler will give an error message
29525 if an object or record component has a representation clause that
29526 requires the access value to fit in 32 bits. In such a situation,
29527 an explicit size clause for the access type, specifying 32 bits,
29528 will have the desired effect.
29529
29530 General access types (declared with @code{access all}) can never be
29531 32 bits, as values of such types must be able to refer to any object
29532 of the  designated type,
29533 including objects residing outside the 32-bit address range.
29534 Existing Ada 83 code will not contain such type definitions,
29535 however, since general access types were introduced in Ada 95.
29536
29537 @node Unchecked conversions
29538 @subsubsection Unchecked conversions
29539
29540 @noindent
29541 In the case of an @code{Unchecked_Conversion} where the source type is a
29542 64-bit access type or the type @code{System.Address}, and the target
29543 type is a 32-bit type, the compiler will generate a warning.
29544 Even though the generated code will still perform the required
29545 conversions, it is highly recommended in these cases to use
29546 respectively a 32-bit access type or @code{System.Short_Address}
29547 as the source type.
29548
29549 @node Predefined constants
29550 @subsubsection Predefined constants
29551
29552 @noindent
29553 The following table shows the correspondence between pre-2006 versions of
29554 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
29555 (``New''):
29556
29557 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
29558 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
29559 @item   @code{System.Word_Size}          @tab 32      @tab 64
29560 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
29561 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
29562 @item   @code{System.Address_Size}       @tab 32      @tab 64
29563 @end multitable
29564
29565 @noindent
29566 If you need to refer to the specific
29567 memory size of a 32-bit implementation, instead of the
29568 actual memory size, use @code{System.Short_Memory_Size}
29569 rather than @code{System.Memory_Size}.
29570 Similarly, references to @code{System.Address_Size} may need
29571 to be replaced by @code{System.Short_Address'Size}.
29572 The program @command{gnatfind} may be useful for locating
29573 references to the above constants, so that you can verify that they
29574 are still correct.
29575
29576 @node Interfacing with C
29577 @subsubsection Interfacing with C
29578
29579 @noindent
29580 In order to minimize the impact of the transition to 64-bit addresses on
29581 legacy programs, some fundamental types in the @code{Interfaces.C}
29582 package hierarchy continue to be represented in 32 bits.
29583 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
29584 This eases integration with the default HP C layout choices, for example
29585 as found in the system routines in @code{DECC$SHR.EXE}.
29586 Because of this implementation choice, the type fully compatible with
29587 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
29588 Depending on the context the compiler will issue a
29589 warning or an error when type @code{Address} is used, alerting the user to a
29590 potential problem. Otherwise 32-bit programs that use
29591 @code{Interfaces.C} should normally not require code modifications
29592
29593 The other issue arising with C interfacing concerns pragma @code{Convention}.
29594 For VMS 64-bit systems, there is an issue of the appropriate default size
29595 of C convention pointers in the absence of an explicit size clause. The HP
29596 C compiler can choose either 32 or 64 bits depending on compiler options.
29597 GNAT chooses 32-bits rather than 64-bits in the default case where no size
29598 clause is given. This proves a better choice for porting 32-bit legacy
29599 applications. In order to have a 64-bit representation, it is necessary to
29600 specify a size representation clause. For example:
29601
29602 @smallexample @c ada
29603 type int_star is access Interfaces.C.int;
29604 pragma Convention(C, int_star);
29605 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
29606 @end smallexample
29607
29608 @node Experience with source compatibility
29609 @subsubsection Experience with source compatibility
29610
29611 @noindent
29612 The Security Server and STARLET on I64 provide an interesting ``test case''
29613 for source compatibility issues, since it is in such system code
29614 where assumptions about @code{Address} size might be expected to occur.
29615 Indeed, there were a small number of occasions in the Security Server
29616 file @file{jibdef.ads}
29617 where a representation clause for a record type specified
29618 32 bits for a component of type @code{Address}.
29619 All of these errors were detected by the compiler.
29620 The repair was obvious and immediate; to simply replace @code{Address} by
29621 @code{Short_Address}.
29622
29623 In the case of STARLET, there were several record types that should
29624 have had representation clauses but did not.  In these record types
29625 there was an implicit assumption that an @code{Address} value occupied
29626 32 bits.
29627 These compiled without error, but their usage resulted in run-time error
29628 returns from STARLET system calls.
29629 Future GNAT technology enhancements may include a tool that detects and flags
29630 these sorts of potential source code porting problems.
29631
29632 @c ****************************************
29633 @node Taking advantage of 64 bit addressing
29634 @subsection Taking advantage of 64-bit addressing
29635
29636 @menu
29637 * Making code 64 bit clean::
29638 * Allocating memory from the 64 bit storage pool::
29639 * Restrictions on use of 64 bit objects::
29640 * Using 64 bit storage pools by default::
29641 * General access types::
29642 * STARLET and other predefined libraries::
29643 @end menu
29644
29645 @node Making code 64 bit clean
29646 @subsubsection Making code 64-bit clean
29647
29648 @noindent
29649 In order to prevent problems that may occur when (parts of) a
29650 system start using memory outside the 32-bit address range,
29651 we recommend some additional guidelines:
29652
29653 @itemize @bullet
29654 @item
29655 For imported subprograms that take parameters of the
29656 type @code{System.Address}, ensure that these subprograms can
29657 indeed handle 64-bit addresses. If not, or when in doubt,
29658 change the subprogram declaration to specify
29659 @code{System.Short_Address} instead.
29660
29661 @item
29662 Resolve all warnings related to size mismatches in
29663 unchecked conversions. Failing to do so causes
29664 erroneous execution if the source object is outside
29665 the 32-bit address space.
29666
29667 @item
29668 (optional) Explicitly use the 32-bit storage pool
29669 for access types used in a 32-bit context, or use
29670 generic access types where possible
29671 (@pxref{Restrictions on use of 64 bit objects}).
29672 @end itemize
29673
29674 @noindent
29675 If these rules are followed, the compiler will automatically insert
29676 any necessary checks to ensure that no addresses or access values
29677 passed to 32-bit code ever refer to objects outside the 32-bit
29678 address range.
29679 Any attempt to do this will raise @code{Constraint_Error}.
29680
29681 @node Allocating memory from the 64 bit storage pool
29682 @subsubsection Allocating memory from the 64-bit storage pool
29683
29684 @noindent
29685 For any access type @code{T} that potentially requires memory allocations
29686 beyond the 32-bit address space,
29687 use the following representation clause:
29688
29689 @smallexample @c ada
29690    for T'Storage_Pool use System.Pool_64;
29691 @end smallexample
29692
29693 @node Restrictions on use of 64 bit objects
29694 @subsubsection Restrictions on use of 64-bit objects
29695
29696 @noindent
29697 Taking the address of an object allocated from a 64-bit storage pool,
29698 and then passing this address to a subprogram expecting
29699 @code{System.Short_Address},
29700 or assigning it to a variable of type @code{Short_Address}, will cause
29701 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
29702 (@pxref{Making code 64 bit clean}), or checks are suppressed,
29703 no exception is raised and execution
29704 will become erroneous.
29705
29706 @node Using 64 bit storage pools by default
29707 @subsubsection Using 64-bit storage pools by default
29708
29709 @noindent
29710 In some cases it may be desirable to have the compiler allocate
29711 from 64-bit storage pools by default. This may be the case for
29712 libraries that are 64-bit clean, but may be used in both 32-bit
29713 and 64-bit contexts. For these cases the following configuration
29714 pragma may be specified:
29715
29716 @smallexample @c ada
29717   pragma Pool_64_Default;
29718 @end smallexample
29719
29720 @noindent
29721 Any code compiled in the context of this pragma will by default
29722 use the @code{System.Pool_64} storage pool. This default may be overridden
29723 for a specific access type @code{T} by the representation clause:
29724
29725 @smallexample @c ada
29726    for T'Storage_Pool use System.Pool_32;
29727 @end smallexample
29728
29729 @noindent
29730 Any object whose address may be passed to a subprogram with a
29731 @code{Short_Address} argument, or assigned to a variable of type
29732 @code{Short_Address}, needs to be allocated from this pool.
29733
29734 @node General access types
29735 @subsubsection General access types
29736
29737 @noindent
29738 Objects designated by access values from a
29739 general access type (declared with @code{access all}) are never allocated
29740 from a 64-bit storage pool. Code that uses general access types will
29741 accept objects allocated in either 32-bit or 64-bit address spaces,
29742 but never allocate objects outside the 32-bit address space.
29743 Using general access types ensures maximum compatibility with both
29744 32-bit and 64-bit code.
29745
29746 @node STARLET and other predefined libraries
29747 @subsubsection STARLET and other predefined libraries
29748
29749 @noindent
29750 All code that comes as part of GNAT is 64-bit clean, but the
29751 restrictions given in @ref{Restrictions on use of 64 bit objects},
29752 still apply. Look at the package
29753 specifications to see in which contexts objects allocated
29754 in 64-bit address space are acceptable.
29755
29756 @node Technical details
29757 @subsection Technical details
29758
29759 @noindent
29760 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
29761 Ada standard with respect to the type of @code{System.Address}. Previous
29762 versions of GNAT Pro have defined this type as private and implemented it as a
29763 modular type.
29764
29765 In order to allow defining @code{System.Short_Address} as a proper subtype,
29766 and to match the implicit sign extension in parameter passing,
29767 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
29768 visible (i.e., non-private) integer type.
29769 Standard operations on the type, such as the binary operators ``+'', ``-'',
29770 etc., that take @code{Address} operands and return an @code{Address} result,
29771 have been hidden by declaring these
29772 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
29773 ambiguities that would otherwise result from overloading.
29774 (Note that, although @code{Address} is a visible integer type,
29775 good programming practice dictates against exploiting the type's
29776 integer properties such as literals, since this will compromise
29777 code portability.)
29778
29779 Defining @code{Address} as a visible integer type helps achieve
29780 maximum compatibility for existing Ada code,
29781 without sacrificing the capabilities of the 64-bit architecture.
29782 @end ifset
29783
29784 @c ************************************************
29785 @ifset unw
29786 @node Microsoft Windows Topics
29787 @appendix Microsoft Windows Topics
29788 @cindex Windows NT
29789 @cindex Windows 95
29790 @cindex Windows 98
29791
29792 @noindent
29793 This chapter describes topics that are specific to the Microsoft Windows
29794 platforms (NT, 2000, and XP Professional).
29795
29796 @menu
29797 * Using GNAT on Windows::
29798 * Using a network installation of GNAT::
29799 * CONSOLE and WINDOWS subsystems::
29800 * Temporary Files::
29801 * Mixed-Language Programming on Windows::
29802 * Windows Calling Conventions::
29803 * Introduction to Dynamic Link Libraries (DLLs)::
29804 * Using DLLs with GNAT::
29805 * Building DLLs with GNAT::
29806 * Building DLLs with GNAT Project files::
29807 * Building DLLs with gnatdll::
29808 * GNAT and Windows Resources::
29809 * Debugging a DLL::
29810 * Setting Stack Size from gnatlink::
29811 * Setting Heap Size from gnatlink::
29812 @end menu
29813
29814 @node Using GNAT on Windows
29815 @section Using GNAT on Windows
29816
29817 @noindent
29818 One of the strengths of the GNAT technology is that its tool set
29819 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
29820 @code{gdb} debugger, etc.) is used in the same way regardless of the
29821 platform.
29822
29823 On Windows this tool set is complemented by a number of Microsoft-specific
29824 tools that have been provided to facilitate interoperability with Windows
29825 when this is required. With these tools:
29826
29827 @itemize @bullet
29828
29829 @item
29830 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
29831 subsystems.
29832
29833 @item
29834 You can use any Dynamically Linked Library (DLL) in your Ada code (both
29835 relocatable and non-relocatable DLLs are supported).
29836
29837 @item
29838 You can build Ada DLLs for use in other applications. These applications
29839 can be written in a language other than Ada (e.g., C, C++, etc). Again both
29840 relocatable and non-relocatable Ada DLLs are supported.
29841
29842 @item
29843 You can include Windows resources in your Ada application.
29844
29845 @item
29846 You can use or create COM/DCOM objects.
29847 @end itemize
29848
29849 @noindent
29850 Immediately below are listed all known general GNAT-for-Windows restrictions.
29851 Other restrictions about specific features like Windows Resources and DLLs
29852 are listed in separate sections below.
29853
29854 @itemize @bullet
29855
29856 @item
29857 It is not possible to use @code{GetLastError} and @code{SetLastError}
29858 when tasking, protected records, or exceptions are used. In these
29859 cases, in order to implement Ada semantics, the GNAT run-time system
29860 calls certain Win32 routines that set the last error variable to 0 upon
29861 success. It should be possible to use @code{GetLastError} and
29862 @code{SetLastError} when tasking, protected record, and exception
29863 features are not used, but it is not guaranteed to work.
29864
29865 @item
29866 It is not possible to link against Microsoft libraries except for
29867 import libraries. The library must be built to be compatible with
29868 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
29869 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
29870 not be compatible with the GNAT runtime. Even if the library is
29871 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
29872
29873 @item
29874 When the compilation environment is located on FAT32 drives, users may
29875 experience recompilations of the source files that have not changed if
29876 Daylight Saving Time (DST) state has changed since the last time files
29877 were compiled. NTFS drives do not have this problem.
29878
29879 @item
29880 No components of the GNAT toolset use any entries in the Windows
29881 registry. The only entries that can be created are file associations and
29882 PATH settings, provided the user has chosen to create them at installation
29883 time, as well as some minimal book-keeping information needed to correctly
29884 uninstall or integrate different GNAT products.
29885 @end itemize
29886
29887 @node Using a network installation of GNAT
29888 @section Using a network installation of GNAT
29889
29890 @noindent
29891 Make sure the system on which GNAT is installed is accessible from the
29892 current machine, i.e. the install location is shared over the network.
29893 Shared resources are accessed on Windows by means of UNC paths, which
29894 have the format @code{\\server\sharename\path}
29895
29896 In order to use such a network installation, simply add the UNC path of the
29897 @file{bin} directory of your GNAT installation in front of your PATH. For
29898 example, if GNAT is installed in @file{\GNAT} directory of a share location
29899 called @file{c-drive} on a machine @file{LOKI}, the following command will
29900 make it available:
29901
29902 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
29903
29904 Be aware that every compilation using the network installation results in the
29905 transfer of large amounts of data across the network and will likely cause
29906 serious performance penalty.
29907
29908 @node CONSOLE and WINDOWS subsystems
29909 @section CONSOLE and WINDOWS subsystems
29910 @cindex CONSOLE Subsystem
29911 @cindex WINDOWS Subsystem
29912 @cindex -mwindows
29913
29914 @noindent
29915 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
29916 (which is the default subsystem) will always create a console when
29917 launching the application. This is not something desirable when the
29918 application has a Windows GUI. To get rid of this console the
29919 application must be using the @code{WINDOWS} subsystem. To do so
29920 the @option{-mwindows} linker option must be specified.
29921
29922 @smallexample
29923 $ gnatmake winprog -largs -mwindows
29924 @end smallexample
29925
29926 @node Temporary Files
29927 @section Temporary Files
29928 @cindex Temporary files
29929
29930 @noindent
29931 It is possible to control where temporary files gets created by setting
29932 the TMP environment variable. The file will be created:
29933
29934 @itemize
29935 @item Under the directory pointed to by the TMP environment variable if
29936 this directory exists.
29937
29938 @item Under c:\temp, if the TMP environment variable is not set (or not
29939 pointing to a directory) and if this directory exists.
29940
29941 @item Under the current working directory otherwise.
29942 @end itemize
29943
29944 @noindent
29945 This allows you to determine exactly where the temporary
29946 file will be created. This is particularly useful in networked
29947 environments where you may not have write access to some
29948 directories.
29949
29950 @node Mixed-Language Programming on Windows
29951 @section Mixed-Language Programming on Windows
29952
29953 @noindent
29954 Developing pure Ada applications on Windows is no different than on
29955 other GNAT-supported platforms. However, when developing or porting an
29956 application that contains a mix of Ada and C/C++, the choice of your
29957 Windows C/C++ development environment conditions your overall
29958 interoperability strategy.
29959
29960 If you use @command{gcc} to compile the non-Ada part of your application,
29961 there are no Windows-specific restrictions that affect the overall
29962 interoperability with your Ada code. If you plan to use
29963 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
29964 the following limitations:
29965
29966 @itemize @bullet
29967 @item
29968 You cannot link your Ada code with an object or library generated with
29969 Microsoft tools if these use the @code{.tls} section (Thread Local
29970 Storage section) since the GNAT linker does not yet support this section.
29971
29972 @item
29973 You cannot link your Ada code with an object or library generated with
29974 Microsoft tools if these use I/O routines other than those provided in
29975 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
29976 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
29977 libraries can cause a conflict with @code{msvcrt.dll} services. For
29978 instance Visual C++ I/O stream routines conflict with those in
29979 @code{msvcrt.dll}.
29980 @end itemize
29981
29982 @noindent
29983 If you do want to use the Microsoft tools for your non-Ada code and hit one
29984 of the above limitations, you have two choices:
29985
29986 @enumerate
29987 @item
29988 Encapsulate your non Ada code in a DLL to be linked with your Ada
29989 application. In this case, use the Microsoft or whatever environment to
29990 build the DLL and use GNAT to build your executable
29991 (@pxref{Using DLLs with GNAT}).
29992
29993 @item
29994 Or you can encapsulate your Ada code in a DLL to be linked with the
29995 other part of your application. In this case, use GNAT to build the DLL
29996 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
29997 environment to build your executable.
29998 @end enumerate
29999
30000 @node Windows Calling Conventions
30001 @section Windows Calling Conventions
30002 @findex Stdcall
30003 @findex APIENTRY
30004
30005 @menu
30006 * C Calling Convention::
30007 * Stdcall Calling Convention::
30008 * Win32 Calling Convention::
30009 * DLL Calling Convention::
30010 @end menu
30011
30012 @noindent
30013 When a subprogram @code{F} (caller) calls a subprogram @code{G}
30014 (callee), there are several ways to push @code{G}'s parameters on the
30015 stack and there are several possible scenarios to clean up the stack
30016 upon @code{G}'s return. A calling convention is an agreed upon software
30017 protocol whereby the responsibilities between the caller (@code{F}) and
30018 the callee (@code{G}) are clearly defined. Several calling conventions
30019 are available for Windows:
30020
30021 @itemize @bullet
30022 @item
30023 @code{C} (Microsoft defined)
30024
30025 @item
30026 @code{Stdcall} (Microsoft defined)
30027
30028 @item
30029 @code{Win32} (GNAT specific)
30030
30031 @item
30032 @code{DLL} (GNAT specific)
30033 @end itemize
30034
30035 @node C Calling Convention
30036 @subsection @code{C} Calling Convention
30037
30038 @noindent
30039 This is the default calling convention used when interfacing to C/C++
30040 routines compiled with either @command{gcc} or Microsoft Visual C++.
30041
30042 In the @code{C} calling convention subprogram parameters are pushed on the
30043 stack by the caller from right to left. The caller itself is in charge of
30044 cleaning up the stack after the call. In addition, the name of a routine
30045 with @code{C} calling convention is mangled by adding a leading underscore.
30046
30047 The name to use on the Ada side when importing (or exporting) a routine
30048 with @code{C} calling convention is the name of the routine. For
30049 instance the C function:
30050
30051 @smallexample
30052 int get_val (long);
30053 @end smallexample
30054
30055 @noindent
30056 should be imported from Ada as follows:
30057
30058 @smallexample @c ada
30059 @group
30060 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30061 pragma Import (C, Get_Val, External_Name => "get_val");
30062 @end group
30063 @end smallexample
30064
30065 @noindent
30066 Note that in this particular case the @code{External_Name} parameter could
30067 have been omitted since, when missing, this parameter is taken to be the
30068 name of the Ada entity in lower case. When the @code{Link_Name} parameter
30069 is missing, as in the above example, this parameter is set to be the
30070 @code{External_Name} with a leading underscore.
30071
30072 When importing a variable defined in C, you should always use the @code{C}
30073 calling convention unless the object containing the variable is part of a
30074 DLL (in which case you should use the @code{Stdcall} calling
30075 convention, @pxref{Stdcall Calling Convention}).
30076
30077 @node Stdcall Calling Convention
30078 @subsection @code{Stdcall} Calling Convention
30079
30080 @noindent
30081 This convention, which was the calling convention used for Pascal
30082 programs, is used by Microsoft for all the routines in the Win32 API for
30083 efficiency reasons. It must be used to import any routine for which this
30084 convention was specified.
30085
30086 In the @code{Stdcall} calling convention subprogram parameters are pushed
30087 on the stack by the caller from right to left. The callee (and not the
30088 caller) is in charge of cleaning the stack on routine exit. In addition,
30089 the name of a routine with @code{Stdcall} calling convention is mangled by
30090 adding a leading underscore (as for the @code{C} calling convention) and a
30091 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
30092 bytes) of the parameters passed to the routine.
30093
30094 The name to use on the Ada side when importing a C routine with a
30095 @code{Stdcall} calling convention is the name of the C routine. The leading
30096 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
30097 the compiler. For instance the Win32 function:
30098
30099 @smallexample
30100 @b{APIENTRY} int get_val (long);
30101 @end smallexample
30102
30103 @noindent
30104 should be imported from Ada as follows:
30105
30106 @smallexample @c ada
30107 @group
30108 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30109 pragma Import (Stdcall, Get_Val);
30110 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
30111 @end group
30112 @end smallexample
30113
30114 @noindent
30115 As for the @code{C} calling convention, when the @code{External_Name}
30116 parameter is missing, it is taken to be the name of the Ada entity in lower
30117 case. If instead of writing the above import pragma you write:
30118
30119 @smallexample @c ada
30120 @group
30121 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30122 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
30123 @end group
30124 @end smallexample
30125
30126 @noindent
30127 then the imported routine is @code{_retrieve_val@@4}. However, if instead
30128 of specifying the @code{External_Name} parameter you specify the
30129 @code{Link_Name} as in the following example:
30130
30131 @smallexample @c ada
30132 @group
30133 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30134 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
30135 @end group
30136 @end smallexample
30137
30138 @noindent
30139 then the imported routine is @code{retrieve_val}, that is, there is no
30140 decoration at all. No leading underscore and no Stdcall suffix
30141 @code{@@}@code{@i{nn}}.
30142
30143 @noindent
30144 This is especially important as in some special cases a DLL's entry
30145 point name lacks a trailing @code{@@}@code{@i{nn}} while the exported
30146 name generated for a call has it.
30147
30148 @noindent
30149 It is also possible to import variables defined in a DLL by using an
30150 import pragma for a variable. As an example, if a DLL contains a
30151 variable defined as:
30152
30153 @smallexample
30154 int my_var;
30155 @end smallexample
30156
30157 @noindent
30158 then, to access this variable from Ada you should write:
30159
30160 @smallexample @c ada
30161 @group
30162 My_Var : Interfaces.C.int;
30163 pragma Import (Stdcall, My_Var);
30164 @end group
30165 @end smallexample
30166
30167 @noindent
30168 Note that to ease building cross-platform bindings this convention
30169 will be handled as a @code{C} calling convention on non Windows platforms.
30170
30171 @node Win32 Calling Convention
30172 @subsection @code{Win32} Calling Convention
30173
30174 @noindent
30175 This convention, which is GNAT-specific is fully equivalent to the
30176 @code{Stdcall} calling convention described above.
30177
30178 @node DLL Calling Convention
30179 @subsection @code{DLL} Calling Convention
30180
30181 @noindent
30182 This convention, which is GNAT-specific is fully equivalent to the
30183 @code{Stdcall} calling convention described above.
30184
30185 @node Introduction to Dynamic Link Libraries (DLLs)
30186 @section Introduction to Dynamic Link Libraries (DLLs)
30187 @findex DLL
30188
30189 @noindent
30190 A Dynamically Linked Library (DLL) is a library that can be shared by
30191 several applications running under Windows. A DLL can contain any number of
30192 routines and variables.
30193
30194 One advantage of DLLs is that you can change and enhance them without
30195 forcing all the applications that depend on them to be relinked or
30196 recompiled. However, you should be aware than all calls to DLL routines are
30197 slower since, as you will understand below, such calls are indirect.
30198
30199 To illustrate the remainder of this section, suppose that an application
30200 wants to use the services of a DLL @file{API.dll}. To use the services
30201 provided by @file{API.dll} you must statically link against the DLL or
30202 an import library which contains a jump table with an entry for each
30203 routine and variable exported by the DLL. In the Microsoft world this
30204 import library is called @file{API.lib}. When using GNAT this import
30205 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
30206 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
30207
30208 After you have linked your application with the DLL or the import library
30209 and you run your application, here is what happens:
30210
30211 @enumerate
30212 @item
30213 Your application is loaded into memory.
30214
30215 @item
30216 The DLL @file{API.dll} is mapped into the address space of your
30217 application. This means that:
30218
30219 @itemize @bullet
30220 @item
30221 The DLL will use the stack of the calling thread.
30222
30223 @item
30224 The DLL will use the virtual address space of the calling process.
30225
30226 @item
30227 The DLL will allocate memory from the virtual address space of the calling
30228 process.
30229
30230 @item
30231 Handles (pointers) can be safely exchanged between routines in the DLL
30232 routines and routines in the application using the DLL.
30233 @end itemize
30234
30235 @item
30236 The entries in the jump table (from the import library @file{libAPI.dll.a}
30237 or @file{API.lib} or automatically created when linking against a DLL)
30238 which is part of your application are initialized with the addresses
30239 of the routines and variables in @file{API.dll}.
30240
30241 @item
30242 If present in @file{API.dll}, routines @code{DllMain} or
30243 @code{DllMainCRTStartup} are invoked. These routines typically contain
30244 the initialization code needed for the well-being of the routines and
30245 variables exported by the DLL.
30246 @end enumerate
30247
30248 @noindent
30249 There is an additional point which is worth mentioning. In the Windows
30250 world there are two kind of DLLs: relocatable and non-relocatable
30251 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
30252 in the target application address space. If the addresses of two
30253 non-relocatable DLLs overlap and these happen to be used by the same
30254 application, a conflict will occur and the application will run
30255 incorrectly. Hence, when possible, it is always preferable to use and
30256 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
30257 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
30258 User's Guide) removes the debugging symbols from the DLL but the DLL can
30259 still be relocated.
30260
30261 As a side note, an interesting difference between Microsoft DLLs and
30262 Unix shared libraries, is the fact that on most Unix systems all public
30263 routines are exported by default in a Unix shared library, while under
30264 Windows it is possible (but not required) to list exported routines in
30265 a definition file (@pxref{The Definition File}).
30266
30267 @node Using DLLs with GNAT
30268 @section Using DLLs with GNAT
30269
30270 @menu
30271 * Creating an Ada Spec for the DLL Services::
30272 * Creating an Import Library::
30273 @end menu
30274
30275 @noindent
30276 To use the services of a DLL, say @file{API.dll}, in your Ada application
30277 you must have:
30278
30279 @enumerate
30280 @item
30281 The Ada spec for the routines and/or variables you want to access in
30282 @file{API.dll}. If not available this Ada spec must be built from the C/C++
30283 header files provided with the DLL.
30284
30285 @item
30286 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
30287 mentioned an import library is a statically linked library containing the
30288 import table which will be filled at load time to point to the actual
30289 @file{API.dll} routines. Sometimes you don't have an import library for the
30290 DLL you want to use. The following sections will explain how to build
30291 one. Note that this is optional.
30292
30293 @item
30294 The actual DLL, @file{API.dll}.
30295 @end enumerate
30296
30297 @noindent
30298 Once you have all the above, to compile an Ada application that uses the
30299 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
30300 you simply issue the command
30301
30302 @smallexample
30303 $ gnatmake my_ada_app -largs -lAPI
30304 @end smallexample
30305
30306 @noindent
30307 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
30308 tells the GNAT linker to look first for a library named @file{API.lib}
30309 (Microsoft-style name) and if not found for a libraries named
30310 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
30311 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
30312 contains the following pragma
30313
30314 @smallexample @c ada
30315 pragma Linker_Options ("-lAPI");
30316 @end smallexample
30317
30318 @noindent
30319 you do not have to add @option{-largs -lAPI} at the end of the
30320 @command{gnatmake} command.
30321
30322 If any one of the items above is missing you will have to create it
30323 yourself. The following sections explain how to do so using as an
30324 example a fictitious DLL called @file{API.dll}.
30325
30326 @node Creating an Ada Spec for the DLL Services
30327 @subsection Creating an Ada Spec for the DLL Services
30328
30329 @noindent
30330 A DLL typically comes with a C/C++ header file which provides the
30331 definitions of the routines and variables exported by the DLL. The Ada
30332 equivalent of this header file is a package spec that contains definitions
30333 for the imported entities. If the DLL you intend to use does not come with
30334 an Ada spec you have to generate one such spec yourself. For example if
30335 the header file of @file{API.dll} is a file @file{api.h} containing the
30336 following two definitions:
30337
30338 @smallexample
30339 @group
30340 @cartouche
30341 int some_var;
30342 int get (char *);
30343 @end cartouche
30344 @end group
30345 @end smallexample
30346
30347 @noindent
30348 then the equivalent Ada spec could be:
30349
30350 @smallexample @c ada
30351 @group
30352 @cartouche
30353 with Interfaces.C.Strings;
30354 package API is
30355    use Interfaces;
30356
30357    Some_Var : C.int;
30358    function Get (Str : C.Strings.Chars_Ptr) return C.int;
30359
30360 private
30361    pragma Import (C, Get);
30362    pragma Import (DLL, Some_Var);
30363 end API;
30364 @end cartouche
30365 @end group
30366 @end smallexample
30367
30368 @noindent
30369 Note that a variable is
30370 @strong{always imported with a Stdcall convention}. A function
30371 can have @code{C} or @code{Stdcall} convention.
30372 (@pxref{Windows Calling Conventions}).
30373
30374 @node Creating an Import Library
30375 @subsection Creating an Import Library
30376 @cindex Import library
30377
30378 @menu
30379 * The Definition File::
30380 * GNAT-Style Import Library::
30381 * Microsoft-Style Import Library::
30382 @end menu
30383
30384 @noindent
30385 If a Microsoft-style import library @file{API.lib} or a GNAT-style
30386 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
30387 with @file{API.dll} you can skip this section. You can also skip this
30388 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
30389 as in this case it is possible to link directly against the
30390 DLL. Otherwise read on.
30391
30392 @node The Definition File
30393 @subsubsection The Definition File
30394 @cindex Definition file
30395 @findex .def
30396
30397 @noindent
30398 As previously mentioned, and unlike Unix systems, the list of symbols
30399 that are exported from a DLL must be provided explicitly in Windows.
30400 The main goal of a definition file is precisely that: list the symbols
30401 exported by a DLL. A definition file (usually a file with a @code{.def}
30402 suffix) has the following structure:
30403
30404 @smallexample
30405 @group
30406 @cartouche
30407 [LIBRARY @i{name}]
30408 [DESCRIPTION @i{string}]
30409 EXPORTS
30410    @i{symbol1}
30411    @i{symbol2}
30412    ...
30413 @end cartouche
30414 @end group
30415 @end smallexample
30416
30417 @table @code
30418 @item LIBRARY @i{name}
30419 This section, which is optional, gives the name of the DLL.
30420
30421 @item DESCRIPTION @i{string}
30422 This section, which is optional, gives a description string that will be
30423 embedded in the import library.
30424
30425 @item EXPORTS
30426 This section gives the list of exported symbols (procedures, functions or
30427 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
30428 section of @file{API.def} looks like:
30429
30430 @smallexample
30431 @group
30432 @cartouche
30433 EXPORTS
30434    some_var
30435    get
30436 @end cartouche
30437 @end group
30438 @end smallexample
30439 @end table
30440
30441 @noindent
30442 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
30443 (@pxref{Windows Calling Conventions}) for a Stdcall
30444 calling convention function in the exported symbols list.
30445
30446 @noindent
30447 There can actually be other sections in a definition file, but these
30448 sections are not relevant to the discussion at hand.
30449
30450 @node GNAT-Style Import Library
30451 @subsubsection GNAT-Style Import Library
30452
30453 @noindent
30454 To create a static import library from @file{API.dll} with the GNAT tools
30455 you should proceed as follows:
30456
30457 @enumerate
30458 @item
30459 Create the definition file @file{API.def} (@pxref{The Definition File}).
30460 For that use the @code{dll2def} tool as follows:
30461
30462 @smallexample
30463 $ dll2def API.dll > API.def
30464 @end smallexample
30465
30466 @noindent
30467 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
30468 to standard output the list of entry points in the DLL. Note that if
30469 some routines in the DLL have the @code{Stdcall} convention
30470 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
30471 suffix then you'll have to edit @file{api.def} to add it, and specify
30472 @code{-k} to @code{gnatdll} when creating the import library.
30473
30474 @noindent
30475 Here are some hints to find the right @code{@@}@i{nn} suffix.
30476
30477 @enumerate
30478 @item
30479 If you have the Microsoft import library (.lib), it is possible to get
30480 the right symbols by using Microsoft @code{dumpbin} tool (see the
30481 corresponding Microsoft documentation for further details).
30482
30483 @smallexample
30484 $ dumpbin /exports api.lib
30485 @end smallexample
30486
30487 @item
30488 If you have a message about a missing symbol at link time the compiler
30489 tells you what symbol is expected. You just have to go back to the
30490 definition file and add the right suffix.
30491 @end enumerate
30492
30493 @item
30494 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
30495 (@pxref{Using gnatdll}) as follows:
30496
30497 @smallexample
30498 $ gnatdll -e API.def -d API.dll
30499 @end smallexample
30500
30501 @noindent
30502 @code{gnatdll} takes as input a definition file @file{API.def} and the
30503 name of the DLL containing the services listed in the definition file
30504 @file{API.dll}. The name of the static import library generated is
30505 computed from the name of the definition file as follows: if the
30506 definition file name is @i{xyz}@code{.def}, the import library name will
30507 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
30508 @option{-e} could have been removed because the name of the definition
30509 file (before the ``@code{.def}'' suffix) is the same as the name of the
30510 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
30511 @end enumerate
30512
30513 @node Microsoft-Style Import Library
30514 @subsubsection Microsoft-Style Import Library
30515
30516 @noindent
30517 With GNAT you can either use a GNAT-style or Microsoft-style import
30518 library. A Microsoft import library is needed only if you plan to make an
30519 Ada DLL available to applications developed with Microsoft
30520 tools (@pxref{Mixed-Language Programming on Windows}).
30521
30522 To create a Microsoft-style import library for @file{API.dll} you
30523 should proceed as follows:
30524
30525 @enumerate
30526 @item
30527 Create the definition file @file{API.def} from the DLL. For this use either
30528 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
30529 tool (see the corresponding Microsoft documentation for further details).
30530
30531 @item
30532 Build the actual import library using Microsoft's @code{lib} utility:
30533
30534 @smallexample
30535 $ lib -machine:IX86 -def:API.def -out:API.lib
30536 @end smallexample
30537
30538 @noindent
30539 If you use the above command the definition file @file{API.def} must
30540 contain a line giving the name of the DLL:
30541
30542 @smallexample
30543 LIBRARY      "API"
30544 @end smallexample
30545
30546 @noindent
30547 See the Microsoft documentation for further details about the usage of
30548 @code{lib}.
30549 @end enumerate
30550
30551 @node Building DLLs with GNAT
30552 @section Building DLLs with GNAT
30553 @cindex DLLs, building
30554
30555 @noindent
30556 This section explain how to build DLLs using the GNAT built-in DLL
30557 support. With the following procedure it is straight forward to build
30558 and use DLLs with GNAT.
30559
30560 @enumerate
30561
30562 @item building object files
30563
30564 The first step is to build all objects files that are to be included
30565 into the DLL. This is done by using the standard @command{gnatmake} tool.
30566
30567 @item building the DLL
30568
30569 To build the DLL you must use @command{gcc}'s @code{-shared}
30570 option. It is quite simple to use this method:
30571
30572 @smallexample
30573 $ gcc -shared -o api.dll obj1.o obj2.o ...
30574 @end smallexample
30575
30576 It is important to note that in this case all symbols found in the
30577 object files are automatically exported. It is possible to restrict
30578 the set of symbols to export by passing to @command{gcc} a definition
30579 file, @pxref{The Definition File}. For example:
30580
30581 @smallexample
30582 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
30583 @end smallexample
30584
30585 If you use a definition file you must export the elaboration procedures
30586 for every package that required one. Elaboration procedures are named
30587 using the package name followed by "_E".
30588
30589 @item preparing DLL to be used
30590
30591 For the DLL to be used by client programs the bodies must be hidden
30592 from it and the .ali set with read-only attribute. This is very important
30593 otherwise GNAT will recompile all packages and will not actually use
30594 the code in the DLL. For example:
30595
30596 @smallexample
30597 $ mkdir apilib
30598 $ copy *.ads *.ali api.dll apilib
30599 $ attrib +R apilib\*.ali
30600 @end smallexample
30601
30602 @end enumerate
30603
30604 At this point it is possible to use the DLL by directly linking
30605 against it. Note that you must use the GNAT shared runtime when using
30606 GNAT shared libraries. This is achieved by using @code{-shared} binder's
30607 option.
30608
30609 @smallexample
30610 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30611 @end smallexample
30612
30613 @node Building DLLs with GNAT Project files
30614 @section Building DLLs with GNAT Project files
30615 @cindex DLLs, building
30616
30617 @noindent
30618 There is nothing specific to Windows in the build process.
30619 @pxref{Library Projects}.
30620
30621 @noindent
30622 Due to a system limitation, it is not possible under Windows to create threads
30623 when inside the @code{DllMain} routine which is used for auto-initialization
30624 of shared libraries, so it is not possible to have library level tasks in SALs.
30625
30626 @node Building DLLs with gnatdll
30627 @section Building DLLs with gnatdll
30628 @cindex DLLs, building
30629
30630 @menu
30631 * Limitations When Using Ada DLLs from Ada::
30632 * Exporting Ada Entities::
30633 * Ada DLLs and Elaboration::
30634 * Ada DLLs and Finalization::
30635 * Creating a Spec for Ada DLLs::
30636 * Creating the Definition File::
30637 * Using gnatdll::
30638 @end menu
30639
30640 @noindent
30641 Note that it is preferred to use the built-in GNAT DLL support
30642 (@pxref{Building DLLs with GNAT}) or GNAT Project files
30643 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
30644
30645 This section explains how to build DLLs containing Ada code using
30646 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30647 remainder of this section.
30648
30649 The steps required to build an Ada DLL that is to be used by Ada as well as
30650 non-Ada applications are as follows:
30651
30652 @enumerate
30653 @item
30654 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
30655 @code{Stdcall} calling convention to avoid any Ada name mangling for the
30656 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
30657 skip this step if you plan to use the Ada DLL only from Ada applications.
30658
30659 @item
30660 Your Ada code must export an initialization routine which calls the routine
30661 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
30662 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
30663 routine exported by the Ada DLL must be invoked by the clients of the DLL
30664 to initialize the DLL.
30665
30666 @item
30667 When useful, the DLL should also export a finalization routine which calls
30668 routine @code{adafinal} generated by @command{gnatbind} to perform the
30669 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
30670 The finalization routine exported by the Ada DLL must be invoked by the
30671 clients of the DLL when the DLL services are no further needed.
30672
30673 @item
30674 You must provide a spec for the services exported by the Ada DLL in each
30675 of the programming languages to which you plan to make the DLL available.
30676
30677 @item
30678 You must provide a definition file listing the exported entities
30679 (@pxref{The Definition File}).
30680
30681 @item
30682 Finally you must use @code{gnatdll} to produce the DLL and the import
30683 library (@pxref{Using gnatdll}).
30684 @end enumerate
30685
30686 @noindent
30687 Note that a relocatable DLL stripped using the @code{strip}
30688 binutils tool will not be relocatable anymore. To build a DLL without
30689 debug information pass @code{-largs -s} to @code{gnatdll}. This
30690 restriction does not apply to a DLL built using a Library Project.
30691 @pxref{Library Projects}.
30692
30693 @node Limitations When Using Ada DLLs from Ada
30694 @subsection Limitations When Using Ada DLLs from Ada
30695
30696 @noindent
30697 When using Ada DLLs from Ada applications there is a limitation users
30698 should be aware of. Because on Windows the GNAT run time is not in a DLL of
30699 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30700 each Ada DLL includes the services of the GNAT run time that are necessary
30701 to the Ada code inside the DLL. As a result, when an Ada program uses an
30702 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30703 one in the main program.
30704
30705 It is therefore not possible to exchange GNAT run-time objects between the
30706 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30707 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
30708 types, etc.
30709
30710 It is completely safe to exchange plain elementary, array or record types,
30711 Windows object handles, etc.
30712
30713 @node Exporting Ada Entities
30714 @subsection Exporting Ada Entities
30715 @cindex Export table
30716
30717 @noindent
30718 Building a DLL is a way to encapsulate a set of services usable from any
30719 application. As a result, the Ada entities exported by a DLL should be
30720 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
30721 any Ada name mangling. As an example here is an Ada package
30722 @code{API}, spec and body, exporting two procedures, a function, and a
30723 variable:
30724
30725 @smallexample @c ada
30726 @group
30727 @cartouche
30728 with Interfaces.C; use Interfaces;
30729 package API is
30730    Count : C.int := 0;
30731    function Factorial (Val : C.int) return C.int;
30732
30733    procedure Initialize_API;
30734    procedure Finalize_API;
30735    --  Initialization & Finalization routines. More in the next section.
30736 private
30737    pragma Export (C, Initialize_API);
30738    pragma Export (C, Finalize_API);
30739    pragma Export (C, Count);
30740    pragma Export (C, Factorial);
30741 end API;
30742 @end cartouche
30743 @end group
30744 @end smallexample
30745
30746 @smallexample @c ada
30747 @group
30748 @cartouche
30749 package body API is
30750    function Factorial (Val : C.int) return C.int is
30751       Fact : C.int := 1;
30752    begin
30753       Count := Count + 1;
30754       for K in 1 .. Val loop
30755          Fact := Fact * K;
30756       end loop;
30757       return Fact;
30758    end Factorial;
30759
30760    procedure Initialize_API is
30761       procedure Adainit;
30762       pragma Import (C, Adainit);
30763    begin
30764       Adainit;
30765    end Initialize_API;
30766
30767    procedure Finalize_API is
30768       procedure Adafinal;
30769       pragma Import (C, Adafinal);
30770    begin
30771       Adafinal;
30772    end Finalize_API;
30773 end API;
30774 @end cartouche
30775 @end group
30776 @end smallexample
30777
30778 @noindent
30779 If the Ada DLL you are building will only be used by Ada applications
30780 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
30781 convention. As an example, the previous package could be written as
30782 follows:
30783
30784 @smallexample @c ada
30785 @group
30786 @cartouche
30787 package API is
30788    Count : Integer := 0;
30789    function Factorial (Val : Integer) return Integer;
30790
30791    procedure Initialize_API;
30792    procedure Finalize_API;
30793    --  Initialization and Finalization routines.
30794 end API;
30795 @end cartouche
30796 @end group
30797 @end smallexample
30798
30799 @smallexample @c ada
30800 @group
30801 @cartouche
30802 package body API is
30803    function Factorial (Val : Integer) return Integer is
30804       Fact : Integer := 1;
30805    begin
30806       Count := Count + 1;
30807       for K in 1 .. Val loop
30808          Fact := Fact * K;
30809       end loop;
30810       return Fact;
30811    end Factorial;
30812
30813    ...
30814    --  The remainder of this package body is unchanged.
30815 end API;
30816 @end cartouche
30817 @end group
30818 @end smallexample
30819
30820 @noindent
30821 Note that if you do not export the Ada entities with a @code{C} or
30822 @code{Stdcall} convention you will have to provide the mangled Ada names
30823 in the definition file of the Ada DLL
30824 (@pxref{Creating the Definition File}).
30825
30826 @node Ada DLLs and Elaboration
30827 @subsection Ada DLLs and Elaboration
30828 @cindex DLLs and elaboration
30829
30830 @noindent
30831 The DLL that you are building contains your Ada code as well as all the
30832 routines in the Ada library that are needed by it. The first thing a
30833 user of your DLL must do is elaborate the Ada code
30834 (@pxref{Elaboration Order Handling in GNAT}).
30835
30836 To achieve this you must export an initialization routine
30837 (@code{Initialize_API} in the previous example), which must be invoked
30838 before using any of the DLL services. This elaboration routine must call
30839 the Ada elaboration routine @code{adainit} generated by the GNAT binder
30840 (@pxref{Binding with Non-Ada Main Programs}). See the body of
30841 @code{Initialize_Api} for an example. Note that the GNAT binder is
30842 automatically invoked during the DLL build process by the @code{gnatdll}
30843 tool (@pxref{Using gnatdll}).
30844
30845 When a DLL is loaded, Windows systematically invokes a routine called
30846 @code{DllMain}. It would therefore be possible to call @code{adainit}
30847 directly from @code{DllMain} without having to provide an explicit
30848 initialization routine. Unfortunately, it is not possible to call
30849 @code{adainit} from the @code{DllMain} if your program has library level
30850 tasks because access to the @code{DllMain} entry point is serialized by
30851 the system (that is, only a single thread can execute ``through'' it at a
30852 time), which means that the GNAT run time will deadlock waiting for the
30853 newly created task to complete its initialization.
30854
30855 @node Ada DLLs and Finalization
30856 @subsection Ada DLLs and Finalization
30857 @cindex DLLs and finalization
30858
30859 @noindent
30860 When the services of an Ada DLL are no longer needed, the client code should
30861 invoke the DLL finalization routine, if available. The DLL finalization
30862 routine is in charge of releasing all resources acquired by the DLL. In the
30863 case of the Ada code contained in the DLL, this is achieved by calling
30864 routine @code{adafinal} generated by the GNAT binder
30865 (@pxref{Binding with Non-Ada Main Programs}).
30866 See the body of @code{Finalize_Api} for an
30867 example. As already pointed out the GNAT binder is automatically invoked
30868 during the DLL build process by the @code{gnatdll} tool
30869 (@pxref{Using gnatdll}).
30870
30871 @node Creating a Spec for Ada DLLs
30872 @subsection Creating a Spec for Ada DLLs
30873
30874 @noindent
30875 To use the services exported by the Ada DLL from another programming
30876 language (e.g. C), you have to translate the specs of the exported Ada
30877 entities in that language. For instance in the case of @code{API.dll},
30878 the corresponding C header file could look like:
30879
30880 @smallexample
30881 @group
30882 @cartouche
30883 extern int *_imp__count;
30884 #define count (*_imp__count)
30885 int factorial (int);
30886 @end cartouche
30887 @end group
30888 @end smallexample
30889
30890 @noindent
30891 It is important to understand that when building an Ada DLL to be used by
30892 other Ada applications, you need two different specs for the packages
30893 contained in the DLL: one for building the DLL and the other for using
30894 the DLL. This is because the @code{DLL} calling convention is needed to
30895 use a variable defined in a DLL, but when building the DLL, the variable
30896 must have either the @code{Ada} or @code{C} calling convention. As an
30897 example consider a DLL comprising the following package @code{API}:
30898
30899 @smallexample @c ada
30900 @group
30901 @cartouche
30902 package API is
30903    Count : Integer := 0;
30904    ...
30905    --  Remainder of the package omitted.
30906 end API;
30907 @end cartouche
30908 @end group
30909 @end smallexample
30910
30911 @noindent
30912 After producing a DLL containing package @code{API}, the spec that
30913 must be used to import @code{API.Count} from Ada code outside of the
30914 DLL is:
30915
30916 @smallexample @c ada
30917 @group
30918 @cartouche
30919 package API is
30920    Count : Integer;
30921    pragma Import (DLL, Count);
30922 end API;
30923 @end cartouche
30924 @end group
30925 @end smallexample
30926
30927 @node Creating the Definition File
30928 @subsection Creating the Definition File
30929
30930 @noindent
30931 The definition file is the last file needed to build the DLL. It lists
30932 the exported symbols. As an example, the definition file for a DLL
30933 containing only package @code{API} (where all the entities are exported
30934 with a @code{C} calling convention) is:
30935
30936 @smallexample
30937 @group
30938 @cartouche
30939 EXPORTS
30940     count
30941     factorial
30942     finalize_api
30943     initialize_api
30944 @end cartouche
30945 @end group
30946 @end smallexample
30947
30948 @noindent
30949 If the @code{C} calling convention is missing from package @code{API},
30950 then the definition file contains the mangled Ada names of the above
30951 entities, which in this case are:
30952
30953 @smallexample
30954 @group
30955 @cartouche
30956 EXPORTS
30957     api__count
30958     api__factorial
30959     api__finalize_api
30960     api__initialize_api
30961 @end cartouche
30962 @end group
30963 @end smallexample
30964
30965 @node Using gnatdll
30966 @subsection Using @code{gnatdll}
30967 @findex gnatdll
30968
30969 @menu
30970 * gnatdll Example::
30971 * gnatdll behind the Scenes::
30972 * Using dlltool::
30973 @end menu
30974
30975 @noindent
30976 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
30977 and non-Ada sources that make up your DLL have been compiled.
30978 @code{gnatdll} is actually in charge of two distinct tasks: build the
30979 static import library for the DLL and the actual DLL. The form of the
30980 @code{gnatdll} command is
30981
30982 @smallexample
30983 @cartouche
30984 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
30985 @end cartouche
30986 @end smallexample
30987
30988 @noindent
30989 where @i{list-of-files} is a list of ALI and object files. The object
30990 file list must be the exact list of objects corresponding to the non-Ada
30991 sources whose services are to be included in the DLL. The ALI file list
30992 must be the exact list of ALI files for the corresponding Ada sources
30993 whose services are to be included in the DLL. If @i{list-of-files} is
30994 missing, only the static import library is generated.
30995
30996 @noindent
30997 You may specify any of the following switches to @code{gnatdll}:
30998
30999 @table @code
31000 @item -a[@var{address}]
31001 @cindex @option{-a} (@code{gnatdll})
31002 Build a non-relocatable DLL at @var{address}. If @var{address} is not
31003 specified the default address @var{0x11000000} will be used. By default,
31004 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
31005 advise the reader to build relocatable DLL.
31006
31007 @item -b @var{address}
31008 @cindex @option{-b} (@code{gnatdll})
31009 Set the relocatable DLL base address. By default the address is
31010 @var{0x11000000}.
31011
31012 @item -bargs @var{opts}
31013 @cindex @option{-bargs} (@code{gnatdll})
31014 Binder options. Pass @var{opts} to the binder.
31015
31016 @item -d @var{dllfile}
31017 @cindex @option{-d} (@code{gnatdll})
31018 @var{dllfile} is the name of the DLL. This switch must be present for
31019 @code{gnatdll} to do anything. The name of the generated import library is
31020 obtained algorithmically from @var{dllfile} as shown in the following
31021 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
31022 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
31023 by option @option{-e}) is obtained algorithmically from @var{dllfile}
31024 as shown in the following example:
31025 if @var{dllfile} is @code{xyz.dll}, the definition
31026 file used is @code{xyz.def}.
31027
31028 @item -e @var{deffile}
31029 @cindex @option{-e} (@code{gnatdll})
31030 @var{deffile} is the name of the definition file.
31031
31032 @item -g
31033 @cindex @option{-g} (@code{gnatdll})
31034 Generate debugging information. This information is stored in the object
31035 file and copied from there to the final DLL file by the linker,
31036 where it can be read by the debugger. You must use the
31037 @option{-g} switch if you plan on using the debugger or the symbolic
31038 stack traceback.
31039
31040 @item -h
31041 @cindex @option{-h} (@code{gnatdll})
31042 Help mode. Displays @code{gnatdll} switch usage information.
31043
31044 @item -Idir
31045 @cindex @option{-I} (@code{gnatdll})
31046 Direct @code{gnatdll} to search the @var{dir} directory for source and
31047 object files needed to build the DLL.
31048 (@pxref{Search Paths and the Run-Time Library (RTL)}).
31049
31050 @item -k
31051 @cindex @option{-k} (@code{gnatdll})
31052 Removes the @code{@@}@i{nn} suffix from the import library's exported
31053 names, but keeps them for the link names. You must specify this
31054 option if you want to use a @code{Stdcall} function in a DLL for which
31055 the @code{@@}@i{nn} suffix has been removed. This is the case for most
31056 of the Windows NT DLL for example. This option has no effect when
31057 @option{-n} option is specified.
31058
31059 @item -l @var{file}
31060 @cindex @option{-l} (@code{gnatdll})
31061 The list of ALI and object files used to build the DLL are listed in
31062 @var{file}, instead of being given in the command line. Each line in
31063 @var{file} contains the name of an ALI or object file.
31064
31065 @item -n
31066 @cindex @option{-n} (@code{gnatdll})
31067 No Import. Do not create the import library.
31068
31069 @item -q
31070 @cindex @option{-q} (@code{gnatdll})
31071 Quiet mode. Do not display unnecessary messages.
31072
31073 @item -v
31074 @cindex @option{-v} (@code{gnatdll})
31075 Verbose mode. Display extra information.
31076
31077 @item -largs @var{opts}
31078 @cindex @option{-largs} (@code{gnatdll})
31079 Linker options. Pass @var{opts} to the linker.
31080 @end table
31081
31082 @node gnatdll Example
31083 @subsubsection @code{gnatdll} Example
31084
31085 @noindent
31086 As an example the command to build a relocatable DLL from @file{api.adb}
31087 once @file{api.adb} has been compiled and @file{api.def} created is
31088
31089 @smallexample
31090 $ gnatdll -d api.dll api.ali
31091 @end smallexample
31092
31093 @noindent
31094 The above command creates two files: @file{libapi.dll.a} (the import
31095 library) and @file{api.dll} (the actual DLL). If you want to create
31096 only the DLL, just type:
31097
31098 @smallexample
31099 $ gnatdll -d api.dll -n api.ali
31100 @end smallexample
31101
31102 @noindent
31103 Alternatively if you want to create just the import library, type:
31104
31105 @smallexample
31106 $ gnatdll -d api.dll
31107 @end smallexample
31108
31109 @node gnatdll behind the Scenes
31110 @subsubsection @code{gnatdll} behind the Scenes
31111
31112 @noindent
31113 This section details the steps involved in creating a DLL. @code{gnatdll}
31114 does these steps for you. Unless you are interested in understanding what
31115 goes on behind the scenes, you should skip this section.
31116
31117 We use the previous example of a DLL containing the Ada package @code{API},
31118 to illustrate the steps necessary to build a DLL. The starting point is a
31119 set of objects that will make up the DLL and the corresponding ALI
31120 files. In the case of this example this means that @file{api.o} and
31121 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
31122 the following:
31123
31124 @enumerate
31125 @item
31126 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
31127 the information necessary to generate relocation information for the
31128 DLL.
31129
31130 @smallexample
31131 @group
31132 $ gnatbind -n api
31133 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
31134 @end group
31135 @end smallexample
31136
31137 @noindent
31138 In addition to the base file, the @command{gnatlink} command generates an
31139 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
31140 asks @command{gnatlink} to generate the routines @code{DllMain} and
31141 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
31142 is loaded into memory.
31143
31144 @item
31145 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
31146 export table (@file{api.exp}). The export table contains the relocation
31147 information in a form which can be used during the final link to ensure
31148 that the Windows loader is able to place the DLL anywhere in memory.
31149
31150 @smallexample
31151 @group
31152 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31153           --output-exp api.exp
31154 @end group
31155 @end smallexample
31156
31157 @item
31158 @code{gnatdll} builds the base file using the new export table. Note that
31159 @command{gnatbind} must be called once again since the binder generated file
31160 has been deleted during the previous call to @command{gnatlink}.
31161
31162 @smallexample
31163 @group
31164 $ gnatbind -n api
31165 $ gnatlink api -o api.jnk api.exp -mdll
31166       -Wl,--base-file,api.base
31167 @end group
31168 @end smallexample
31169
31170 @item
31171 @code{gnatdll} builds the new export table using the new base file and
31172 generates the DLL import library @file{libAPI.dll.a}.
31173
31174 @smallexample
31175 @group
31176 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31177           --output-exp api.exp --output-lib libAPI.a
31178 @end group
31179 @end smallexample
31180
31181 @item
31182 Finally @code{gnatdll} builds the relocatable DLL using the final export
31183 table.
31184
31185 @smallexample
31186 @group
31187 $ gnatbind -n api
31188 $ gnatlink api api.exp -o api.dll -mdll
31189 @end group
31190 @end smallexample
31191 @end enumerate
31192
31193 @node Using dlltool
31194 @subsubsection Using @code{dlltool}
31195
31196 @noindent
31197 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
31198 DLLs and static import libraries. This section summarizes the most
31199 common @code{dlltool} switches. The form of the @code{dlltool} command
31200 is
31201
31202 @smallexample
31203 $ dlltool [@var{switches}]
31204 @end smallexample
31205
31206 @noindent
31207 @code{dlltool} switches include:
31208
31209 @table @option
31210 @item --base-file @var{basefile}
31211 @cindex @option{--base-file} (@command{dlltool})
31212 Read the base file @var{basefile} generated by the linker. This switch
31213 is used to create a relocatable DLL.
31214
31215 @item --def @var{deffile}
31216 @cindex @option{--def} (@command{dlltool})
31217 Read the definition file.
31218
31219 @item --dllname @var{name}
31220 @cindex @option{--dllname} (@command{dlltool})
31221 Gives the name of the DLL. This switch is used to embed the name of the
31222 DLL in the static import library generated by @code{dlltool} with switch
31223 @option{--output-lib}.
31224
31225 @item -k
31226 @cindex @option{-k} (@command{dlltool})
31227 Kill @code{@@}@i{nn} from exported names
31228 (@pxref{Windows Calling Conventions}
31229 for a discussion about @code{Stdcall}-style symbols.
31230
31231 @item --help
31232 @cindex @option{--help} (@command{dlltool})
31233 Prints the @code{dlltool} switches with a concise description.
31234
31235 @item --output-exp @var{exportfile}
31236 @cindex @option{--output-exp} (@command{dlltool})
31237 Generate an export file @var{exportfile}. The export file contains the
31238 export table (list of symbols in the DLL) and is used to create the DLL.
31239
31240 @item --output-lib @i{libfile}
31241 @cindex @option{--output-lib} (@command{dlltool})
31242 Generate a static import library @var{libfile}.
31243
31244 @item -v
31245 @cindex @option{-v} (@command{dlltool})
31246 Verbose mode.
31247
31248 @item --as @i{assembler-name}
31249 @cindex @option{--as} (@command{dlltool})
31250 Use @i{assembler-name} as the assembler. The default is @code{as}.
31251 @end table
31252
31253 @node GNAT and Windows Resources
31254 @section GNAT and Windows Resources
31255 @cindex Resources, windows
31256
31257 @menu
31258 * Building Resources::
31259 * Compiling Resources::
31260 * Using Resources::
31261 @end menu
31262
31263 @noindent
31264 Resources are an easy way to add Windows specific objects to your
31265 application. The objects that can be added as resources include:
31266
31267 @itemize @bullet
31268 @item
31269 menus
31270
31271 @item
31272 accelerators
31273
31274 @item
31275 dialog boxes
31276
31277 @item
31278 string tables
31279
31280 @item
31281 bitmaps
31282
31283 @item
31284 cursors
31285
31286 @item
31287 icons
31288
31289 @item
31290 fonts
31291 @end itemize
31292
31293 @noindent
31294 This section explains how to build, compile and use resources.
31295
31296 @node Building Resources
31297 @subsection Building Resources
31298 @cindex Resources, building
31299
31300 @noindent
31301 A resource file is an ASCII file. By convention resource files have an
31302 @file{.rc} extension.
31303 The easiest way to build a resource file is to use Microsoft tools
31304 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
31305 @code{dlgedit.exe} to build dialogs.
31306 It is always possible to build an @file{.rc} file yourself by writing a
31307 resource script.
31308
31309 It is not our objective to explain how to write a resource file. A
31310 complete description of the resource script language can be found in the
31311 Microsoft documentation.
31312
31313 @node Compiling Resources
31314 @subsection Compiling Resources
31315 @findex rc
31316 @findex windres
31317 @cindex Resources, compiling
31318
31319 @noindent
31320 This section describes how to build a GNAT-compatible (COFF) object file
31321 containing the resources. This is done using the Resource Compiler
31322 @code{windres} as follows:
31323
31324 @smallexample
31325 $ windres -i myres.rc -o myres.o
31326 @end smallexample
31327
31328 @noindent
31329 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
31330 file. You can specify an alternate preprocessor (usually named
31331 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
31332 parameter. A list of all possible options may be obtained by entering
31333 the command @code{windres} @option{--help}.
31334
31335 It is also possible to use the Microsoft resource compiler @code{rc.exe}
31336 to produce a @file{.res} file (binary resource file). See the
31337 corresponding Microsoft documentation for further details. In this case
31338 you need to use @code{windres} to translate the @file{.res} file to a
31339 GNAT-compatible object file as follows:
31340
31341 @smallexample
31342 $ windres -i myres.res -o myres.o
31343 @end smallexample
31344
31345 @node Using Resources
31346 @subsection Using Resources
31347 @cindex Resources, using
31348
31349 @noindent
31350 To include the resource file in your program just add the
31351 GNAT-compatible object file for the resource(s) to the linker
31352 arguments. With @command{gnatmake} this is done by using the @option{-largs}
31353 option:
31354
31355 @smallexample
31356 $ gnatmake myprog -largs myres.o
31357 @end smallexample
31358
31359 @node Debugging a DLL
31360 @section Debugging a DLL
31361 @cindex DLL debugging
31362
31363 @menu
31364 * Program and DLL Both Built with GCC/GNAT::
31365 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
31366 @end menu
31367
31368 @noindent
31369 Debugging a DLL is similar to debugging a standard program. But
31370 we have to deal with two different executable parts: the DLL and the
31371 program that uses it. We have the following four possibilities:
31372
31373 @enumerate 1
31374 @item
31375 The program and the DLL are built with @code{GCC/GNAT}.
31376 @item
31377 The program is built with foreign tools and the DLL is built with
31378 @code{GCC/GNAT}.
31379 @item
31380 The program is built with @code{GCC/GNAT} and the DLL is built with
31381 foreign tools.
31382 @item
31383 @end enumerate
31384
31385 @noindent
31386 In this section we address only cases one and two above.
31387 There is no point in trying to debug
31388 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
31389 information in it. To do so you must use a debugger compatible with the
31390 tools suite used to build the DLL.
31391
31392 @node Program and DLL Both Built with GCC/GNAT
31393 @subsection Program and DLL Both Built with GCC/GNAT
31394
31395 @noindent
31396 This is the simplest case. Both the DLL and the program have @code{GDB}
31397 compatible debugging information. It is then possible to break anywhere in
31398 the process. Let's suppose here that the main procedure is named
31399 @code{ada_main} and that in the DLL there is an entry point named
31400 @code{ada_dll}.
31401
31402 @noindent
31403 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
31404 program must have been built with the debugging information (see GNAT -g
31405 switch). Here are the step-by-step instructions for debugging it:
31406
31407 @enumerate 1
31408 @item Launch @code{GDB} on the main program.
31409
31410 @smallexample
31411 $ gdb -nw ada_main
31412 @end smallexample
31413
31414 @item Start the program and stop at the beginning of the main procedure
31415
31416 @smallexample
31417 (gdb) start
31418 @end smallexample
31419
31420 @noindent
31421 This step is required to be able to set a breakpoint inside the DLL. As long
31422 as the program is not run, the DLL is not loaded. This has the
31423 consequence that the DLL debugging information is also not loaded, so it is not
31424 possible to set a breakpoint in the DLL.
31425
31426 @item Set a breakpoint inside the DLL
31427
31428 @smallexample
31429 (gdb) break ada_dll
31430 (gdb) cont
31431 @end smallexample
31432
31433 @end enumerate
31434
31435 @noindent
31436 At this stage a breakpoint is set inside the DLL. From there on
31437 you can use the standard approach to debug the whole program
31438 (@pxref{Running and Debugging Ada Programs}).
31439
31440 @ignore
31441 @c This used to work, probably because the DLLs were non-relocatable
31442 @c keep this section around until the problem is sorted out.
31443
31444 To break on the @code{DllMain} routine it is not possible to follow
31445 the procedure above. At the time the program stop on @code{ada_main}
31446 the @code{DllMain} routine as already been called. Either you can use
31447 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
31448
31449 @enumerate 1
31450 @item Launch @code{GDB} on the main program.
31451
31452 @smallexample
31453 $ gdb ada_main
31454 @end smallexample
31455
31456 @item Load DLL symbols
31457
31458 @smallexample
31459 (gdb) add-sym api.dll
31460 @end smallexample
31461
31462 @item Set a breakpoint inside the DLL
31463
31464 @smallexample
31465 (gdb) break ada_dll.adb:45
31466 @end smallexample
31467
31468 Note that at this point it is not possible to break using the routine symbol
31469 directly as the program is not yet running. The solution is to break
31470 on the proper line (break in @file{ada_dll.adb} line 45).
31471
31472 @item Start the program
31473
31474 @smallexample
31475 (gdb) run
31476 @end smallexample
31477
31478 @end enumerate
31479 @end ignore
31480
31481 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
31482 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
31483
31484 @menu
31485 * Debugging the DLL Directly::
31486 * Attaching to a Running Process::
31487 @end menu
31488
31489 @noindent
31490 In this case things are slightly more complex because it is not possible to
31491 start the main program and then break at the beginning to load the DLL and the
31492 associated DLL debugging information. It is not possible to break at the
31493 beginning of the program because there is no @code{GDB} debugging information,
31494 and therefore there is no direct way of getting initial control. This
31495 section addresses this issue by describing some methods that can be used
31496 to break somewhere in the DLL to debug it.
31497
31498 @noindent
31499 First suppose that the main procedure is named @code{main} (this is for
31500 example some C code built with Microsoft Visual C) and that there is a
31501 DLL named @code{test.dll} containing an Ada entry point named
31502 @code{ada_dll}.
31503
31504 @noindent
31505 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
31506 been built with debugging information (see GNAT -g option).
31507
31508 @node Debugging the DLL Directly
31509 @subsubsection Debugging the DLL Directly
31510
31511 @enumerate 1
31512 @item
31513 Find out the executable starting address
31514
31515 @smallexample
31516 $ objdump --file-header main.exe
31517 @end smallexample
31518
31519 The starting address is reported on the last line. For example:
31520
31521 @smallexample
31522 main.exe:     file format pei-i386
31523 architecture: i386, flags 0x0000010a:
31524 EXEC_P, HAS_DEBUG, D_PAGED
31525 start address 0x00401010
31526 @end smallexample
31527
31528 @item
31529 Launch the debugger on the executable.
31530
31531 @smallexample
31532 $ gdb main.exe
31533 @end smallexample
31534
31535 @item
31536 Set a breakpoint at the starting address, and launch the program.
31537
31538 @smallexample
31539 $ (gdb) break *0x00401010
31540 $ (gdb) run
31541 @end smallexample
31542
31543 The program will stop at the given address.
31544
31545 @item
31546 Set a breakpoint on a DLL subroutine.
31547
31548 @smallexample
31549 (gdb) break ada_dll.adb:45
31550 @end smallexample
31551
31552 Or if you want to break using a symbol on the DLL, you need first to
31553 select the Ada language (language used by the DLL).
31554
31555 @smallexample
31556 (gdb) set language ada
31557 (gdb) break ada_dll
31558 @end smallexample
31559
31560 @item
31561 Continue the program.
31562
31563 @smallexample
31564 (gdb) cont
31565 @end smallexample
31566
31567 @noindent
31568 This will run the program until it reaches the breakpoint that has been
31569 set. From that point you can use the standard way to debug a program
31570 as described in (@pxref{Running and Debugging Ada Programs}).
31571
31572 @end enumerate
31573
31574 @noindent
31575 It is also possible to debug the DLL by attaching to a running process.
31576
31577 @node Attaching to a Running Process
31578 @subsubsection Attaching to a Running Process
31579 @cindex DLL debugging, attach to process
31580
31581 @noindent
31582 With @code{GDB} it is always possible to debug a running process by
31583 attaching to it. It is possible to debug a DLL this way. The limitation
31584 of this approach is that the DLL must run long enough to perform the
31585 attach operation. It may be useful for instance to insert a time wasting
31586 loop in the code of the DLL to meet this criterion.
31587
31588 @enumerate 1
31589
31590 @item Launch the main program @file{main.exe}.
31591
31592 @smallexample
31593 $ main
31594 @end smallexample
31595
31596 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
31597 that the process PID for @file{main.exe} is 208.
31598
31599 @item Launch gdb.
31600
31601 @smallexample
31602 $ gdb
31603 @end smallexample
31604
31605 @item Attach to the running process to be debugged.
31606
31607 @smallexample
31608 (gdb) attach 208
31609 @end smallexample
31610
31611 @item Load the process debugging information.
31612
31613 @smallexample
31614 (gdb) symbol-file main.exe
31615 @end smallexample
31616
31617 @item Break somewhere in the DLL.
31618
31619 @smallexample
31620 (gdb) break ada_dll
31621 @end smallexample
31622
31623 @item Continue process execution.
31624
31625 @smallexample
31626 (gdb) cont
31627 @end smallexample
31628
31629 @end enumerate
31630
31631 @noindent
31632 This last step will resume the process execution, and stop at
31633 the breakpoint we have set. From there you can use the standard
31634 approach to debug a program as described in
31635 (@pxref{Running and Debugging Ada Programs}).
31636
31637 @node Setting Stack Size from gnatlink
31638 @section Setting Stack Size from @command{gnatlink}
31639
31640 @noindent
31641 It is possible to specify the program stack size at link time. On modern
31642 versions of Windows, starting with XP, this is mostly useful to set the size of
31643 the main stack (environment task). The other task stacks are set with pragma
31644 Storage_Size or with the @command{gnatbind -d} command.
31645
31646 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31647 reserve size of individual tasks, the link-time stack size applies to all
31648 tasks, and pragma Storage_Size has no effect.
31649 In particular, Stack Overflow checks are made against this
31650 link-time specified size.
31651
31652 This setting can be done with
31653 @command{gnatlink} using either:
31654
31655 @itemize @bullet
31656
31657 @item using @option{-Xlinker} linker option
31658
31659 @smallexample
31660 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
31661 @end smallexample
31662
31663 This sets the stack reserve size to 0x10000 bytes and the stack commit
31664 size to 0x1000 bytes.
31665
31666 @item using @option{-Wl} linker option
31667
31668 @smallexample
31669 $ gnatlink hello -Wl,--stack=0x1000000
31670 @end smallexample
31671
31672 This sets the stack reserve size to 0x1000000 bytes. Note that with
31673 @option{-Wl} option it is not possible to set the stack commit size
31674 because the coma is a separator for this option.
31675
31676 @end itemize
31677
31678 @node Setting Heap Size from gnatlink
31679 @section Setting Heap Size from @command{gnatlink}
31680
31681 @noindent
31682 Under Windows systems, it is possible to specify the program heap size from
31683 @command{gnatlink} using either:
31684
31685 @itemize @bullet
31686
31687 @item using @option{-Xlinker} linker option
31688
31689 @smallexample
31690 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
31691 @end smallexample
31692
31693 This sets the heap reserve size to 0x10000 bytes and the heap commit
31694 size to 0x1000 bytes.
31695
31696 @item using @option{-Wl} linker option
31697
31698 @smallexample
31699 $ gnatlink hello -Wl,--heap=0x1000000
31700 @end smallexample
31701
31702 This sets the heap reserve size to 0x1000000 bytes. Note that with
31703 @option{-Wl} option it is not possible to set the heap commit size
31704 because the coma is a separator for this option.
31705
31706 @end itemize
31707
31708 @end ifset
31709
31710 @c **********************************
31711 @c * GNU Free Documentation License *
31712 @c **********************************
31713 @include fdl.texi
31714 @c GNU Free Documentation License
31715
31716 @node Index,,GNU Free Documentation License, Top
31717 @unnumbered Index
31718
31719 @printindex cp
31720
31721 @contents
31722 @c Put table of contents at end, otherwise it precedes the "title page" in
31723 @c the .txt version
31724 @c Edit the pdf file to move the contents to the beginning, after the title
31725 @c page
31726
31727 @bye